php 如何使用php检查mysql查询是否没有返回结果(未找到记录)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20063068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:50:18  来源:igfitidea点击:

how to check if mysql query return no result(record not found) using php?

phpmysql

提问by user1788736

i am passing images file names via textarea to php script to find information about each image in mysql db .The problem is i am trying to output those image file names that not found in mysql db and inform the user which image file names not found in mysql. my current code fails to output those missing records in db but it correctly outputs information about those images found in db. could any one tell me what i am doing wrong ?

我正在通过 textarea 将图像文件名传递给 php 脚本,以查找有关 mysql db 中每个图像的信息。问题是我试图输出在 mysql db 中找不到的那些图像文件名,并通知用户哪些图像文件名在mysql。我当前的代码无法在 db 中输出那些丢失的记录,但它正确输出了有关在 db 中找到的那些图像的信息。谁能告诉我我做错了什么?

foreach ($lines as $line) {


$line = rtrim($line);


$result = mysqli_query($con,"SELECT ID,name,imgUrl,imgPURL FROM testdb WHERE imgUrl like '%$line'");            



 if (!$result) {
             die('Invalid query: ' . mysql_error());
            }
//echo $result;

  if($result == 0) 
    {

       // image not found, do stuff..
      echo "Not Found Image:".$line; 
    }



while($row = mysqli_fetch_array($result))
  {
  $totalRows++;

  echo "<tr>";
  echo "<td>" . $row['ID'] ."(".$totalRows. ")</td>";
  echo "<td>" . $row['name'] . "</td>";
  echo "<td>" . $row['imgPURL'] . "</td>";
  echo "<td>" . $row['imgUrl'] . "</td>";  echo "</tr>";


}

};

echo "</table>";

echo "<br>totalRows:".$totalRows;

回答by Krish R

You can use mysqli_num_rows()in mysqli

你可以mysqli_num_rows()在mysqli中使用

if(mysqli_num_rows($result) > 0){

    while($row = mysqli_fetch_array($result))
    {
        $totalRows++;

        echo "<tr>";
        echo "<td>" . $row['ID'] ."(".$totalRows. ")</td>";
        echo "<td>" . $row['name'] . "</td>";
        echo "<td>" . $row['imgPURL'] . "</td>";
        echo "<td>" . $row['imgUrl'] . "</td>";  
        echo "</tr>";         
    }
} else {
    echo "<tr><td colspan='4'>Not Found Image:".$line.'</td></tr>';
}

回答by Machavity

You want to use mysqli_num_rows

你想使用mysqli_num_rows

if(mysqli_num_rows($result)) {
   // Do your while loop here
}

回答by esqew

Use mysqli_num_rowsto compare the number of rows in the result set.

使用mysqli_num_rows比较结果集中的行数。