PHP - 打印表时排除空行

时间:2009-07-15 18:06:13

标签: php

以下代码效果很好。它将MySQL数据库中的项目打印为HTML表格。但是,数据库具有第一列(变量“site”)为空的条目。如何让此表排除“site”为空的行/条目?

$result=mysql_query("SHOW TABLES FROM database LIKE '$find'")
or die(mysql_error());


if(mysql_num_rows($result)>0){
while($table=mysql_fetch_row($result)){
print "<p class=\"topic\">$table[0]</p>\n";
$r=mysql_query("SELECT * , itemsa - itemsb AS itemstotal FROM `$table[0]` ORDER BY itemstotal DESC");



print "<table class=\"navbar\">\n";
while($row=mysql_fetch_array($r)){


$itemstotal = $row['itemsa'] - $row['itemsb']; 

print "<tr>";


print "<td class='sitename'>".'<a type="amzn" category="books" class="links2">'.$row['site'].'</a>'."</td>";

print "<td class='class1'>".'<span class="class1_count" id="class1_count'.$row['id'].'">'.number_format($itemstotal).'</span>'."</td>";
print "<td class='selector'>".'<span class="button" id="button'.$row['id'].'">'.'<a href="javascript:;" class="cell1" id="'.$row['id'].'">'.Select.'</a>'.'</span>'."</td>";
}
print "</tr>\n";
}
print "</table>\n";



}
else{
print "";
}

4 个答案:

答案 0 :(得分:7)

在SQL查询中添加where子句。

WHERE `site` <> ''
or
WHERE `site` != ''

应该有用。

但是,如果您希望其他PHP选项的站点为空的行,最好过滤掉PHP中的空白站点,而不是MySQL查询。

答案 1 :(得分:0)

只需在print循环中的while来电之前填写以下内容:

if (trim($row['site']) == '') {
    // skip output of this row if site is empty
    continue;
}

答案 2 :(得分:0)

最简单的解决方案是将以下行插入内部while块:

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

if (!trim($row['site'])) continue; // skip empty rows

$itemstotal = $row['itemsa'] - $row['itemsb'];

编辑:实际上,看起来不需要$itemstotal变量;它被计算为SQL查询中的“虚拟”itemstotal列。如果您将“number_format($itemstotal)”替换为“number_format($row['itemstotal'])”几行,则可以完全摆脱“$itemstotal = ...”行。

答案 3 :(得分:0)

    while($row=mysql_fetch_array($r)){
if($row['site'] != "") {
    $itemstotal = $row['itemsa'] - $row['itemsb']; 
    print "<tr>";
    print "<td class='sitename'>".'<a type="amzn" category="books" class="links2">'.$row['site'].'</a>'."</td>";
    print "<td class='class1'>".'<span class="class1_count" id="class1_count'.$row['id'].'">'.number_format($itemstotal).'</span>'."</td>";
    print "<td class='selector'>".'<span class="button" id="button'.$row['id'].'">'.'<a href="javascript:;" class="cell1" id="'.$row['id'].'">'.Select.'</a>'.'</span>'."</td>";
}
}