Problem:
In PHP, it's important to retrieve all selected MySQL rows into an array for comprehensive data handling. However, the commonly used mysql_fetch_array function only retrieves one record at a time.
Solution:
To fetch all selected rows into an array, we can utilize a looping mechanism combined with the mysql_fetch_assoc function:
<code class="php">$result = mysql_query("SELECT * FROM $tableName"); $json = array(); while($row = mysql_fetch_assoc($result)) { $json[] = $row; } echo json_encode($json);</code>
This while loop iterates through the result set, extracting each row into an associative array and adding it to the $json array. Finally, we encode the $json array as JSON for convenient processing.
Alternative with MySQLi:
For enhanced performance and security, consider using MySQLi or MySQL PDO. With MySQLi, the following code achieves the same result:
<code class="php">$query = "SELECT * FROM table"; $result = mysqli_query($db, $query); $json = mysqli_fetch_all ($result, MYSQLI_ASSOC); echo json_encode($json );</code>
By leveraging the mysqli_fetch_all function, we directly retrieve all rows into an associative array, simplifying the process even further.
The above is the detailed content of How to Fetch All MySQL Results into an Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!