2016-02-26 108 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>"; 
     } 
    } 

?> 

看起來似乎是一個相當愚蠢的方式去做,但至少它的作品。感謝所有的幫助。 :)