tags:

views:

46

answers:

2

Hi everyone,

I need to retrieve data (vehicle details, in this case) from a MySQL table tabled and then loop through the results to generate separate lists for each category of vehicle. Is there a simple way to do this without having to have a SELECT statement for each type of vehicle?

If I were just doing this for one category, I would use the following:

<?php
$sql = "SELECT * FROM apparatus WHERE vehicleType = 'Support';
$getSQL = mysql_query($sql);
?>

<ul>
<?php while ($vehicleData = mysql_fetch_assoc($getSQL)) {?>
<li><?php echo $vehicleData['name'];?></li>
<?php } ?>
</ul>

..etc. Need to do this for four different types of vehicles.

Thanks!

+2  A: 

You could use this:

SELECT * FROM apparatus
WHERE vehicleType IN ('foo', 'bar', 'baz', 'qux')
ORDER BY vehicleType

This will return all four vehicle types, nicely grouped for easy iteration. If you want all the vehicle types, you don't need the WHERE clause.

Mark Byers
Okay, thanks! But one question - how would I then loop through each vehicle type using this SELECT statement?
NightMICU
You don't - you loop through the entire set in one go, and be careful to notice if the vehicle type changes. But I wouldn't bother with this extra complexity unless performance is really a critical issue for you.
Mark Byers
I am trying to generate a UL for each type of vehicle on the same page, in different parts of the page. This would require looping through each matching row in the table for that type of vehicle, as in my example. So, I need to retrieve all details from the table but then organize it in different parts of the page based on the type of vehicle.
NightMICU
+4  A: 

Building on Mark's Answer, you can select all the vehicles, and rearrange your result set in php:

<?php
  $sql = "SELECT * FROM apparatus ORDER BY vehicleType";
  $getSQL = mysql_query($sql);
  // transform the result set:
  $data = array();
  while ($row = mysql_fetch_assoc($getSQL)) {
    $data[$row['vehicleType']][] = $row;    
  }
?>
<?php foreach ($data as $type => $rows): ?>
  <h2><?php echo $type?></h2>
  <ul>
  <?php foreach ($rows as $vehicleData):?>
    <li><?php echo $vehicleData['name'];?></li>
  <?php endforeach ?>
  </ul>
<?php endforeach ?>
gnarf
I had a feeling that an array would be required but I wasn't sure how to implement it. Many thanks :)
NightMICU