开发者

Put records next to eachother in columns using mysql_fetch_array?

I use mysql_fetch_array to fetch data from a mysql results set:

  while($row = mysql_fetch_array($qry_result)){

Next I would like to place the data into columns in a table, but maximum of two c开发者_如何学Goolumns at each row.

So using a table:

  <table>
   <tr>
      <td>Record Here</td>
      <td>Record Here</td>
   </tr>
   <tr>
      <td>Record Here</td>
      <td>Record Here</td>
   </tr>
   <tr>
      <td colspan="2">Record Here</td>
   </tr>

As you see above, I want to loop the results and create table columns in the loop.

This so that the records line up two and two on a results page.

Remember, if there is an odd number of records, then the last table column would need a colspan of 2, or perhaps just use an empty column?

Anybody know how to do this?

If I use a for loop inside the while loop, I would just be lining up the same records x times for each while loop. Confusing...

Any ideas?

Thanks


Implement a (1-indexed) counter within the while loop. Then add (after the loop):

if ($counter%2)
   echo '<td></td>';

This will leave an additional blank cell in your table if the last column contains only one row.


Something like this should work...

<table>
<?php
while(true) {
    $row1 = mysql_fetch_array($qry_result);
    if($row1 === false) break;
    $row2 = mysql_fetch_array($qry_result);

    if($row2 !== false) {
        echo "<tr><td>$row1</td><td>$row2</td></tr>";
    } else {
        echo "<tr><td coslspan=\"2\">$row1</td></tr>";
        break; // output the final row and then stop looping
    }
}
?>
</table>


<table>
   <tr>
<?
$i=1;
$num = mysql_num_rows($qry_result);
while($row = mysql_fetch_array($qry_result)){
 if($i%2==1)
?>
<tr>
<?
?>
      <td <? if($i==$num && $i%2==1)echo 'colspan="2"';?>><?=$row['keyName']?></td>
<?
 if($i%2==0)
{
<?
</tr>
?>
}

$i++;
}
?>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜