How can you efficiently fetch and store data from multiple database queries in PHP using a foreach loop?
When fetching data from multiple database queries in PHP, it's efficient to use a foreach loop to iterate through the results and store them in an array or another data structure. This allows you to organize and access the data easily, especially when dealing with multiple query results.
// Assume $dbConnection is the database connection object
// Array to store query results
$dataArray = [];
// Array of queries
$queries = ["SELECT * FROM table1", "SELECT * FROM table2"];
// Fetch and store data from each query
foreach ($queries as $query) {
$result = $dbConnection->query($query);
if ($result) {
while ($row = $result->fetch_assoc()) {
$dataArray[] = $row;
}
}
}
// Now $dataArray contains all the fetched data from the queries
Related Questions
- How can external PHP files be utilized to encapsulate language selection logic for better code organization and reusability?
- What are common issues that can arise when installing or updating phpBB2 on a server?
- How can PHP developers effectively troubleshoot issues with preg_match_all not returning expected results?