"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > PHP中如何将MySQL所有结果存入数组?

PHP中如何将MySQL所有结果存入数组?

Posted on 2025-04-18
Browse:495

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:

$result = mysql_query("SELECT * FROM $tableName");

$json = array();
while($row = mysql_fetch_assoc($result)) {
     $json[] = $row;
}

echo json_encode($json);

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:

$query = "SELECT * FROM table";
$result = mysqli_query($db, $query);

$json = mysqli_fetch_all ($result, MYSQLI_ASSOC);
echo json_encode($json );

By leveraging the mysqli_fetch_all function, we directly retrieve all rows into an associative array, simplifying the process even further.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3