Page 1 of 1

SQL Insert IP if Not exist

Posted: 03 Apr 2018, 10:24
by JanMolendijk
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'
 ");

SQL Insert IP if Not exist

Posted: 03 Apr 2018, 12:44
by JanMolendijk
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.

SQL Insert IP if Not exist

Posted: 04 Apr 2018, 04:32
by Admin
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.