How can the concept of transaction in PHP be utilized to ensure all database operations are executed successfully before committing?

When working with databases in PHP, it's important to ensure that all database operations are executed successfully before committing them to avoid partial updates or data inconsistencies. This can be achieved by using transactions in PHP, which allow you to group multiple database operations into a single unit of work that either all succeed or all fail together.

// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

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

try {
    // Perform multiple database operations
    $pdo->exec("INSERT INTO table1 (column1) VALUES ('value1')");
    $pdo->exec("UPDATE table2 SET column2 = 'new_value' WHERE id = 1");

    // Commit the transaction if all operations succeed
    $pdo->commit();
} catch (PDOException $e) {
    // Rollback the transaction if any operation fails
    $pdo->rollBack();
    echo "Transaction failed: " . $e->getMessage();
}