PHP MySQL Grouped Outputs

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
philiprakusen
Forum Newbie
Posts: 1
Joined: Thu Nov 17, 2005 3:53 am

PHP MySQL Grouped Outputs

Post 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
yum-jelly
Forum Commoner
Posts: 98
Joined: Sat Oct 29, 2005 9:16 pm

Post 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
Post Reply