George
George

Reputation: 1032

MYSQL PHP PDO order of statements in a transaction

I am using InnoDB in MySQL and accessing the table from PHP with PDO.

I need to lock the table, do a select and then, depending on the result of that either insert a row or not. Since I want to have the table locked for as short a time as possible, can I do it like this?

prepare select
prepare insert
begin transaction
lock table
execute select
if reservation time is available then execute insert
unlock table
commit

Or do the prepares have to be inside the transaction? Or do they have to be after the lock?

Should the transaction only include the insert, or does that make any difference?

Upvotes: 1

Views: 142

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191729

beginTransaction turns off autocommit mode, so it only affects queries that actually commit changes. This means that prepared statements, SELECT, and even LOCK TABLES are not affected by transactions at all. In fact, if you're only doing a single INSERT there's no need to even use a transaction; you would only need to use them if you wanted to do multiple write queries atomically.

Upvotes: 0

Related Questions