Home >Backend Development >PHP Tutorial >How to Efficiently Iterate Through MySQLi Result Sets in PHP?
Iterating Over MySQLi Result Sets
In PHP, iterating over the results of a MySQL query can be achieved using the mysqli_query() method.
To loop through the result set of the query select uid from userbase, you can employ the following loop:
$output = mysqli_query($mysqli, "select uid from userbase"); foreach ($output as $row) { echo $row['uid']; }
This loop will correctly fetch and display the uid value for each row in the result set. It utilizes the object-oriented syntax of MySQLi, which is more concise and efficient than the procedural syntax.
Potential Errors
The error you encountered in your code may be caused by the use of fetch_array() with the default behavior of generating a result set that contains both indexed and associative keys (MYSQLI_BOTH). To fix this, you can specify the desired behavior using MYSQLI_ASSOC or MYSQLI_NUM as the second argument to fetch_array().
Alternatively, you can avoid using fetch_array() altogether by using mysqli_query() as an iterable object, eliminating the need to call fetch_array() on each iterated row.
Correcting Iteration
The code you provided also contains an incorrect iteration scheme. The $i variable should be incremented within the loop to access subsequent rows in the result set, which start with index 0.
Therefore, the correct iteration using fetch_array() would be:
$i = 0; $output = mysqli_query($mysqli, "select uid from userbase"); while ($row = $output->fetch_array(MYSQLI_ASSOC)) { echo $row['uid']; $i++; }
The above is the detailed content of How to Efficiently Iterate Through MySQLi Result Sets in PHP?. For more information, please follow other related articles on the PHP Chinese website!