Im trying to select an IP address using prepared statements with php, if the IP already exist its everything is ok, but if doesnt exist it does never enter inside the if($stmt -> num_rows === 0)
, it always enter on the else
like if the query is wrong. The field is setted to int unsigned
.
So whats wrong with this prepared statement?
How can make it enter in the if($stmt -> num_rows === 0)
when select
doesnt match anything?
$ip_long= ip2long($ip);
$stmt = $mysqli -> prepare('SELECT INET_NTOA(ip), registry_date FROM users WHERE ip = ?');
if (
$stmt &&
$stmt -> bind_param('i', $ip_long) &&
$stmt -> execute() &&
$stmt -> store_result() &&
$stmt -> bind_result($ip, $registry_date_checker) &&
$stmt -> fetch()
) {
if($stmt -> num_rows === 0) {
//It does never enter here.
}
if($stmt -> num_rows === 1) {
//If exist enter here.
}
}
else{
//If select not found anything it always enter here.
echo "Error mysqli: ".$mysqli-> error; //Returns empty error
echo "Error stmt : ".$stmt -> error; //Returns empty error
echo "Numrows: ".$stmt -> num_rows; //Returns 0
exit;
}
The mysqli_stmt::fetch method returns null
if no rows exist in the resultset. In the boolean context null
is interpreted as false
.
This means if no record is returned by your query, then your first if
will go straight into the else
branch.
I would replace $stmt -> fetch()
with
($stmt -> fetch() ?: true)
in your first if. This will convert the null
value into true
.
You made a typo in your code
Here is it
if($stmt->num_rows() === 0) {
//It does never enter here.
}
elseif($stmt->num_rows() === 1) {
//If exist enter here.
}
New version of mysqli is using num_rows as function not key object.