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
Release: 2024-10-28 20:05:02
Original
705 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template