What are the best practices for handling email sending and database updates simultaneously in PHP?

When handling email sending and database updates simultaneously in PHP, it's important to ensure that the operations are executed efficiently and without conflicts. One way to achieve this is by using transactions to group the email sending and database update operations together, ensuring that they either both succeed or both fail. This helps maintain data integrity and prevents inconsistencies in the system.

// Start a transaction
$pdo->beginTransaction();

try {
    // Perform database update operation
    $pdo->exec("UPDATE table SET column = value WHERE condition");

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

    // Commit the transaction if both operations succeed
    $pdo->commit();

} catch (Exception $e) {
    // Rollback the transaction if an error occurs
    $pdo->rollBack();
    echo "Error: " . $e->getMessage();
}