Home >Backend Development >PHP Tutorial >Why Does `mysqli_stmt::num_rows` Always Return 0?
Why Does My mysqli_stmt::num_rows Always Return 0?
When attempting to retrieve the number of rows returned by an MySQL query using mysqli_stmt::num_rows, users may encounter consistently returning 0, despite the existence of actual results. To address this issue, it is crucial to call the mysqli_stmt::store_result() function prior to num_rows.
The following code illustrates the correct usage:
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 } echo($num_of_rows); $stmt->close(); }
As stated in the official MySQL documentation for mysqli_stmt::num_rows, "[...] The number of rows in a result set can be found by calling the num_rows method. This must be done after calling store_result." By including the mysqli_stmt::store_result() call, the result set is stored in the client, allowing for the accurate determination of the number of rows.
The above is the detailed content of Why Does `mysqli_stmt::num_rows` Always Return 0?. For more information, please follow other related articles on the PHP Chinese website!