如果结果为空,如何返回无记录的消息?

时间:2017-08-25 16:42:32

标签: php mysqli

我试图让它返回变量代码或在查询返回空时显示消息。请帮我解决这个问题,因为这只显示代码但不显示错误消息,如果为空白。

/Auth/Forbidden

4 个答案:

答案 0 :(得分:1)

使用mysqli_num_rows()计算返回的内容。

 $returnquery = mysqli_query($con,"select coupon_id, code, discount  from   
 oc_coupon where coupon_id = '$code' ");
 $row_cnt = mysqli_num_rows($returnquery); 
 if($row_cnt > 0) {
     while ($show = mysqli_fetch_array($returnquery)) {
        echo "variable is set to  $show['code']"; // quote the identifier
     } 
 } else {
     echo "variable is not set";
 }  

警告!

Little Bobby your script is at risk for SQL Injection Attacks. 了解preparedMySQLi语句。即使escaping the string也不安全!

答案 1 :(得分:0)

这样做

$i=0;
while ($show = mysqli_fetch_array($returnquery)) {
 echo "variable is set to  $show[code]";
$i++;
 }  

if ( $i==0) echo "variable is not set";

//或者正如评论中指出的那样,更“正确”的解决方案是

if($prodquery->num_rows === 0)
    {
        echo 'No results';
    } else {
    while ($show = mysqli_fetch_array($returnquery)) {
     echo "variable is set to  $show[code]";
     } 
}

答案 2 :(得分:0)

while ($show = mysqli_fetch_array($returnquery)) {
    if(mysqli_num_rows($show)) {

       echo "variable is set to  $show[code]";

     } else {
       echo "variable is not set";
     }  
}

答案 3 :(得分:0)

除了任何其他问题之外,让我简单解释一下您的主要逻辑错误。

  

这只显示代码,但不显示错误消息,如果空白

这是因为您正在使用if(isset($show))在代码部分中显示错误消息,如果 isset($show) 评估为true,无法访问

如果您迭代了所有查询结果,或者没有要迭代的结果,则mysqli_fetch_array($returnquery)将返回null。当发生这种情况时,它不再满足你的while循环的延续条件(null计算为false),因此循环的内容将不会被执行,并且你的代码将在循环之后继续。

有各种方法可以修复它。一种方法是在while循环中设置一个变量,然后检查它是否显示任何结果。

while ($show = mysqli_fetch_array($returnquery)) {
    echo "variable is set to  $show[code]";
    $has_results = true;
}
if (!isset($has_results)) {
    echo "variable is not set";
}