Re: optimal way of counting votes in online poll

From: Date: Wed, 28 Feb 2001 11:55:00 +0000
Subject: Re: optimal way of counting votes in online poll
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-41992@lists.php.net to get a copy of this message
From: "Vikram Vaswani" <vikram@w-o-i.com> > Hi all! > > I have a question as to the optimal method of counting and storing votes in > an online poll. > > Once a user answers the poll by clicking on one of three options, I am > performing a query on a table which holds values for each option. Currently I > - query the table to get the current count > - increment the count by 1 > - UPDATE the table with the new value > > I wonder: what happens if two users submit the answer simulatneously, and > the answer is the same. Will only of those votes register? Or will the SQL > somehow be "queued" so that both are counted? And so you should wonder :) You have created a race condition - if the table is updated between your SELECT and your UPDATE, then your UPDATE will be using incorrect values. The solution is very simple - instead of querying the current value and incrementing it in PHP, let MySQL do the work: UPDATE polls SET votecount=votecount+1 WHERE pollid=$poll There are all sorts of manipulations you can do to the data during queries, and they're all usually much better than trying to do the same thing in your application. http://www.mysql.com/doc/F/u/Functions.html Cheers Simon Garner

« previous php.general (#41992) next »