php echo如果查询为空

时间:2016-02-26 10:31:11

标签: php mysql if-statement while-loop

我正在查询数据库,但是当结果为空时,我想输出一个显示“无显示”的表格行,但if似乎总是返回true。

这是我的代码......

$priorityincidentsQ         = mysql_query("SELECT * FROM applications WHERE pi >= ('2') ");
while($priorityincidentsR   = mysql_fetch_object($priorityincidentsQ)) 
  {
    if (empty($priorityincidentsR)) {
      echo "<tr><td class=\"closedcallscell centered\"><b>Nothing to display</b></td></tr>";    
    } else {        
      echo "<tr><td class=\"closedcallscell\"><b>$priorityincidentsR->application_friendly_name</b></td>";
      echo "<td  class=\"closedcallscell table_row_small\"><center>$priorityincidentsR->pi</center></td></tr>"; 
    }
  }

2 个答案:

答案 0 :(得分:4)

使用mysqli_num_rows()检查是否有任何结果:

    $conn = mysqli_connect($host, $user, $password, $database);
    $priorityincidentsQ = mysqli_query($conn, "SELECT * FROM applications WHERE pi >= ('2') ");
    if (mysqli_num_rows($priorityincidentsQ) > 0){
        while ($priorityincidentsR = mysqli_fetch_object($priorityincidentsQ)) {
            echo "<tr><td class=\"closedcallscell\"><b>$priorityincidentsR->application_friendly_name</b></td>";
            echo "<td  class=\"closedcallscell table_row_small\"><center>$priorityincidentsR->pi</center></td></tr>";
        }
    }else{    
        echo "<tr><td class=\"closedcallscell centered\"><b>Nothing to display</b></td></tr>";
    }

是的,最好使用mysqli_*函数代替mysql_*

答案 1 :(得分:0)

仍然没有弄明白为什么这对我不起作用,我在SQL工作台中直接尝试了查询,一切看起来应该如何,我最终解决了这样的问题。

<!-- priority incidents-->
<?php

$priorityincidentsQ         = mysql_query("SELECT * FROM applications WHERE pi >= ('1') ");
while($priorityincidentsR   = mysql_fetch_object($priorityincidentsQ)) 
    {
    echo "<tr><td class=\"closedcallscell\"><b><a href=\"".DIR."?p=$priorityincidentsR->pageID\">$priorityincidentsR->application_friendly_name</a></b></td>";
    echo "<td  class=\"closedcallscell table_row_small\"><center>$priorityincidentsR->pi</center></td></tr>";
    }

?>

<!-- if no incidents-->
<?php

$incidentNumberofRowsQ      = mysql_query("SELECT COUNT(*)numberofrows FROM applications WHERE pi >= ('1') ");
while($incidentNumberofRowsR    = mysql_fetch_object($incidentNumberofRowsQ)) 
    {

        if ($incidentNumberofRowsR->numberofrows == '0')
        {
                echo "<tr><td class=\"closedcallscell centered\"><b>Currently no priority incidents</b></td>";
        }
    }

?>

看起来似乎是一种相当愚蠢的方式,但至少它是有效的。谢谢大家的帮助。 :)