选择时没有匹配行的MySQLi Query返回值 [英] MySQLi Query return value in case of Select with no matching rows
问题描述
我有一个表bank
,如下所示:
I have a table bank
as follows:
|name|day|time|
|jack| 1 | 2 |
我需要检查name
,day
和time
.现在,即使我更改WHERE
条件参数的值,以致找不到匹配的行,它仍然会打印成功".这有什么问题吗?如果我的代码尝试如下:
I need to check for name
, day
and time
. Now, even if I change values of WHERE
condition parameters, such that no matching rows are found, it still prints "success". What could be wrong here ? Below if my code attempt:
<?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();
?>
推荐答案
来自 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) {
边注:
- 现在是时候使用PHP-MySQL采取正确的初始步骤了.与其使用查询功能,不如使用 Prepared Statements .
- 始终使用异常处理(
try-catch
),以在查询执行期间捕获其他错误.
- 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.
- 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
}
这篇关于选择时没有匹配行的MySQLi Query返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!