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.
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