faqts : Computers : Programming : Languages : PHP : Database Backed Sites : MySQL

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

19 of 43 people (44%) answered Yes
Recently 5 of 10 people (50%) answered Yes

Entry

How do you print 2 HTML table columns from 1 select statement?

Jan 29th, 2004 16:10
Philip Olson, Jay Staton, php-general@lists.php.net


The following should print field 'name' in two rows.
 <table>
  <tr>
    <?php
      $i = 0;
      while ($row = mysql_fetch_assoc($result)) {
          echo "\t<td>". $row['name'] ."</td>\n";
          if ($i++ % 2) {
              echo "</tr>\n<tr>\n";
          }
      }
    ?>
  </tr>
 </table>
To read about some PHP related discussion on the modulus operator (%), 
check out this related faqt :
  http://www.faqts.com/knowledge_base/view.phtml/aid/783/
Modulus works nicely for this.  Also consider using a bitwise operator 
as it's actually "faster."  
        if ($i & 1) {
            echo "</tr>\n<tr>\n";
        }
Read a little about bitwise operators here :
  http://java.sun.com/docs/books/tutorial/java/nutsandbolts/bitwise.html
  http://marc.theaimsgroup.com/?l=php-general&s=bitwise
And of course the PHP manual is useful (check user comments too)
  http://www.php.net/manual/language.operators.php
On a related note, let's say you wanted three rows instead of two, then 
you might do something like:
 <table>
  <tr>
    <?php
      $i = 1;
      while ($row = mysql_fetch_assoc($result)) {
          echo "\t<td>". $row['name'] ."</td>\n";
           if (($i++ % 3) == false) {
              echo "</tr>\n<tr>\n";
          }
      }
    ?>
  </tr>
 </table>
And to visualize how this will be seen, something like so:
 1 | 2 | 3
 4 | 5 | 6
 7 | 8 | 9
( keywords: modulas, modulus, alternating, columns, two, three )