user1180888 user1180888 - 1 year ago 67
MySQL Question

On Duplicate key proper use? Not working. MySQL / PHP

I am trying to record IP addresses of users on my site, and I want to have the following flow when the user logs on

if (new ip address detected)
enter in to db
else if (ip address has already been recorded)
do nothing

So that I am not recording every single time a user logs on, just if it is from a new IP address. I thought that I had the correct code, but duplicates are still entering the DB. Can anyone see where I am going wrong?

public function insertIpAddress($user_id, $user_ip) {
return $this->dbHandler->DbQuery("INSERT into user_ip (user_id, ip_address)
VALUES (?,?) ON DUPLICATE KEY UPDATE `user_id` = `user_id`",

, but that didn't work.

My DB looks like this:

enter image description here

and it's coming out like this:

ip_address user_id 378 378

Answer Source

It doesn't appear that you have a unique index for those two columns. You can add a unique index to your table with the following:

ALTER TABLE user_ip 
    ADD UNIQUE `unique_user_ip_address_user_id`(`ip_address`, `user_id`);

This creates a unique constraint for the specific combination of IP address and user ID.

As a suggestion, you could add a third column to your user_ip table to track when the login was attempted and update that field to the current timestamp if there is a duplicate key.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download