【问题标题】:php echo if query is empty如果查询为空,则 php 回显
【发布时间】:2016-06-09 12:38:39
【问题描述】:

我正在查询一个数据库,但是当结果为空时,我想输出一个表行,显示“无显示”,但 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>"; 
    }
  }

【问题讨论】:

  • 您是否尝试过 var_dump 的 priorityincidentsR 值?
  • 代码执行后您的表格究竟显示了什么?从理论上讲,如果您的结果由于 while 循环上的条件而没有返回任何行,那么您的 if 语句甚至永远不会运行。如果没有行,则 mysql_fetch_object() 不会被评估为真。如果您根本看不到 if 语句的结果,那么您的查询一定有错误。

标签: php mysql if-statement while-loop


【解决方案1】:

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

【讨论】:

  • 似乎 if 总是评估为真......我怀疑它以某种方式将 0 视为假。
  • 哪一个? mysqli_num_rows() 返回确切的行数,所以 if 总是 true 意味着你总是有数据返回,所以最好检查你的 SQL 查询。
【解决方案2】:

仍然没有弄清楚为什么这对我不起作用,我直接在 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>";
        }
    }

?>

这似乎是一种相当愚蠢的做法,但至少它有效。谢谢大家的帮助。 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-17
    • 1970-01-01
    • 2012-10-10
    • 1970-01-01
    相关资源
    最近更新 更多