What is the best way to fill an array in PHP with data from a MySQL database?
When filling an array in PHP with data from a MySQL database, the best way is to first establish a connection to the database using MySQLi or PDO. Then, execute a query to fetch the data from the database and loop through the results to populate the array. Finally, close the database connection to free up resources.
// Establish a connection to the MySQL database
$connection = new mysqli('localhost', 'username', 'password', 'database_name');
// Check for connection errors
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
// Query to fetch data from the database
$query = "SELECT * FROM table_name";
$result = $connection->query($query);
// Initialize an empty array to store the data
$dataArray = [];
// Loop through the results and populate the array
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$dataArray[] = $row;
}
}
// Close the database connection
$connection->close();
// Use the $dataArray for further processing