Why is the ip of Google Bots saved multiple times in my database?
there is something really weird going on in my mysql database. I have a script which takes the ip address of the use开发者_运维百科r and saves it for 5 minutes in the database. By doing this I can show the number of people currently active on my website. The script also checks whether the ip address is allready in the database or not. Now what happens is that there is allways a google bot coming with a specific ip address. And this ip address is saved about 40 times in my database, all the entries have exactly the same timestamp. How is this possible although my script is actually checking whether the ip address allready exists before writing it into the database?
Thank you, phpheini
So you have something like:
if(!already_exists($ip))
insert_into_db($ip)
Which is a neat example of a race condition, as your PHP script will be run in parallel, one for each request.
Just imagine what happens when you have 40 requests executing the first if
roughly at the same time, before the database reply comes... they all think the IP address does not exist, and they insert it.
You could use an ON DUPLICATE KEY UPDATE query to get around this.
INSERT INTO visitors values (NOW(),$ip) ON DUPLICATE KEY UPDATE ts = NOW();
This will insert the record if it does not exist, if it does, it will update the ts
column.
You need an UNIQUE index on the column with the IP address for this to work.
精彩评论