且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

选择时没有匹配行的MySQLi Query返回值

更新时间:2023-01-12 22:25:42

来自 MySQLi文档:

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

Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE

因此,基本上,即使查询不返回任何行,它仍然是成功的查询.您应该检查返回的行数.将您的if条件更改为:

So basically, even if query does not return any rows, it is still a successful query. You should rather check for number of rows returned. Change your if condition to:

If ($result->num_rows) {

边注:

  1. 现在是时候使用PHP-MySQL采取正确的初始步骤了.与其使用查询功能,不如使用 Prepared Statements .
  2. 始终使用异常处理(try-catch),以在查询执行期间捕获其他错误.
  1. Now is the right time to take correct initial steps in working with PHP-MySQL. Instead of using query function, you should rather use Prepared Statements.
  2. Always use Exception handling (try-catch), to catch other errors during query execution.

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

Here is the equivalent code using prepared statements and exception handling:

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
}