Hi I have a mysql table having the following fields
A INT, B INT, C INT, D INT, Count INT
I want the insertion to be unique for the values of ‘A’, ‘B’, ‘C’ ANT ‘D’. ie if there is a ‘Count’ entry for a particular values of ‘A’, ‘B’, ‘C’ AND ‘D’ then there will be only UPDATION of ‘Count’ field for the same values of ‘A’, ‘B’, ‘C’ AND ‘D’. The problem is that more than 1 users are trying to Insert same value to database simultaneously, so there is a chance of multiple entry of same values to database.I am using php to check whether an entry is present for a particular values of ‘A’, ‘B’, ‘C’ AND ‘D’, if yes I can make an update. But for the first time without an entry there is a chance that 2 or more user’s can make an insert of same values for A’, ‘B’, ‘C’ AND ‘D’ at the same time, like
A=10, B=8, C=4, D=5 AND Count=1
A=10, B=8, C=4, D=5 AND Count=2
but I want an Insertion of “A=10, B=8, C=4, D=5 AND Count=1” for first(second) user and the row get updated to “A=10, B=8, C=4, D=5 AND Count=3” for second(first) user even if both user’s tried to insert values at the same time. How can I fix this problem ?
1) Don’t use ‘count’ as a column name – it is a MySQL keyword
2) You need to make a UNIQUE key on the columns that you want to watch for duplicates of and then use the ‘on duplicate key update’ funcitonality: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
insert into mytable
(a, b, c, d, entryCount )
values
( ?, ?, ?, ?, 0)
on duplicate key update
a = ?, b = ?, c = ?, d = ?, entryCount = entryCount + 1;
That code is ‘thread safe’ at a MySQL level, so you don’t need to handle it in PHP at all.