//以下代码只能分2列不出错:if ($i%2==1) {
//分3列5列输出不正确:if ($i%5==1) {
//请高手帮忙改正代码:<?
//连接数据库
require_once("config.php");
$db=mysql_connect($db_host,$db_user,$db_passwd) or die('Can not connect to database');
mysql_select_db($db_name) or die('No database');$query="select * from member order by id desc Limit 0,100";
$result=mysql_query($query,$db);$tr_list="";
$i=0;
while ($arr=mysql_fetch_array($result))
{
$i++;
if ($i%5==1) {
$huanhang="<tr>";
$huanhang2="</tr>";
}else {
$huanhang="";
$huanhang2="";
}
$tr_list.=" $huanhang
<td>$arr[name]</td>
$huanhang2";
}
?>
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>输出</title>
</head><body><table border="1" width="100%" id="table1"><?echo$tr_list;?></table></body></html>

解决方案 »

  1.   

    if($i>0 and 0 == $i%5)
    {}
      

  2.   

    逻辑错误的不是一点半点。。
    这样的逻辑,$i=1时,输出的是<tr><td></td></tr>一条记录就一行了。<?php
    $tr_list="";
    $i=0;
    while ($i<=100)
    {
      $last = "</tr>";
      $pre = "<tr>";
      if ($i%5==0) {
       $tr_list.="$pre<td$arr[name]</td>";
      }
      elseif(($i+1)%5==0){
       $tr_list.="<td>$arr[name]</td>$last";
      }
      else{
       $tr_list.="<td>$arr[name]</td>";
      }
    $i++;
    }
    ?>
      

  3.   

    把$i <100换成你的循环
     $arr = mysql_fetch_array($result)
      

  4.   

    改成if ($i%5==0) 就行了吧。0 5 10 15 ... 时才有<tr>..</tr>
    其它时都是<td></td.
      

  5.   

    优化一下:
    <?php
    $tr_list="";
    $i=0;
    $last = "</tr>";
    $pre = "<tr>";
    while ($arr = mysql_fetch_array($result))
    {
      if ($i%5 == 0) {
       $tr_list.="$pre<td>$arr[name]</td>";
      }
      elseif(($i+1)%5 == 0){
       $tr_list.="<td>$arr[name]</td>$last";
      }
      else{
       $tr_list.="<td>$arr[name]</td>";
      }
    $i++;
    }
    ?>
      

  6.   

    echo '<table border=1><tr>';
    $count = 12;//数据总数
    $col = 4;//列数,此处可以设置
    for ($i = 0; $i < $count; $i++){
    echo '<td>'.$i.'</td>';
    if($i%$col == $col-1){
    echo '</tr><tr>';
    }
    }
    if ($count%$col != 0){
    for ($i = 0; $i < $col-$count%$col; $i++){
    echo '<td>&nbsp;</td>';
    }
    echo '</tr>';
    }
    echo '</table>';
      

  7.   


    还真不是。$i=5,10,15的时候,输出的是
    <tr><td>内容</td></tr>,都是一条记录一行,而不是每行5条记录。
      

  8.   

    刚睡觉时想到的,#3的代码忘记考虑,如果总数不能被5整除时,后缀忘记添加</tr>结束符。
    特修改一下,以免误导lz.
    <?php
    $tr_list="";
    $i=0;
    $last = "</tr>";
    $pre = "<tr>";
    while ($arr = mysql_fetch_array($result))
    {
      $last = "</tr>";
      $pre = "<tr>";
      if ($i%5==0) {
       $tr_list.="$pre<td>$arr[name]</td>";
      }
      elseif(($i+1)%5==0){
       $tr_list.="<td>$arr[name]</td>$last";
      }
      else{
       $tr_list.="<td>$arr[name]</td>";
      }
    $i++;
    }
    if(substr($str_list,-5)!='</tr>'){
       $tr_list.="</tr>";
    }
    while($i<25){
       //补齐;
    }
    ?>