"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Use `mysqli_fetch_array()` Multiple Times on the Same Resultset?

How Can I Use `mysqli_fetch_array()` Multiple Times on the Same Resultset?

Published on 2024-11-19
Browse:880

How Can I Use `mysqli_fetch_array()` Multiple Times on the Same Resultset?

Using mysqli_fetch_array() Multiple Times

When working with databases using PHP and MySQL, you may encounter a situation where you need to access the same query results more than once using the mysqli_fetch_array() function. However, attempting to use mysqli_fetch_array() on the same resultset multiple times will result in an empty output.

This is because mysqli_fetch_array() fetches and advances the pointer in the resultset. Thus, if you try to fetch the same result again, there will be no data left to retrieve.

To resolve this issue, you should separate data manipulation from output. First, fetch all the data from the database and store it in an array:

$db_res = mysqli_query($db_link, $sql);
$data = [];
while ($row = mysqli_fetch_assoc($db_res)) {
    $data[] = $row;
}

Note: Since PHP 5.3, you can use fetch_all() instead of the explicit loop:

$db_res = mysqli_query($db_link, $sql);
$data = $db_res->fetch_all(MYSQLI_ASSOC);

Once you have stored the data in an array, you can iterate through it as many times as needed:

Top row:

foreach ($data as $row) {
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3