【问题标题】:MySQLi Query return value in case of Select with no matching rows [duplicate]如果选择没有匹配的行,MySQLi查询返回值[重复]
【发布时间】:2018-09-13 04:04:02
【问题描述】:

我有一张表bank如下:

|name|day|time|
|jack| 1 |  2 |

我需要检查namedaytime。现在,即使我更改了WHERE 条件参数的值,以至于找不到匹配的行,它仍然会打印“成功”。这里有什么问题?如果我的代码尝试如下:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM `bank` WHERE name='jack' AND day='1' AND time='2'";
$result = $conn->query($sql);

if ($result) 
{
        echo "success";
} 
else 
{
    echo "0 results";
}
$conn->close();
?>

【问题讨论】:

  • 因为您的查询仍然成功,尽管没有给出任何行。所以 $query 对象是一个 mysqli_result 对象
  • 查看我的更新答案stackoverflow.com/a/52306607/2469308 它应该可以帮助您更好地学习! :)

标签: php mysql mysqli


【解决方案1】:

来自MySQLi documentation

失败时返回 FALSE。对于成功的 SELECT、SHOW、DESCRIBE 或 EXPLAIN 查询,mysqli_query() 将返回一个 mysqli_result 对象。对于其他成功的查询 mysqli_query() 将返回 TRUE

所以基本上,即使查询没有返回任何行,它仍然是一个成功的查询。您应该检查返回的行数。将您的 if 条件更改为:

If ($result->num_rows) {

旁注:

  1. 现在是在使用 PHP-MySQL 时采取正确初始步骤的正确时机。与其使用查询功能,不如使用Prepared Statements
  2. 始终使用异常处理 (try-catch) 来捕获查询执行期间的其他错误。

这是使用准备好的语句和异常处理的等效代码:

try {

    // Prepare the query
    $stmt = "SELECT * FROM bank 
             WHERE name = ? 
               AND day = ? 
               AND time = ?";

    // Bind the parameters
    // assuming that your day and time are integer values
    $stmt->bind_param("sii", 'jack', '1', '2');

    // execute the query
    $stmt->execute();

    // Getting results:
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        echo "0 results";
    } else {
        echo "success";

        // reading results
        while($row = $result->fetch_assoc()) {
            $name = $row['name'];
            $day = $row['day'];
            $time = $row['time'];
        }
    }

} catch (Exception $e) {

     // your code to handle in case of exceptions here
     // generally you log error details, 
     //and send out specific error message alerts
}

【讨论】:

    【解决方案2】:

    插入

        if ($result) 
    {
            echo "success";
    } 
    else 
    {
        echo "0 results";
    }
    

    你能试试“mysql_num_rows($result) or mysqli_num_rows($result)”吗

    我们需要检查是否有任何行满足条件,因为我们需要使用 num 行。现在您正在检查查询是否运行,即使条件不正确,查询也会运行,这就是您成功的原因。

    【讨论】:

    • 使用程序风格已经过时(PHP4时代遗留)。始终使用 $result 作为对象来使用面向对象的方法。此外,建议基于 mysql_* 扩展的结果一点也不好。它已从 PHP 7 中完全删除
    猜你喜欢
    • 1970-01-01
    • 2014-01-25
    • 2012-11-02
    • 1970-01-01
    • 2016-06-09
    • 1970-01-01
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多