In what situations should transactions be used in PHP programming, especially with regards to database queries?

Transactions should be used in PHP programming when you need to ensure that a series of database queries are executed as a single, atomic unit. This is important in situations where you want to maintain data integrity and ensure that all changes are either committed together or rolled back if an error occurs. Transactions are especially useful when dealing with multiple queries that are dependent on each other and need to be executed together.

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

try {
    // Perform multiple database queries
    $pdo->query("INSERT INTO table1 (column1) VALUES ('value1')");
    $pdo->query("UPDATE table2 SET column2 = 'new_value' WHERE id = 1");
    
    // Commit the transaction if all queries are successful
    $pdo->commit();
} catch (Exception $e) {
    // Roll back the transaction if an error occurs
    $pdo->rollBack();
    echo "Transaction failed: " . $e->getMessage();
}