My PHP/Mysql script works in stages:
Insert Customer info
Get new customer's ID via mysqli_insert_id(blah)
Insert into ADDRESS using new customer's ID
Insert into PHONE using new customer's ID
Insert into CONTACTS using new customer's ID
My problem is: If something goes wrong with one of the latter insert statements, MYSQL stops and throws an error of course, but the initial Customer INSERT already fired and was successful. Now if we go back and correct the error in the inputs and try to do this all again, we will have multiple partial entries for this Customer.
So Question: Is there a way to test ALL the MySQL Inserts for errors and upon finding none, THEN go ahead and submit them all?
For Example:
Insert Customer info (check for would-be errors; don't actually insert)
Get new customer's ID...
Insert into ADDRESS...(check for would-be errors; don't actually insert)
Insert into PHONE...(check for would-be errors; don't actually insert)
Insert into CONTACTS...(check for would-be errors; don't actually insert)
OK, now that there were no errors thrown and nothing was actually inserted, do all the pre-screened inserts!
Does this exist?
Use MySQL transaction.
A transaction is a sequential group of database manipulation operations, which is performed as if it were one single work unit. In other words, a transaction will never be complete unless each individual operation within the group is successful. If any operation within the transaction fails, the entire transaction will fail.
Practically, you will club many SQL queries into a group and you will execute all of them together as part of a transaction.
Read this tutorial about MySQL transaction
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With