我有一个简单的表,它响应查询的结果,以及一些PHP,可以改变表中行的颜色(不能使用CSS3,因为我需要它与IE8一起工作)和我所拥有的。然而,在某些情况下,没有任何记录返回。修改代码的最好方法是什么,这样如果没有任何记录要显示,它就说"none"。或者可以通过mysql查询代替.....
<?php $count = 0; do { ?>
<tr>
<?php $count++;?>
<td colspan = "5" class="<?php echo (($count % 2) == 0) ? 'even' : 'odd'; ?>">
<?php echo $row_RecordSet1['result']; ?>
</td>
</tr>
<?php } while ($row_RecordSet1 = mysql_fetch_assoc($RecordSet1)); ?>`
试着坚持你的编码风格,我想这就是我要做的…
<?php $count = 0; ?>
<?php while ($row_RecordSet1 = mysql_fetch_assoc($RecordSet1)) { ?>
<?php $count++;?>
<tr>
<td colspan="5" class="<?php echo (($count % 2) == 0) ? 'even' : 'odd'; ?>"><?php echo $row_RecordSet1['result']; ?></td>
</tr>
<?php } ?>
<?php if ($count == 0) { ?>
<tr>
<td colspan="5">No results found.</td>
</tr>
<?php } ?>
首先,我建议您使用while
循环,您仍然可以维护您的$count
变量。
$count = 0;
while($row_RecordSet1 = mysql_fetch_assoc($RecordSet1)){
//this way, if the recordset is empty -- the loop will never run
++$count;
//your normal processing continues here
}
if($count === 0){
//there was no content or result from the database
echo '<tr><td>None</td></tr>';
}
我相信这应该能解决你的问题。
在显示结果之前,您可以使用mysql_num_rows检查行数(顺便说一句,仔细阅读关于mysql扩展的红色警告!)
if(mysql_num_rows($RecordSet1) == 0) {//no results
//display none
} else {
//display your results
}