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>
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>
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!