How can implementing a transaction in PHP help prevent data inconsistencies when working with MySQL queries?

Implementing a transaction in PHP helps prevent data inconsistencies when working with MySQL queries by ensuring that a group of queries are executed as a single unit. This means that either all queries are successfully executed, or none of them are, preventing partial updates that could lead to data inconsistencies.

// Establish a connection to the database
$connection = new mysqli("localhost", "username", "password", "database");

// Begin a transaction
$connection->begin_transaction();

// Execute multiple queries within the transaction
$query1 = "INSERT INTO table1 (column1) VALUES ('value1')";
$query2 = "UPDATE table2 SET column2 = 'new_value' WHERE condition = 'value'";
$connection->query($query1);
$connection->query($query2);

// Commit the transaction if all queries are successful
$connection->commit();

// Rollback the transaction if any query fails
$connection->rollback();