How can one effectively retrieve data from a database and store it in an array in PHP?
To effectively retrieve data from a database and store it in an array in PHP, you can use the PDO extension to connect to the database, execute a query to fetch the data, and then loop through the results to store them in an array.
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL query
$stmt = $pdo->prepare("SELECT * FROM my_table");
// Execute the query
$stmt->execute();
// Fetch the results and store them in an array
$data = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
// Print the array
print_r($data);