Home > Backend Development > PHP Tutorial > How to Avoid Empty Arrays When Fetching MySQL Rows Using `mysqli_fetch_row()`?

How to Avoid Empty Arrays When Fetching MySQL Rows Using `mysqli_fetch_row()`?

Patricia Arquette
Release: 2024-12-26 09:34:16
Original
928 people have browsed it

How to Avoid Empty Arrays When Fetching MySQL Rows Using `mysqli_fetch_row()`?

Retrieving Rows from MySQL Result Object Using mysqli

To obtain all rows from a mysqli result object and construct a new array to hold them, the fetch_row() method can be utilized. However, it's crucial to address a syntax error that may lead to an empty array being returned instead of the expected rows.

Problem:

In the provided code snippet, there's an erroneous semicolon at the end of the while loop statement:

while($row = $result->fetch_row());
Copy after login

This semicolon terminates the while loop prematurely, resulting in no execution of the code within the loop.

Solution:

To rectify this issue, simply remove the semicolon to allow the correct execution of the loop:

while($row = $result->fetch_row()) {
    $rows[] = $row;
}
Copy after login

Error Reporting:

Additionally, it's advisable to request MySQLi to report any encountered issues:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$sql = new mysqli($config['host'], $config['user'], $config['pass'], $config['db_name']);

$query = "SELECT domain FROM services";
$result = $sql->query($query);
$rows = [];
while($row = $result->fetch_row()) {
    $rows[] = $row;
}
return $rows;
Copy after login

By adhering to these suggestions, you should be able to successfully retrieve and store all rows from the result object in the $rows array.

The above is the detailed content of How to Avoid Empty Arrays When Fetching MySQL Rows Using `mysqli_fetch_row()`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template