The query is executing normally for a successful database search, but for an unsuccessful search it is still following the successful execution path. Is there a different way to analyze $result for an unsuccessful Mysql database query?
$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
}
Using count()
almost gets you there, except for one small problem. Even if there is no matching password, a single result is still returned, hence count
will not return zero. Instead, you can try using mysqli_num_rows
, which returns the number of records affected by query. In the case of an empty result set, this should return 0, hence the following check should work:
$rowcount = mysqli_num_rows($result);
if ($rowcount == 0) {
// unsuccessful query
}