2016-02-26 51 views
2

我在查询数据库,但是当结果为空时,我想输出一个表格行显示“什么都不显示”,但if似乎总是返回true。php echo如果查询为空

这里是我的代码...

+2

[**'mysql_ *'已弃用,不再包含在PHP中](http://stackoverflow.com/questions/13944956/the-mysql-extension-is-deprecated-and-will-be -removed-在最未来 - 使用 - 库MySQLi)**。 – Ben

+1

你尝试var_dump priorityincidentsR值吗? – rikpg

+0

执行代码后,表格显示的是什么?从理论上讲,如果你的结果因为while循环的条件而没有返回任何行,你的if语句将永远不会运行。如果没有行,那么'mysql_fetch_object()'不会被评估为true。如果您甚至完全看到if语句的结果,那么在查询中必定会有错误。 – shamsup

回答

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_*

+0

仍似乎无法得到这个工作。 – MatthewBryce

+0

有什么不对吗? – mitkosoft

+0

它似乎是如果总是评估为真......我怀疑它以某种方式将0视为假。 – MatthewBryce

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>"; 
     } 
    } 

?> 

看起来似乎是一个相当愚蠢的方式去做,但至少它的作品。感谢所有的帮助。 :)