Understanding the Issue with mysql_fetch_array
A common mistake when using the mysql_fetch_array() function is assuming it returns an array of all rows from a query. However, it only retrieves a single row, causing confusion when trying to access more than the first element.
Explanation of the Code
The provided code attempts to retrieve artists whose names start with 'a', 'b', or 'c'. The query is stored in $array and the first row is fetched into $array_result. However, when trying to access $array_result[1], an "undefined offset" error occurs. This is because mysql_fetch_array() only returns the first row as an array.
Solution: Iterating Over Rows
To obtain all rows from the query, the mysql_fetch_array() function needs to be called multiple times within a loop. For example:
<code class="php">$array = mysql_query("SELECT artist FROM directory WHERE artist LIKE 'a%' OR artist LIKE 'b%' OR artist LIKE 'c%'"); while ($data = mysql_fetch_array($array)) { // Output or process each row data as needed var_dump($data); }</code>
In this example, the loop will retrieve and process each row from the query result, allowing the desired functionality of accessing elements from each row.
The above is the detailed content of When Does \'mysql_fetch_array()\' Really Return an Array of All Query Rows?. For more information, please follow other related articles on the PHP Chinese website!