Home > Database > Mysql Tutorial > Why Does mysqli_fetch_array() Fail on Repeated Use, and How Can I Fix It?

Why Does mysqli_fetch_array() Fail on Repeated Use, and How Can I Fix It?

Patricia Arquette
Release: 2024-12-03 04:33:12
Original
947 people have browsed it

Why Does mysqli_fetch_array() Fail on Repeated Use, and How Can I Fix It?

Resolving the mysqli_fetch_array() Dilemma

Attempting to use mysqli_fetch_array() multiple times on the same result set can result in data inaccessibility. This arises because mysqli_fetch_array() consumes the result incrementally.

Data Manipulation Separation

To avoid this issue, separate data manipulation from output. Here's an improved approach:

1. Data Selection

$db_res = mysqli_query($db_link, $sql);
$data = array();
while ($row = mysqli_fetch_array($db_res, MYSQLI_ASSOC)) {
    $data[] = $row;
}
Copy after login

Alternatively, use fetch_all() in PHP 5.3 :

$db_res = mysqli_query($db_link, $sql);
$data = $db_res->fetch_all(MYSQLI_ASSOC);
Copy after login

This step retrieves the entire result set into an array, $data.

2. Data Usage

Now, you can iterate over $data multiple times without affecting the result set.

Top Row

foreach ($data as $row) {
Copy after login

The above is the detailed content of Why Does mysqli_fetch_array() Fail on Repeated Use, and How Can I Fix It?. 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