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>
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>
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>
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!