How can I fetch the value of a row only one time?

Discussion in 'PHP' started by Airwalk Enterprise, Inc, Jun 11, 2011.

  1. #1
    So let's say I have a list of ids, each row has a category assigned to it. So there may be 3 rows assigned to apple, 4 to orange, etc.

    At best, I can retreive the rows so I fetch all category names...

    Apple apple apple orange orange orange orange in a while loop.

    How can I fetch each one only once? So that if orange occurs 4 or even 8billion times, it only outputs once. Basically I want to create a list of categories in a while loop.
     
    Airwalk Enterprise, Inc, Jun 11, 2011 IP
  2. niks00789

    niks00789 Well-Known Member

    Messages:
    188
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    110
    #2
    Use distinct keyword in your query instead...

    say the column name of your category is category and say your table name is fruits

    So your query should be :

    
    $sql = "SELECT DISTINCT category FROM fruits";
    
    PHP:
    Now run a while loop and print every entry.. it will be distinct only :)
     
    niks00789, Jun 12, 2011 IP
  3. mpa360

    mpa360 Peon

    Messages:
    14
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    You can use the " Group By "

    dev.mysql.com/tech-resources/articles/debunking-group-by-myths.html
     
    mpa360, Jun 12, 2011 IP
  4. The Webby

    The Webby Peon

    Messages:
    1,852
    Likes Received:
    30
    Best Answers:
    1
    Trophy Points:
    0
    #4
    Group by wont help for his problem, Niks has suggested the perfect solution.
     
    The Webby, Jun 12, 2011 IP
  5. mindblaster

    mindblaster Peon

    Messages:
    77
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    $sql = "SELECT DISTINCT category FROM fruits";
    $result = mysql_fetch_array($sql);
    echo $result['anyfield'];
     
    mindblaster, Jun 28, 2011 IP