PHP MySQLi Lock Tables Query Sometimes Does Not Complete
Gag!  LOCK TABLES is essentially unnecessary if you are using ENGINE=InnoDB.  If you are still using MyISAM, convert!

After converting, you will need to understand how to put things in "transactions" (BEGIN...COMMIT) and use SELECT ... FOR UPDATE.