How can the use of foreach loops in PHP scripts impact performance, especially when dealing with database queries?

Using foreach loops in PHP scripts can impact performance when dealing with database queries because each iteration of the loop results in a separate query being executed. This can lead to a large number of queries being sent to the database, causing unnecessary overhead and slowing down the script. To improve performance, it is recommended to fetch all the necessary data from the database in a single query and then iterate over the results using a foreach loop.

// Fetch all data from the database in a single query
$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);

// Check if the query was successful
if($result) {
    // Iterate over the results using a foreach loop
    while($row = mysqli_fetch_assoc($result)) {
        // Process each row of data here
    }
} else {
    echo "Error: " . mysqli_error($connection);
}