PHP处理MySQL高并发加锁事务

需求

现在有这样的需求,插入数据时,判断test表有无username为‘mraz’的数据,无则插入,有则提示“已插入”,目的就是想只插入一条username为‘mraz’的记录。

逻辑

$conn = mysqli_connect('127.0.0.1','root','root') or die(mysqli_error());

mysqli_select_db($conn,'mraz');
$rs=mysqli_query($conn,'SELECT count(*) as total FROM test WHERE username = "mraz"');
$row = mysqli_fetch_array($rs);
if($row['total']>0){
    exit('exist');
}

mysqli_query($conn,'INSERT INTO test(username) VALUES("mraz")');
var_dump('error'.mysqli_error($conn));
$insert_id = mysqli_insert_id($conn);

echo 'insert_id:'.$insert_id;

mysqli_free_result($rs);
mysqli_close($conn);

问题

一般少量请求的时候,程序逻辑不会有问题。但是一旦高并发请求执行的话,程序并没有按预期执行,会插入多条username为‘mraz’的记录。

优化

$conn = mysqli_connect('127.0.0.1','root','root') or die(mysqli_error());

mysqli_select_db($conn,'mraz');
mysqli_query($conn,'BEGIN');
$rs = mysqli_query($conn,'SELECT count(*) as total FROM test WHERE username = "mraz" FOR UPDATE');
$row = mysqli_fetch_array($rs);
if($row['total']>0){
    exit('exist');
}
mysqli_query($conn,'INSERT INTO test(username) VALUES("mraz")');
var_dump('error'.mysqli_error($conn));
$insert_id = mysqli_insert_id($conn);
mysqli_query($conn,'COMMIT');
echo 'insert_id:'.$insert_id;

mysqli_free_result($rs);
mysqli_close($conn);

再利用php的curl模拟高并发请求该php脚本,查看数据库会只有一条username为‘mraz’的记录。达到程序执行的预期结果~

发表评论

发表评论