Reputation: 161
I tried to count return rows from a query using prepared statements.
Something like this :
$q = "SELECT name, address, contact FROM members";
$stmt = mysqli_prepare ($dbc, $q);
mysqli_stmt_store_result($stmt);
// Get the number of rows returned:
$rows = mysqli_stmt_num_rows($stmt);
echo $rows;
But always I am getting 0 rows when executing this query. I tested it using mysql client ant then I got 6 returned rows.
can anyone tell me what is the wrong with this?
Thank you.
Upvotes: 0
Views: 5346
Reputation: 23
i was concerned whether your table Members actually had records in it. Anyways try
$rows = mysqli_num_rows($stmt);
//or
$rows = mysql_num_rows($stmt);
This has worked out for me and has returned 5 as there were only 5 records in my table.
Upvotes: 0
Reputation: 46768
You need to call mysqli_stmt_execute
to actually get a result set, before trying to store the results.
$stmt = mysqli_prepare ($dbc, $q);
mysqli_stmt_execute($stmt); // <--------- currently missing!!!
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
Upvotes: 4
Reputation: 111
You need to call execute() on your statement handle, right now you are only preparing the query.
$q = "SELECT name, address, contact FROM members";
$stmt = mysqli_prepare ($dbc, $q);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
// Get the number of rows returned:
$rows = mysqli_stmt_num_rows($stmt);
echo $rows;
Upvotes: 1
Reputation: 90
You have to execute the query
$q = "SELECT name, address, contact FROM members";
if ($stmt = mysqli_prepare ($dbc, $q)) {
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
// Get the number of rows returned:
$rows = mysqli_stmt_num_rows($stmt);
echo $rows;
mysqli_stmt_free_result($stmt);
mysqli_stmt_close($stmt);
}
Upvotes: 3