"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 > How to efficiently store all MySQL rows into arrays for data operations?

How to efficiently store all MySQL rows into arrays for data operations?

Posted on 2025-04-15
Browse:806

How to Store All MySQL Rows in an Array for Efficient Data Manipulation?

Accessing All Selected MySQL Rows in an Array

When querying data from a MySQL database, you may desire to store all the returned rows conveniently in an array. This provides you with the flexibility to manipulate and access the data more efficiently.

To achieve this, you can leverage the mysql_fetch_array() function, which retrieves a single row as an associative array. However, this method only fetches the first row by default. To access all the rows, you can utilize a while loop:

This loop will iterate through all the rows in the result set and append each row as an item in the $array. Finally, the array is converted to JSON format and echoed back to the browser.

For improved performance and enhanced security, it's recommended to use the MySQLi or MySQL PDO extensions instead of the deprecated mysql_* functions. If you switch to MySQLi, you can use the following code:

The mysqli_fetch_all() function will fetch all the rows in the result set as an array of associative arrays, which is then encoded into JSON and displayed.

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