after reading tons of threads, tutorials and whatever - I feel like posting here and hope that someone can help me.
I tried out every advice I could get, but it's still not working.
Here is my code :
$prep_stmt = "SELECT id, DATE_FORMAT(added,'%d.%M'), title FROM offers ORDER BY added DESC LIMIT ?, ?;";
$stmt = $mysqli->prepare($prep_stmt);
$stmt->bind_param ('ii',$lowlimit, $page);
$stmt->execute();
$stmt->bind_result($id, $added, $title);
while ($stmt->fetch()) {
... # some random output here
}
$count = $stmt->num_rows;
echo "c -> ". $count;exit;
I always get "c -> 0" ... but there IS output already ... so what am I doing wrong ? :/
You need to call the store_result()
method before accessing the num_rows
property.
From a comment on PHP manual documentation:
If you do not use mysqli_stmt_store_result()
, and immediately 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.
mysqli_stmt_store_result()
saves the result set in memory thus you can immedietly use this function after you both execute the statement AND save the result set.
Your code should look like:
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id, $added, $title);
while ($stmt->fetch()) {
# some random output here...
}
$count = $stmt->num_rows;
Taken from php.net You have to store it first.
$stmt->store_result();
$count = $stmt->num_rows
From the PHP manual, first comment http://fr2.php.net/manual/fr/mysqli-stmt.num-rows.php :
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.
mysqli_stmt_store_result( ) saves the result set in memory thus you
can immedietly use this function after you both execute the statement
AND save the result set.
If you do not save the result set but still want to use this function
you have to actually loop through the result set one row at a time
using mysqli_stmt_fetch( ) before using this function to determine the
number of rows.
A thought though, if you want to determine the number of rows without
storing the result set and after looping through it, why not just
simply keep an internal counter in your loop every time a row is
fetched and save the function call.
In short, this function is only really useful if you save the result
set and want to determine the number of rows before looping through
it, otherwise you can pretty much recreate its use like I suggested.