Home > Database > Mysql Tutorial > How to Store All MySQL Rows in an Array for Efficient Data Manipulation?

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

Linda Hamilton
Release: 2024-10-29 17:15:02
Original
963 people have browsed it

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:

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

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

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!

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