Note that, with this idea, if a query fails, an Exception must be thrown:
PDO can do that, depending on how you configure it
See PDO::setAttribute
and PDO::ATTR_ERRMODE and PDO::ERRMODE_EXCEPTION
else, with some other API, you might have to test the result of the function used to execute a query, and throw an exception yourself.
You cannot just put an instruction somewhere and have transactions done automatically: you still have to specific which group of queries must be executed in a transaction.
For example, quite often you’ll have a couple of queries before the transaction (before the begin) and another couple of queries after the transaction (after either commit or rollback) and you’ll want those queries executed no matter what happened (or not) in the transaction.
check which storage engine you are using. If it is MyISAM, then Transaction(‘COMMIT’,’ROLLBACK’) will not be supported because only the InnoDB storage engine, not MyISAM, supports transactions.
PHP MySQL transaction example
First, execute the following statement to create the accounts table:
Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.