Home > Database > Mysql Tutorial > How to Efficiently Retrieve Multiple MySQL Rows into an Array in PHP?

How to Efficiently Retrieve Multiple MySQL Rows into an Array in PHP?

Barbara Streisand
Release: 2024-10-29 07:21:02
Original
1068 people have browsed it

How to Efficiently Retrieve Multiple MySQL Rows into an Array in PHP?

Bulk Retrieval of MySQL Selected Rows into an Array

In PHP, fetching MySQL data often involves the use of mysql_fetch_array() to obtain selected records. However, this method only retrieves a single row at a time. For situations where you need to aggregate all selected rows into an array, alternative approaches exist.

mysql_fetch_assoc()

One alternative to mysql_fetch_array() is mysql_fetch_assoc(). This function retrieves the next row of data and returns it as an associative array, with column names as keys. A loop can be used to iterate through all the rows and populate an array.

<code class="php">$result = mysql_query("SELECT * FROM $tableName");
$rows = array();
while($row = mysql_fetch_assoc($result)){
     $rows[] = $row;
}</code>
Copy after login

mysqli_fetch_all()

For PHP developers who prefer the MySQLi extension over the older mysql_* functions, mysqli_fetch_all() provides a convenient way to retrieve all rows in a result set as an array.

<code class="php">$query = "SELECT * FROM table";
$result = mysqli_query($db, $query);
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);</code>
Copy after login

The MYSQLI_ASSOC parameter specifies that the rows should be returned as associative arrays.

Once populated, the $rows array will contain all the selected records and can be processed further, converted to JSON, or used as needed in your code.

The above is the detailed content of How to Efficiently Retrieve Multiple MySQL Rows into an Array in PHP?. 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