Home >Database >Mysql Tutorial >How Can I Avoid Empty Arrays When Iterating Multiple Times Through `mysqli_fetch_array()` Results?

How Can I Avoid Empty Arrays When Iterating Multiple Times Through `mysqli_fetch_array()` Results?

DDD
DDDOriginal
2024-12-06 17:00:18693browse

How Can I Avoid Empty Arrays When Iterating Multiple Times Through `mysqli_fetch_array()` Results?

Duplicating mysqli_fetch_array() Calls

When working with database results, it's common to require multiple iterations through the data. However, the mysqli_fetch_array() function consumes the result set, making subsequent calls return empty arrays.

Solution: Perform Data Manipulation Before Output

To avoid this issue, separate data manipulation from output by following these steps:

1. Select Data First:

  • Execute the SQL query and store the result in a variable.
  • Use a loop (e.g., while or foreach) with mysqli_fetch_assoc() to retrieve the data from the result.
  • Store the retrieved data in an array ($data).

2. Use Data Repeatedly:

  • Once the data is stored in the $data array, you can use it multiple times for different outputs.

Example Code:

// Select data and store it in an array
$db_res = mysqli_query( $db_link, $sql );
$data = array();
while ($row = mysqli_fetch_assoc($db_res)) {
    $data[] = $row;
}

// Output top row
foreach ($data as $row) {

The above is the detailed content of How Can I Avoid Empty Arrays When Iterating Multiple Times Through `mysqli_fetch_array()` Results?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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