Reputation: 33
I am using prepared statement and want to count the row number of the query result set:
/* create a prepared statement */
// Note: mysqli can only use placeholder ? in prepared statement!
$q = "SELECT user_id, first_name, DATE_FORMAT(last_login_time, '%a, %b %e at %l:%i%p') as f_last_login_time, last_login_time FROM users WHERE (email=? AND pass=SHA1(?)) AND active IS NULL";
$stmt = mysqli_prepare($dbc, $q);
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ss", $e, $p);
/* execute query */
$r = mysqli_stmt_execute($stmt);
if (mysqli_num_rows($r) == 1) { // A match was made in the user table
/* bind result variables */
mysqli_stmt_bind_result($stmt, $user_id, $first_name, $f_last_login_time, $last_login_time);
/* fetch value */
// Fetch the result from a prepared statement into the variables bound by mysqli_stmt_bind_result().
mysqli_stmt_fetch($stmt);
Here the if (mysqli_num_rows($r) == 1)
is wrong: mysqli_num_rows() expects parameter 1 to be mysqli_result, object given.
I checked the manual:
Procedural style int mysqli_num_rows ( mysqli_result $result )
Returns the number of rows in the result set.
The behaviour of mysqli_num_rows() depends on whether buffered or unbuffered result sets are being used. For unbuffered result sets, mysqli_num_rows() will not return the correct number of rows until all the rows in the result have been retrieved. Parameters ¶
result
Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().
So how to count row number of the result set if I am using Mysqli prepared statement(procedural style)??
Upvotes: 1
Views: 1891
Reputation: 781731
mysqli_stmt_execute
returns a boolean that indicates whether the query was successful, it doesn't return a mysqli_result
. You need to call mysqli_stmt_get_result
:
$r = mysqli_stmt_execute($stmt);
if ($r) {
$result = mysqli_stmt_get_result($stmt);
if (mysqli_num_rows($result) == 1) {
...
}
}
You can also simply test the result of mysqli_stmt_fetch
. It returns a boolean indicating whether a row was fetched.
$r = mysqli_stmt_execute($stmt);
if (mysqli_stmt_fetch($stmt)) {
...
}
Upvotes: 4