Home >Database >Mysql Tutorial >How Can I Retrieve Multiple Rows from a MySQL Result Set Using `mysql_fetch_array()` in PHP?

How Can I Retrieve Multiple Rows from a MySQL Result Set Using `mysql_fetch_array()` in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-11-28 21:24:12528browse

How Can I Retrieve Multiple Rows from a MySQL Result Set Using `mysql_fetch_array()` in PHP?

Retrieving Multiple Rows from MySQL Using mysql_fetch_array

In PHP, the mysql_fetch_array function retrieves a single row from a MySQL result set as an associative array. By default, it returns the first row, but it doesn't automatically iterate through multiple rows.

Single-Row Limitation

The following code snippet illustrates the issue you're facing:

$array = mysql_query("SELECT artist FROM directory WHERE artist LIKE 'a%' 
        OR artist LIKE 'b%' 
        OR artist LIKE 'c%'");
$array_result= mysql_fetch_array($array);

In this example, mysql_query() executes the query and returns a resource representing the result set. Subsequently, mysql_fetch_array($array) is called, retrieving the first row and populating the $array_result array.

Iterating Through Rows

To access additional rows, you need to iteratively call mysql_fetch_array() within a loop:

while($data = mysql_fetch_array($array)) {
  // Process $data here, which now holds the current row's data
}

This while loop will continue executing until there are no more rows left in the result set. Inside the loop, you can access the data for the current row using the array's index or key names, such as $data['artist'] or $data[0].

The above is the detailed content of How Can I Retrieve Multiple Rows from a MySQL Result Set Using `mysql_fetch_array()` in PHP?. 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