eqiz eqiz - 5 months ago 45
PHP Question

num_rows() always returns 0 when using prepared statements

I've tried looking at every one else's stack overflow with exact error in title, but I still can't figure this out.

I'm using http://andrew-greig.net/portfolio/better_mysqli.htm for mysqli extend because it does make binding items as arrays much easier. I been trying to move over from native mysql to mysqli and I've always had this same issue with tring to find out if there is a result or not.

Here is my current code

$searchSQL = $mysqli->select("SELECT * FROM coreUsers WHERE Username = ? AND Password = ?", $row, array($username, $password));


echo "<br/>---FOUND Valid LOGIN!!</br>";


The output I get is..

object(mysqli_stmt)#2 (10) { ["affected_rows"]=> int(-1) ["insert_id"]=>
int(0) ["num_rows"]=> int(0) ["param_count"]=> int(2) ["field_count"]=> int(19)
["errno"]=> int(0) ["error"]=> string(0) "" ["error_list"]=> array(0) { }
["sqlstate"]=> string(5) "00000" ["id"]=> int(1) }
---FOUND Valid LOGIN!!

so it found the record, if I output the record information it does echo out Username and Password just fine from the row response, but num_rows is always 0. For this I can never get

$rowCount = $searchSQL->num_rows();

to work when trying to see if there are actual results before doing the while loop.


I have no idea why this is marked as a duplicate. The post added refers to "boolean" and that isn't my error. Mine is object given.

if ($searchSQL === false) {
echo "invalid";
} else {
echo "valid";

this code doesn't work (from the post you marked as duplicate) because my response always will return true if you actually would look at the code I'm using from the extend.


As mentioned by @Ghost below the issue I was missing was 1 line of code.

 $rowCount = $stmt->num_rows;

This has to be called BEFORE I can access num_rows() on a prepared statement.