简体   繁体   中英

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="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 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');

You need to store the result using store_result() . Read more here :

So your code should be something like:

<?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;
    }
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM