php and mySQL database concurrency update -


lets wanted increment counter in database every time visits webpage.

the database called 'example' looks this:

|name.....| value..........| id |

===================

|count......| 5................| 1 | <---- 1st row

and code on webpage looks this:

$db = mysqli_connect("localhost", ....); $q = "select value example id = '1'"; $r=mysqli_query($db, $q); $result = mysqli_fetch_array($r); $increment = $result[0] + 1; $q = "update example set value = '$increment' id = '1'"; mysqli_query($db,$q); 

if 2 people access webpage @ same time, person fetch value of 5 , after that, person b fetch same value. both increment 6 , both perform update 1 after other entering 6 counter value when should 7 since 2 people visited page. how can prevent this?

you can in 1 statement:

"update example set value = value + 1 id = '1'"; 

so no other task can change between read , update.

here script

$db = mysqli_connect("localhost", ....); $q = "update example set value = value + 1 id = '1'"; mysqli_query($db,$q);


Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -