我有一个php脚本,它将被多次“同时”请求,我还有一个表中的字段,我们称它为persons作为active/inactive的标志。我希望脚本的第一个实例运行时将该字段设置为不活动,以便其他实例在检查该字段时死亡。有人能提供解决方案吗?如何确保此脚本只运行一次?
PHP, PDO, MySQL
提前非常感谢。

最佳答案

脚本应使用锁定读取(如SELECT ... FOR UPDATE)获取事务中的当前标志:

$dbh = new PDO("mysql:dbname=$dbname", $username, $password);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);

$dbh->beginTransaction();

// using SELECT ... FOR UPDATE, MySQL will hold all other connections
// at this point until the lock is released
$qry = $dbh->query('SELECT persons FROM my_table WHERE ... FOR UPDATE');

if ($qry->fetchColumn() == 'active') {
  $dbh->query('UPDATE my_table SET persons = "inactive" WHERE ...');
  $dbh->commit();  // releases lock so others can see they are inactive

  // we are the only active connection
} else {
  $dbh->rollBack();
  // we are inactive
}

关于php - 锁定表如何工作?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14444164/

10-15 11:06