What role do transactions play in ensuring data consistency and preventing deadlocks in PHP applications that interact with MySQL databases?

Transactions in PHP applications interacting with MySQL databases are crucial for ensuring data consistency and preventing deadlocks. By using transactions, you can group multiple SQL queries into a single unit of work that either succeeds entirely or fails entirely, ensuring data integrity. Additionally, transactions help prevent deadlocks by allowing you to lock rows or tables only for the duration of the transaction, reducing the likelihood of conflicts with other processes.

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

try {
    // Perform multiple SQL queries within the transaction
    $pdo->query('UPDATE table1 SET column1 = value1');
    $pdo->query('UPDATE table2 SET column2 = value2');

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