How can transactions be utilized in PHP to ensure that data is successfully copied from one table to another before deleting it from the original table?

To ensure that data is successfully copied from one table to another before deleting it from the original table, transactions can be used in PHP. By starting a transaction, executing the copy operation, and then committing the transaction only if the copy is successful, data integrity can be maintained.

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

// Copy data from original table to new table
$copyQuery = $pdo->prepare("INSERT INTO new_table SELECT * FROM original_table");
$copySuccess = $copyQuery->execute();

// If copy was successful, delete data from original table
if($copySuccess) {
    $deleteQuery = $pdo->prepare("DELETE FROM original_table");
    $deleteQuery->execute();
    
    // Commit the transaction
    $pdo->commit();
} else {
    // Rollback the transaction if copy was not successful
    $pdo->rollBack();
}