mysqli num_rows Consistently Returns Zero
Question:
When using MySQLi's prepare, bind_param, num_rows, bind_result, and fetch methods to retrieve rows from a database, why does num_rows always return 0?
Answer:
Incorrect usage of MySQLi calls. To resolve this issue, execute the following steps prior to fetching the number of rows:
$stmt->execute(); $stmt->store_result();
The call to store_result() is essential for mysqli_stmt::num_rows to work correctly.
Here is a revised code snippet with the store_result() call added:
if ($stmt = $mysqli->prepare("SELECT id, title, visible, parent_id FROM content WHERE parent_id = ? ORDER BY page_order ASC;")) { $stmt->bind_param('s', $data->id); $stmt->execute(); $stmt->store_result(); $num_of_rows = $stmt->num_rows; $stmt->bind_result($child_id, $child_title, $child_visible, $child_parent); while ($stmt->fetch()) { // Code here } echo($num_of_rows); $stmt->close(); }
Please refer to the official documentation for mysqli_stmt::num_rows for further details.
The above is the detailed content of Why Does `mysqli_stmt::num_rows` Consistently Return Zero After Using `prepare`, `bind_param`, `bind_result`, and `fetch`?. For more information, please follow other related articles on the PHP Chinese website!