Home >Database >Mysql Tutorial >How to Fetch All MySQL Results into an Array in PHP?

How to Fetch All MySQL Results into an Array in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-10-28 20:05:02665browse

How to Fetch All MySQL Results into an Array in PHP?

Fetching All MySQL Results into an Array

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!

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