I want to write several queries to DB for saving 5 users. But before saving them all i must be sure about errors. For example, i inserted the first user, and no errors. But after trying to save the second one, there were errors (NOTE: not only duplicating errors). After, i have to cancel all data i saved, and delete the first one from DB. It is bad idea, better to check for errors SOMEHOW, and after save all 3 users...
QUESTION: How to check for errors before inserting data.
NOTE: It is not enough to check wether data exists, because another errors can appear.
Consider wrapping your queries in a transaction.
What you are looking for are transactions. This way, you send all the statements to the server, which are then executed in something that is similar to a sandbox, the server checks for errors and then (if there are none!) it saves the data.
This can be done in MySQL by wrapping your statements in:
BEGIN;
YOUR QUERIES GO HERE
COMMIT;
For more detailed information, you can have a look at this documentation. Take note that not all MySQL engines support transactions.
Have you tried using a transaction to commit all changes to the database at once? Then if any of them fail, all will be rolled back.
You need to use a transaction here for safer insertions into your database.
DB TABLE: users having 3 fields u_id int , u_name varchar, u_email varchar
<?php
$dbh = mysqli_connect("localhost", "db_user", "password", "databse_name");
mysqli_autocommit($dbh, FALSE);
// run query 1
$query1 = "INSERT INTO users (u_name,u_email) VALUES('Abdus Samad1', 'abdul.samad1@...')";
$result = mysqli_query($dbh, $query1);
if ($result !== TRUE) {
mysqli_rollback($dbh); // if error, roll back transaction
}
// run query 2
$query2 = "INSERT INTO users (u_name,u_email) VALUES('Abdus Samad2', abdul.samad2@...)";
$result = mysqli_query($dbh, $query2);
if ($result !== TRUE) {
mysqli_rollback($dbh); // if error, roll back transaction
echo "Error found in one of queries";
}
else{
echo "Success";
}
// assuming no errors, commit transaction
mysqli_commit($dbh);
// close connection
mysqli_close($dbh);
?>