[英]php and mySQL database concurrency update
Lets say I wanted to increment a counter in a database every time someone visits a webpage. 可以说,我每次有人访问网页时都想在数据库中增加一个计数器。
The database called 'example' looks like this: 名为“ example”的数据库如下所示:
|Name.....| |名称..... | Value..........|
值.......... | id |
id |
=================== ===================
|count......| |计数... | 5................|
5 ....... | 1 |
1 | <---- 1st row
<----第一行
and the code on the webpage looks like this: 网页上的代码如下:
$db = mysqli_connect("localhost", ....);
$q = "SELECT Value FROM example WHERE id = '1'";
$r=mysqli_query($db, $q);
$result = mysqli_fetch_array($r);
$increment = $result[0] + 1;
$q = "UPDATE example SET Value = '$increment' WHERE id = '1'";
mysqli_query($db,$q);
If two people access the webpage at the same time, person A will fetch the value of 5 and immediately after that, person B will fetch the same value. 如果两个人同时访问该网页,则人A将获取5的值,此后,人B将立即获取相同的值。 They will both increment it to six and both perform the update one after the other entering 6 as the counter value when it should really be 7 since two people visited the page.
由于两个人都访问过该页面,因此他们都将其递增到6,并且都一个又一个地执行更新,然后输入6作为计数器值(实际上应该为7)。 How can I prevent this?
我该如何预防?
you can do it in one statement: 您可以在一条语句中做到这一点:
"UPDATE example SET Value = Value + 1 WHERE id = '1'";
so also no other task can change it between your read and update. 因此在读取和更新之间没有其他任务可以更改它。
Here your script 这是你的剧本
$db = mysqli_connect("localhost", ....); $ db = mysqli_connect(“ localhost”,....); $q = "UPDATE example SET Value = Value + 1 WHERE id = '1'";
$ q =“更新示例SET值=值+ 1 WHERE id ='1'”“; mysqli_query($db,$q);
mysqli_query($ db,$ q);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.