How can the use of the mysql_num_rows function and for loop be improved when fetching and sending emails to multiple recipients?

When fetching and sending emails to multiple recipients using the mysql_num_rows function and a for loop, the issue arises when the number of rows returned by the query is large. This can lead to performance issues as the for loop iterates through each row to send emails individually. To improve this, you can fetch all the email addresses from the database at once and then loop through the result set to send emails.

// Fetch all email addresses from the database
$query = "SELECT email FROM recipients";
$result = mysqli_query($connection, $query);

// Loop through the result set to send emails
while ($row = mysqli_fetch_assoc($result)) {
    $to = $row['email'];
    $subject = "Your Subject Here";
    $message = "Your Message Here";
    $headers = "From: your@email.com";

    // Send email
    mail($to, $subject, $message, $headers);
}

// Free the result set
mysqli_free_result($result);