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
Patricia ArquetteOriginal
2024-12-03 04:33:12894browse

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;
}

Alternatively, use fetch_all() in PHP 5.3 :

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

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) {

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!

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