Home >Backend Development >PHP Tutorial >Why Does MySQL Fetch Array Only Retrieve the First Row of a Query Result?

Why Does MySQL Fetch Array Only Retrieve the First Row of a Query Result?

Susan Sarandon
Susan SarandonOriginal
2024-10-20 14:31:29988browse

Why Does MySQL Fetch Array Only Retrieve the First Row of a Query Result?

MySQL Fetch Array Retrieves Limited Rows

The code provided aims to retrieve multiple rows from a database using the MySQL extension in PHP. However, it encounters an issue where only the first row is accessible. The query retrieves artists starting with 'a', 'b', or 'c'; however, subsequent attempts to access rows beyond the first result in an undefined offset error.

The reason for this issue lies in the functionality of the mysql_fetch_array function. It returns a single row from the result set as an associative and indexed array. To access multiple rows, the function must be called repeatedly until all rows have been processed.

The following modified code snippet demonstrates how to iterate over all the rows in the result set:

<code class="php">$array = mysql_query("SELECT artist FROM directory WHERE artist LIKE 'a%' 
        OR artist LIKE 'b%' 
        OR artist LIKE 'c%'");

while ($array_result = mysql_fetch_array($array)) {
    echo $array_result[0] . "\n";
    // Additional processing for each row can be performed here.
}</code>

In this code, the while loop continues to call mysql_fetch_array until there are no more rows to retrieve from the result set. This allows the code to process each row as needed.

The above is the detailed content of Why Does MySQL Fetch Array Only Retrieve the First Row of a Query 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