Home >Backend Development >PHP Tutorial >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());
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; }
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;
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!