Home > Backend Development > PHP Tutorial > Can You Reuse mysqli_fetch_array() Multiple Times on the Same Result Set?

Can You Reuse mysqli_fetch_array() Multiple Times on the Same Result Set?

Patricia Arquette
Release: 2024-11-02 14:48:03
Original
1040 people have browsed it

Can You Reuse mysqli_fetch_array() Multiple Times on the Same Result Set?

How to Utilize mysqli_fetch_array() Multiple Times on the Same Result

In working with database-driven apps, it's often necessary to iteratively process returned data rows. In MySQL, the mysqli_fetch_array() function plays a crucial role in extracting data from query results. However, a common challenge arises when you attempt to access the same result set multiple times using mysqli_fetch_array(), resulting in unexpected behavior.

The reason for this issue stems from the behavior of mysqli_fetch_array(). Each invocation moves the cursor within the result set to the next row. Consequently, using it twice on the same result will only provide access to the first two rows. To overcome this limitation, we must separate the data manipulation from the output.

1. Capture the Data:

The first step involves extracting all data into an array:

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

Or, using PHP 5.3's fetch_all() method:

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

2. Utilize the Data Multiple Times:

Once captured into an array, you can iterate through it multiple times, ensuring access to all rows:

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

The above is the detailed content of Can You Reuse mysqli_fetch_array() Multiple Times on the Same Result Set?. 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