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:
<code class="php"><?php $result = mysql_query("SELECT * FROM $tableName"); $array = array(); while($row = mysql_fetch_assoc($result)) { $array[] = $row; } echo json_encode($array); ?></code>
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:
<code class="php"><?php $query = "SELECT * FROM table"; $result = mysqli_query($db, $query); $json = mysqli_fetch_all($result, MYSQLI_ASSOC); echo json_encode($json); ?></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.
The above is the detailed content of How to Store All MySQL Rows in an Array for Efficient Data Manipulation?. For more information, please follow other related articles on the PHP Chinese website!