title: Is there a better way to group query results with a loop in PHP?
body: <p>that´s my first question in <strong>stackoverflow</strong>.</p>
  
  <p>I have two MYSQL tables: categories and products. I manage the query results with a while loop in PHP to group every category with its products. It´s the first time I do something so, and I think I made it very "crafty/hardcoded" (Sorry for my English). I think that should be a better way to do this. So, I´d like to ask to professional programmers. Here is my code:</p>
  
  <pre><code> CREATE TABLE IF NOT EXISTS `categories` (
   `id` int(11) NOT NULL auto_increment,
   `name` text NOT NULL,
   PRIMARY KEY  (`id`)
   ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ;
  
  
   CREATE TABLE IF NOT EXISTS `products` (
   `id` int(11) NOT NULL auto_increment,
   `name` text NOT NULL,
   `description` text NOT NULL,
   `category` int(11) NOT NULL,
   `photo` int(11) NOT NULL,
    PRIMARY KEY  (`id`)
   ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=33 ;
  </code></pre>
  
  <p>I have a query that returns products relationed with their category:</p>
  
  <pre><code>SELECT categories.name as category,products.name as product
  FROM categories
  INNER JOIN products ON(categories.id = products.category)
  </code></pre>
  
  <p>With PHP I manage the results to create an unordered list for every category with its products:</p>
  
  <pre><code>&lt;?php
  $category = '';//A control variable
  
  while($row = mysql_fetch_array($query))
  {
      //if its a new category I start a new &lt;ul&gt;
      if($row['category'] != $category)
      {
          //If it´s not the firt category I need to close previous one
          if($category != '')
          {
              echo "&lt;/ul&gt;\n";
          }
          //I start the new &lt;ul&gt;
          echo '&lt;h2&gt;' . $row['category'] . '&lt;/h2&gt;';
          echo '&lt;ul&gt;';
      }
  
      //I create the correspondient &lt;li&gt;
      echo '&lt;li&gt;' . $row['product'] . "&lt;/li&gt;\n";
  
      //Asign the value of actual category for the next time in the loop
      $category = $row['category'];
  
  }
  
  //I neeed to close last &lt;ul&gt;
  echo "&lt;/ul&gt;\n";
  ?&gt;
  </code></pre>
  
  <p>Is there a better way to do this operation?
  Thanks in advance for your answers!</p>