我有一个表bank
如下:
|name|day|time|
|jack| 1 | 2 |
我需要检查name
,day
和time
。现在,即使我更改了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();
?>
答案 0 :(得分:1)
失败时返回FALSE。对于成功的SELECT,SHOW,DESCRIBE或EXPLAIN查询,mysqli_query()将返回mysqli_result对象。对于其他成功的查询,mysqli_query()将返回TRUE
因此,基本上,即使查询不返回任何行,它仍然是成功的查询。您应该检查返回的行数。将您的if
条件更改为:
If ($result->num_rows) {
边注:
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
}
答案 1 :(得分:-1)
装有
if ($result)
{
echo "success";
}
else
{
echo "0 results";
}
您可以尝试使用“ mysql_num_rows($result)
还是mysqli_num_rows($result)
”
我们需要检查是否有满足条件的行,因为我们需要使用num行。现在,您正在检查查询是否运行,即使条件不正确,查询也会运行,这就是您获得成功的原因。