Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of returned rows 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 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?

like image 752
partho Avatar asked Sep 28 '22 18:09

partho


1 Answers

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');
like image 67
Hanky Panky Avatar answered Oct 03 '22 02:10

Hanky Panky