SQL Insert IP if Not exist

Discuss coding issues, and scripts related to PHP and MySQL.
User avatar
JanMolendijk
Posts: 282
Location: Holland Rotterdam

SQL Insert IP if Not exist

My next problem... I want to insert into my data-base & detect if the record allready exists
when the record allready exists i don`t want to insert a new record

I looking for some hours for a solution but can`t find any

(This SQL example is not working) What must I do ?

Code: Select all

mysqli_query($con," INSERT INTO ip_register (ip_adress,country,date) 
 VALUES ('$ip','$details->country','$today') 

 SELECT * FROM ip_register WHERE NOT ip_adress='$ip'
 ");

JanMolendijk Posts: 282
I wrote something about Unique Key (id) but i would like to use, from the record the Unique ip_adress='$ip'.
I modified the ip wiuth str_replace() into:

Code: Select all

 $intip = str_replace(".","",$ip);
I hope all is working if not then I will ask your Support.

Admin Posts: 805
You can use INSERT ... ON DUPLICATE KEY UPDATE to Insert record if not exist.
The sql column for that record must be set as UNIQUE index or PRIMARY KEY.
Example:

Code: Select all

$sql ="INSERT INTO table_name (ip_adress, country, date_reg) VALUES('$ip', '$details->country', '$today') ON DUPLICATE KEY UPDATE date_reg ='$today'";
- The column for iP (ip_adress) must be Unique, or Primary_Key.

Similar Topics