What potential issues can arise when using PHP to insert data into one table and delete data from another table in a database?

One potential issue that can arise when using PHP to insert data into one table and delete data from another table in a database is the lack of error handling. If the insert operation is successful but the delete operation fails, the database can end up in an inconsistent state. To solve this issue, you can use transactions in PHP to ensure that both operations are either completed successfully or rolled back in case of an error.

<?php

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

// Check connection
if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
}

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

// Insert data into table 1
$insert_query = "INSERT INTO table1 (column1, column2) VALUES ('value1', 'value2')";
$connection->query($insert_query);

// Delete data from table 2
$delete_query = "DELETE FROM table2 WHERE column3 = 'value3'";
$connection->query($delete_query);

// Commit the transaction
$connection->commit();

// Close connection
$connection->close();

?>