MySQL distinct keyword - How do you retrieve each unique value?

as4s1n

New Member
Messages
174
Reaction score
4
Points
0
I was looking at the distinct keyword in the SQL statement and I was wondering how you would get each individual columns. My guess was this:
PHP:
$sth = $dbh->query("SELECT distinct colName FROM table");
$i=0;
while($row=$sth->fetch()) {
      $colVal.$i = $row[$i];

      echo $colVal.$i;
      $i++;
}

But I'm not sure that is quite right, or there may be a better way I'm just not seeing.
 
Last edited:

descalzo

Grim Squeaker
Community Support
Messages
9,373
Reaction score
326
Points
83
If you have a column named 'city',

$sth = $dbh->query("SELECT distinct city FROM address_book");

will return just a list of city names, one entry per city. If you have five friends from Cairo, you get one entry for Cairo.

There is no information from other columns, since that would not make any sense.
 

as4s1n

New Member
Messages
174
Reaction score
4
Points
0
Yes, but how do you display values onto the page? The way I did it?
 

descalzo

Grim Squeaker
Community Support
Messages
9,373
Reaction score
326
Points
83
while($row=$sth->fetch()) {


echo $row[ 0 ] ;

}
 

as4s1n

New Member
Messages
174
Reaction score
4
Points
0
Oh, that makes sense. Sorry, I thought it was much more complicated.
 
Last edited:

descalzo

Grim Squeaker
Community Support
Messages
9,373
Reaction score
326
Points
83
Yes (guess you should add some <br /> etc formatting).

Each row contains one result.
 
Top