select distinct not working

Status
Not open for further replies.

2stroke

New member
May 29, 2007
48
2
0
I am trying to do something like this in a php script but I can't get it to work when I put distinct in there. What am I doing wrong?

If I run it from the command line it works fine.
mysql> select distinct category from products;

Code:
$query  = "select distinct category from products";
$result = mysql_query($query);

if ($result)
{
  while($row = mysql_fetch_row($result))
   {
    $name     = $row[0];
    $desc      = $row[1];
    $price      = $row[2];
    $category = $row[3];

    echo "Category : $category <br>";
   }
}
 


your php is wong :)
each entry across is a row. So you need this:

Code:
if ( $result ) {
while ( $row=mysql_fetch_row( $result ) ) {
  $name=$row[0];
  echo "Category: $name<br />";
 }
}

Take whatever shortcuts you want in there.
You're only takin the categories in the select part of the statement, so you only have one column in each row. $row[0] will be the only one with any data. And you will get x number of rows each with one column.
 
You can test your output the next time for easier debug. very efficient and I use it all the time.

$query = "select distinct category from products";
$result = mysql_query($query);

if ($result)
{
while($row = mysql_fetch_row($result))
{

echo"<pre>";print_r($row);echo"</pre>";
}
}
 
Status
Not open for further replies.