简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM