How can a foreach loop be effectively used to populate an array with data from a database in PHP?
When populating an array with data from a database in PHP, a foreach loop can be effectively used to iterate over the result set and store each row as an element in the array. This allows for easy access to the data and manipulation within the PHP script.
// Assume $db is a PDO object connected to the database
$statement = $db->query("SELECT * FROM table_name");
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$dataArray = array();
foreach ($results as $row) {
$dataArray[] = $row;
}
// $dataArray now contains all rows from the database table
Keywords
Related Questions
- What are some alternative methods to animate images in PHP, especially for beginners?
- What are the potential security risks associated with allowing users to upload images to a PHP website?
- What are some best practices for handling date calculations in PHP, particularly when excluding weekends from the calculation?