I am learning OOP PHP with MySQL. I am trying to run a query that should print the number of rows returned. My php code is as below:
$con= mysqli_connect('localhost','root','','dealinte_cms') or die(mysqli_error());
$email="[email protected]";
if($r=$con->prepare("SELECT * FROM user WHERE email=? ")){
$r->bind_param("s",$email);
if(!$r->execute()){
echo mysqli_errno($con);
}
else{
$rowCount=$r->num_rows;
echo $rowCount;
}
}
In my database that email is in 4 rows, So it should print 4, but it shows 0
Whats wrong with my code?
You must store result
$r->store_result();
and that too, before you check for row count. See this note on the Manual page
Please be advised, for people who sometimes miss to read this important Manual entry for this function:
If you do not use mysqli_stmt_store_result( ), and immediatley call this function after executing a prepared statement, this function will usually return 0 as it has no way to know how many rows are in the result set as the result set is not saved in memory yet.
Tip
Since you are learning OOP PHP with mysql, it is important to note that the connection you created to mysql was in procedural style syntax. While in PHP you may get away with that but in many other languages you won't. Why not convert it into OOP syntax now?
$con= new mysqli('localhost', 'my_user', 'my_password', 'my_db');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With