Jay Jay - 4 months ago 8
MySQL Question

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:

|Name.....| Value..........| id |


|count......| 5................| 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'";

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. 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. 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", ....); $q = "UPDATE example SET Value = Value + 1 WHERE id = '1'"; mysqli_query($db,$q);