将mysql_num_rows分解为6x4

时间:2011-02-27 11:11:46

标签: php mysql mysql-num-rows

我差不多有下面的代码,我试图在每6个结果后添加</tr><tr>

echo "<table><tr>";

$query="SELECT * WHERE id='$id' ORDER BY date ASC";
$result=mysql_query($query);

if (mysql_num_rows($result) > 0) {
while($rts = mysql_fetch_array($result)){

$cdata1 = $rts['cdata1'];
$cdata2 = $rts['cdata2'];

echo "<td>$cdata1 and $cdata2</td>";

}
}else{
echo "<td>no results</td>";
}
echo "</tr></table>";

1 个答案:

答案 0 :(得分:1)

echo "<table><tr>";

$query="SELECT * WHERE id='$id' ORDER BY date ASC";
$result=mysql_query($query);

$i = 0;

if (mysql_num_rows($result) > 0) {
while($rts = mysql_fetch_array($result)){

$cdata1 = $rts['cdata1'];
$cdata2 = $rts['cdata2'];

echo "<td>$cdata1 and $cdata2</td>";

if(++$i % 6 == 0) {
   echo '</tr><tr>';
}

}
}else{
echo "<td>no results</td>";
}
echo "</tr></table>";

<强> UPD:

什么意思是if(++$i % 6 == 0)代码:

  1. ++$i等于$i = $i + 1;
  2. $i % 6表示$i modulo 6
  3. 如果$ i modulo 6等于0,则回显</tr><tr>
  4. 所以我们可以把它写成:

    $i = $i + 1;
    if($i % 6 == 0) {
       echo '</tr><tr>';
    }
    

    http://php.net/manual/en/internals2.opcodes.mod.php

    http://php.net/manual/en/language.operators.increment.php