简体   繁体   English

如何在php中锁定mysql表

[英]How to lock mysql tables in php

How do I lock mysql tables in php? 如何在php中锁定mysql表? I currently have this code: 我目前有这个代码:

$db->query("LOCK TABLES tbl_othercharge WRITE");
for($x=0;$x<=500; $x++){
    $id = get_max();
    $db->query("INSERT INTO tbl_othercharge SET tblocID = '$id', assessmentID='lock1'");
}

$db->query("UNLOCK TABLES");

Here's the get_max() function, which obviously will fail if the script above executes simultaneously. 这是get_max()函数,如果上面的脚本同时执行,它显然会失败。

 <?php
    function get_max(){
        global $db;
        $max = $db->get_var("SELECT MAX(tblocNumber) FROM tbl_othercharge");
        if($max == null){
            $max = 1;
        }else if($max >= 1){
            $max = $max + 1;
        }
        return 'OC'.$max;
    }
    ?>

I'm trying to test if there are still concurrency problems by executing the same script on 2 browsers. 我试图通过在2个浏览器上执行相同的脚本来测试是否仍然存在并发问题。 The script above inserts 400+ records instead of 999 records. 上面的脚本插入400多条记录而不是999条记录。 How do I properly lock the table while I'm inserting something into it. 我在插入物品时如何正确锁定桌子。

I want to lock the table to prevent something like this to happen: 我想锁定表以防止发生这样的事情: 在此输入图像描述

As you can see the field with the prefix 'OC' on it should have a number which is equal to the auto-increment primary key. 正如您所看到的,前缀为“OC”的字段应该有一个等于自动增量主键的数字。

The only reliable solution is to do an insert with a dummy value, getting the last insert id, and updating the row to the correct value. 唯一可靠的解决方案是使用虚拟值执行插入,获取最后一个插入ID,并将行更新为正确的值。

mysql_query("INSERT INTO table (field) VALUES (dummy);");
$id = mysql_last_insert_id();
mysql_query("UPDATE table SET field='OC{$id}' WHERE id={$id} LIMIT 1;");

I'd suggest to drop the 'OC' field from the table, eg 我建议从表中删除'OC'字段,例如

CREATE TABLE tbl_othercharge (tblocID int AUTO_INCREMENT PRIMARY KEY, assessmentID varchar(100));

CREATE VIEW vw_othercharge SELECT tblocID, concat('OC',tblocID) as OCnumber, assessmentID FROM tbl_othercharge

now direct all relevant SELECTs to vw_othercharge and forget about it. 现在将所有相关的SELECT指向vw_othercharge并忘记它。

Have you try: 你试过:

for($x=0;$x<=500; $x++){
    $db->query("LOCK TABLES tbl_othercharge WRITE");
    $id = get_max();
    $db->query("INSERT INTO tbl_othercharge SET tblocID = '$id', assessmentID='lock1'");
    $db->query("UNLOCK TABLES");
}

In this way you will set lock each time you insert a row! 这样,每次插入行时都会设置锁定!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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