Home  >  Article  >  Database  >  How to Retrieve All Rows from a MySQL Database into an Array in PHP?

How to Retrieve All Rows from a MySQL Database into an Array in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-10-30 05:19:03825browse

How to Retrieve All Rows from a MySQL Database into an Array in PHP?

Accessing MySQL Data with Structured Arrays

To retrieve all selected rows from a MySQL database into an array, PHP provides various methods.

Using mysql_fetch_array():

<br>$result = mysql_query("SELECT * FROM $tableName");<br>$row = mysql_fetch_array($result);<br>print_r($row);  // Prints the first row as an array<br>

However, mysql_fetch_array() only fetches a single row at a time. To retrieve all rows, use a loop.

Retrieving All Rows with a Loop:

To obtain all rows in an array, utilize a while loop with mysql_fetch_assoc():

<br>$result = mysql_query("SELECT * FROM $tableName");<br>$array = array();</p>
<p>while($row = mysql_fetch_assoc($result)) {</p>
<pre class="brush:php;toolbar:false">$array[] = $row;

}

print_r($array); // Prints all rows in an associative array format

Recommendation: Consider Using MySQLi or MySQL PDO

While the above methods work with the deprecated MySQL API, it's recommended to switch to MySQLi or MySQL PDO for improved performance and security. The syntax for retrieving all rows using these is as follows:

MySQLi:

<br>$query = "SELECT * FROM table";<br>$result = mysqli_query($db, $query);<br>$json = mysqli_fetch_all($result, MYSQLI_ASSOC);<br>echo json_encode($json);  // Outputs an array to JSON format<br>

MySQL PDO:

<br>$statement = $db->query("SELECT * FROM table");<br>$results = $statement->fetchAll(PDO::FETCH_ASSOC);<br>echo json_encode($results);  // Outputs an array to JSON format<br>

The above is the detailed content of How to Retrieve All Rows from a MySQL Database into an Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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