Lock mysql table with php

Script 1.

$query_ = "lock tables test1 as test11 write";
mysql_query($query);
$query_ = "select * from test11";
sleep(20);
$query_ = "unlock tables";
mysql_query($query_);

Script 2.

$query_ = "select * from test1";
$result = mysql_query($query_);

The problem is that if I run the second script when I run the script first. The table is not locked. And I can read any data from it.

I need it to be locked and return an error.

How to do it?

+5
source share
4 answers

You readlock the table with $query_ = "lock tables test1 as test11 read";- this means that other queries can still read it without any problems, something never (relevant link - scroll down to the section on types of locks):

Lock Type Information read:

  • A session containing a lock can read the table (but not write it).
  • READ .
  • READ.

- , , write :

$query_ = "lock tables test1 as test11 write";
+5

, ,

LOCK TABLES test1 WRITE;

script , .

, ...

+7

db.

+2

If the code in the question is the actual code used, there is a typo. The first call to mysql_query () is passed in another variable. You stopped "_" at the end of the variable name. In addition, you have a misconception about what castles do. Locks do not prevent other scripts from accessing data and do not lead to errors. When script 2 tries to access or change data that it is not allowed because of a lock, it will stop and wait for the lock to exit. After script 1 unlocks the table, script 2 continues and exits without problems.

0
source

All Articles