Home  >  Article  >  Database  >  How Can I Retrieve All Rows from a MySQL Query Using `mysql_fetch_array()`?

How Can I Retrieve All Rows from a MySQL Query Using `mysql_fetch_array()`?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-24 09:52:09334browse

How Can I Retrieve All Rows from a MySQL Query Using `mysql_fetch_array()`?

MySQL Query Returning a Limited Number of Rows with mysql_fetch_array

Initial Query:

Consider the following MySQL query:

SELECT artist FROM directory WHERE artist LIKE 'a%' 
        OR artist LIKE 'b%' 
        OR artist LIKE 'c%'

mysql_fetch_array Behavior:

When the mysql_query() function is executed, a resource representing the result set is returned. Subsequently, the mysql_fetch_array() function is used to retrieve a single row from the result set. By default, it returns an associative array where the column names serve as the keys.

In your code:

$array = mysql_query("...");
$array_result= mysql_fetch_array($array);

You are attempting to access the first element of the array, which corresponds to the first column of the first row. However, the mysql_fetch_array() function only returns a single row in the result set.

Retrieving Multiple Rows:

To obtain all the rows from the result set, you need to continue calling mysql_fetch_array() until no more rows are left. This can be achieved using a while loop:

while($array_result = mysql_fetch_array($array)) {
  echo $array_result['artist'];
}

In this example, the loop will execute until no more rows are returned, and the contents of the artist column will be printed for each row.

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