Number of rows returned in OOP PHP

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 follows:

$con= mysqli_connect('localhost','root','','dealinte_cms') or die(mysqli_error()); $email=" joy1@gmail.com "; 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, this letter consists of 4 lines, so it should print 4, but it shows 0

What is wrong with my code?

+5
source share
2 answers

You must save the result

  $r->store_result(); 

and that too, before , you check the number of rows. See this note on the manual page.

Please note that for those who sometimes overlook this important entry in the manual for this function:

If you do not use mysqli_stmt_store_result () and immediately call this function after executing the prepared statement, this function usually returns 0, because it has no way of knowing how many rows are in the result set, since the result set is not stored in memory.

Tip

Since you are learning OOP PHP with mysql, it is important to note that the connection you created with mysql was in procedural style syntax. Although in PHP you can do without it, in many other languages ​​you won’t. Why not convert it to OOP syntax?

 $con= new mysqli('localhost', 'my_user', 'my_password', 'my_db'); 
+3
source

You need to save the result using store_result() . More details here :

So your code should look something like this:

 <?php $con= mysqli_connect('localhost','root','','dealinte_cms') or die(mysqli_error()); $email=" joy1@gmail.com "; if($r=$con->prepare("SELECT * FROM user WHERE email=? ")){ $r->bind_param("s",$email); if(!$r->execute()){ echo mysqli_errno($con); } else{ $r->store_result(); $rowCount=$r->num_rows; echo $rowCount; } } ?> 
0
source

All Articles