更新时间: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) {
边注:
try-catch
),以在查询执行期间捕获其他错误.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
}