Page 1 of 1

PHP MySQL Grouped Outputs

Posted: Thu Nov 17, 2005 4:28 am
by philiprakusen
Apologies if this a daft question, but I’m an ColdFusion programmer and I have been asked to update a website that has been build with PHP and MySQL.

The client wants a list of products grouped by name, and subgrouped by description, for example:

Name 1
Description 1.1
Description 1.2
Description 1.3

Name 2
Description 2.1
Description 2.2

...


In ColdFusion, the code would be something like:

Code: Select all

<cfoutout query=”products” group=”name”>
   <p>#products.name#
   <cfoutput group=”description”>
      <br>#products.description#
   </cfoutout>
</cfoutput>
The existing code looks like this:

Code: Select all

<?php 
   while($row = mysql_fetch_array($result))
   {
?>

   <?php echo $row["productName"]; ?>
   ...

<?php
   } 
?>
Please would someone let me know how this would be done in PHP?

Thanks in anticipation

Philip

Posted: Thu Nov 17, 2005 7:07 am
by yum-jelly
You can do something like this...

Code: Select all

<? 
    $sql = "SELECT name, description FROM products GROUP BY name, description"; 

    $r = mysql_query ( $sql ); 

    if ( mysql_num_rows ( $r ) > 0 ) 
    { 
        $old = ''; 

        while ( $row = mysql_fetch_assoc ( $r ) ) 
        { 
            if ( $old != $row['name'] ) 
            { 
                echo ( ! empty ( $old ) ? "\r\n" : null ) . $row['name'] . "\r\n\r\n";
                $old = $row['name']; 
            } 

            echo $row['description'] . "\r\n"; 
        } 
    } 

?>

yj