Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.