Jump to content

Display list of cars from MySQL


Unknown98

Recommended Posts

I have a table, with about a hundred cars in it. There's three columns, id, car name, and one for manufacturer. What I'd like to do, is display a table listing all manufacturers and how many cars each has assigned to it. For example, say I have 5 Dodge cars in the table and 7 Fords. I'd like it to look like this:

 

Dodge | 5

Ford | 7

 

etc... for all manufacturers. I think I would have to use some form of COUNT() in my query correct? And would I need a for or while loop?

Link to comment
https://forums.phpfreaks.com/topic/241860-display-list-of-cars-from-mysql/
Share on other sites

$sql="SELECT car_manufacturer, COUNT(*) FROM `car_pool` GROUP BY car_manufacturer";

if ($query=@mysql_query($sql)) {
   if (@mysql_num_rows($query)) {
      while ($req=@mysql_fetch_array($query)) {
         echo $req[0] ."|".$req[1];
      }
   }
}
else {
   die(mysql_error());
}

You don't need sprintf() on that string.

 

$sql = 'SELECT car_manufacturer, COUNT(*) as car_count FROM car_pool GROUP BY car_manufacturer';
$result = mysql_query($sql) or trigger_error($sql . ' has an error<br />' . mysql_error());
if(mysql_num_rows($result) > 0) {
  while($row = mysql_fetch_assoc($result)) {
     echo $row['car_manufacturer'] . ' | ' . $row['car_count'] . '<br />';
  }
}
else {
    echo 'There is NO cars selected!';
}

 

Teynon has a typo, this should work.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.