Home >Backend Development >PHP Tutorial >Why Does `mysqli_num_rows()` Return 0 After `mysqli_stmt::execute()`?

Why Does `mysqli_num_rows()` Return 0 After `mysqli_stmt::execute()`?

Susan Sarandon
Susan SarandonOriginal
2024-12-05 10:53:11360browse

Why Does `mysqli_num_rows()` Return 0 After `mysqli_stmt::execute()`?

Why mysqli_num_rows() Returns 0 in PHP

In MySQLi, executing queries without first fetching results can lead to incorrect row counts. When encountering this issue with mysqli_num_rows(), consider the following:

Code Sample and Explanation

Consider the code snippet below:

$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();

$num_of_rows = $stmt->num_rows; // Error!

$stmt->bind_result($child_id, $child_title, $child_visible, $child_parent);

while ($stmt->fetch()) {
  //...
}

echo($num_of_rows);

In this code, mysqli_num_rows() always returns 0 because the results haven't been fetched yet.

Solution: Use mysqli_stmt::store_result()

Prior to calling mysqli_num_rows(), you need to call mysqli_stmt::store_result() to store the query results in a buffer. This process enables rowCount counting:

$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(); // Fetches results into a memory buffer
$num_of_rows = $stmt->num_rows;

$stmt->bind_result($child_id, $child_title, $child_visible, $child_parent);

while ($stmt->fetch()) {
  //...
}

echo($num_of_rows);

Remember to check the documentation for mysqli_num_rows() as such details are usually mentioned in the description section.

The above is the detailed content of Why Does `mysqli_num_rows()` Return 0 After `mysqli_stmt::execute()`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn