get_result在它应该返回时不会返回false
问题描述:
对于成功的数据库搜索,查询正常执行,但对于不成功的搜索,它仍在跟踪成功的执行路径。有没有不同的方法来分析不成功的Mysql数据库查询$结果?get_result在它应该返回时不会返回false
$query = "SELECT password
FROM consumer
WHERE username = ? ";
//prepare query
if ($stmt = $this->conn->prepare($query)) {
$stmt->bind_param('s', $username);
$stmt->execute();
$result = $stmt->get_result();
if (!is_null($result) && empty($stmt->last_error) && count($result)>0) {
//successful query, going to this every time even when there
//is no row in the database that matches the query
} else {
//unsuccessful query
}
答
使用count()
几乎让你在那里,除了一个小问题。即使没有匹配的密码,单个结果仍会返回,因此count
不会返回零。相反,您可以尝试使用mysqli_num_rows
,它返回受查询影响的记录数。在结果集为空的情况下,这应该返回0,因此应该检查以下检查:
$rowcount = mysqli_num_rows($result);
if ($rowcount == 0) {
// unsuccessful query
}
不会产生'$ result-> num_rows;'更合适。面向对象的风格,而不是程序?我自己是一个PDO家伙,所以只是好奇。 – ArtisticPhoenix
这工作谢谢蒂姆! –