Home >Backend Development >PHP Tutorial >Can mysqli_fetch_array() Be Used Multiple Times on the Same Result?

Can mysqli_fetch_array() Be Used Multiple Times on the Same Result?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-03 03:39:311041browse

Can mysqli_fetch_array() Be Used Multiple Times on the Same Result?

Multiple Applications of mysqli_fetch_array() on the Same Result

Encountering limitations while attempting to utilize mysqli_fetch_array() repeatedly on the same result is a common issue.

Why it Fails

mysqli_fetch_array() is designed to retrieve the next row from a result set, advancing the internal pointer. By using it twice, you move past the end of the data.

Solution: Data Manipulation vs. Output

It is essential to separate data manipulation from output. Instead of fetching and displaying data simultaneously, execute the following steps:

1. Select and Store the Data

Retrieve the data from the database using mysqli_query() and store it in an array:

$db_res = mysqli_query($db_link, $sql);
$data = [];

while($row = mysqli_fetch_assoc($db_res)) {
    $data[] = $row;
}

2. Use the Data Multiple Times

Utilize the stored data as many times as needed:

// Top row
foreach($data as $row) {

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