这是我的代码:
$query = mysql_query("SELECT * FROM books ORDER BY id") or die(mysql_error());
while($row = mysql_fetch_assoc($query)) {
echo $row["bookname"]." - ";
}
如果每行显示5本书,如果行是5或10或15等,则在开头插入一个... ...
由于
答案 0 :(得分:7)
你可以计算你循环的次数(每次增加一个变量)。
比较值模数5.如果结果为0则输出
$rowCounter = 1;
while($row = mysql_fetch_assoc($query)) {
echo $row["bookname"]." - ";
if( $rowCounter % 5 == 0 ) {
echo "<hr />";
}
$rowCounter++;
}
答案 1 :(得分:2)
一种简单的方法是使用计数器增量...并用5来检查它的mod(%)。
所以
if (i % 5 == 0) echo $row["bookname"];
答案 2 :(得分:1)
$query = mysql_query("SELECT * FROM books ORDER BY id") or die(mysql_error());
$counter=1;
while($row = mysql_fetch_assoc($query)) {
echo $row["bookname"]." - ";
if($counter%5==0){echo "<br/>";}
$counter++;
}
答案 3 :(得分:1)
michaels代码的优化版本! :)
$rowCounter = 0;
$possibleHR = array("","","","","<hr/>");
while($row = mysql_fetch_assoc($query)) {
echo $row["bookname"]." - ".$possibleHR[($rowCounter++) % 5];
}
答案 4 :(得分:0)
Michael代码的较短版本:
$rowCounter = 0;
while ($row = mysql_fetch_assoc($query)) {
echo $row["bookname"] . ' - ';
if (++$rowCounter % 5 == 0) {
echo '<br />';
}
}
另一种选择:
$rowCounter = 1; // not sure if this should be 1 or 0
// 1 is correct, check comments
while ($row = mysql_fetch_assoc($query)) {
echo $row["bookname"] . ' - ';
if ($rowCounter++ % 5 == 0) {
echo '<br />';
}
}