iterate a html table of two row and 3 column using one php query

只愿长相守 提交于 2019-12-04 21:38:49

Use modulo operator (%):

http://www.devchunks.com/web-development/using-the-php-modulus-operator/

something like this:

<table>

<?php

$i = 0;
while ( $row = mysql_fetch_array($result) ){
    if ($i % 3 == 0){
        echo '<tr>';
    }
    echo '<td>'.$row['column_name'].'</td>';
    if ($i % 3 == 2){
        echo '</tr>';
    }
    $i++; 
}

//here is a check in case you don't have multiple of 3 rows
if ($i % 3 != 0){
    echo '</tr>';
}

?>

</table>

At its base, you'll need something like this:

<table>
<tr>

<?

$count = 0;
foreach ($row) {
    echo "<td>" . $row["value"] ."</td>";
    $count++;

    if (($count % 3) == 0) && ($count > 0) {
        echo ("</tr><tr>");
    }
}

?>

</tr>
</table>

Start printing out the header of your table, and then begin iterating through the dataset. Keep track of how many you've printed out, and if this is the third one, print the HTML to finish this row and start the next one. (I've used %, so it'll wrap on every third entry, not just the first one)

Well, you could correctly fetch those informations in your sql-query ( just one example that could fit http://en.wikibooks.org/wiki/MySQL/Pivot_table ).

Or simply fetch everything into PHP arrays.

Oldschool: mysql_query() and while( $row = mysql_fetch_array() ) Newchool: PDO ( http://de.php.net/manual/en/book.pdo.php )

Awesome! Thanks a lot. It works for me, Zend. You can try something like this.

   <table width="1024px" border="0" cellspacing="2" cellpadding="2">  
  <?php
      $i = 0;
      foreach ($this->rows as $row )
      {
          $img = IMAGE_PATH . '/' . 'gallery/' . $row->gly_thumbnail;
          if ($i % 3 == 0)
          {
              echo '<tr>';
          }
  ?>
  <td align="center">
    <img src="<?php echo $img; ?>" width="300" height="215"><br/>
    <?php echo $row->gly_title; ?>
  </td>
  <?php        
          if ($i % 3 == 2)
          {
              echo '</tr>';
          }
          $i++; 
      }

      //here is a check in case you don't have multiple of 3 rows
      if ($i % 3 != 0)
      {
          echo '</tr>';
      }

  ?>
</table>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!