Home > Database > Mysql Tutorial > body text

How to Fetch All MySQL Records into an Array Using PHP?

Mary-Kate Olsen
Release: 2024-10-28 16:03:45
Original
701 people have browsed it

How to Fetch All MySQL Records into an Array Using PHP?

Retrieve MySQL Data into an Array

The code snippet provided attempts to use the mysql_fetch_array() function to retrieve selected data from a MySQL table. However, as the PHP manual suggests, this function is prone to limitations and won't fetch all records.

Fetching All Records into an Array

To address this issue, consider using the following alternative approach:

<code class="php">// MySQLi Method
$query = "SELECT * FROM $tableName";
$result = mysqli_query($db, $query);
$json = mysqli_fetch_all($result, MYSQLI_ASSOC);
echo json_encode($json);</code>
Copy after login

In this example, the mysqli_fetch_all() function retrieves all records from the result set and automatically populates an associative array (MYSQLI_ASSOC) for each row.

MySQL PDO Method

Alternatively, you can use MySQL PDO:

<code class="php">// MySQL PDO Method
$stmt = $db->prepare("SELECT * FROM $tableName");
$stmt->execute();
$json = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($json);</code>
Copy after login

Both these approaches will fetch all selected rows into an array, allowing for efficient data retrieval and manipulation.

The above is the detailed content of How to Fetch All MySQL Records into an Array Using 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!