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

DDD
Release: 2024-11-02 08:15:03
Original
490 people have browsed it

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:

<code class="php">$db_res = mysqli_query($db_link, $sql);
$data = [];
while ($row = mysqli_fetch_assoc($db_res)) {
    $data[] = $row;
}</code>
Copy after login

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

<code class="php">$db_res = mysqli_query($db_link, $sql);
$data = $db_res->fetch_all(MYSQLI_ASSOC);</code>
Copy after login

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

Top row:

<code class="php">foreach ($data as $row) {</code>
Copy after login

The above is the detailed content of How Can I Use `mysqli_fetch_array()` Multiple Times on the Same Resultset?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!