If not exist

driveflexfuel

New Member
Messages
159
Reaction score
0
Points
0
I have been trying to get the following code to work but for some reason it keeps throwing an error. Any assistance is appreciated.


Code:
mysql_query("IF NOT EXIST (SELECT * FROM station WHERE name='$name' AND address='$address' AND city='$city') THEN
INSERT INTO station (name, address, city, state, zip, phone, notes) VALUES ('$name', '$address', '$city', '$state', '$zip', '$phone', '$notes')") or die(mysql_error());
 

garrettroyce

Community Support
Community Support
Messages
5,609
Reaction score
252
Points
63
I think it would be easier just to say INSERT INTO station ....

This operation will produce an error if the record exists and fail. However, you can also do this

INSERT INTO station...
ON DUPLICATE KEY UPDATE
name=$name,
address=$address, ...

It's also a little easier for you and others to understand what's going on with your code if you put some line breaks in:

Code:
mysql_query("
IF NOT EXIST (
     SELECT * 
     FROM station 
     WHERE name='$name' 
          AND address='$address' 
          AND city='$city'
) THEN
     INSERT INTO station (name, address, city, state, zip, phone, notes) 
     VALUES ('$name', '$address', '$city', '$state', '$zip', '$phone', '$notes')
") or die(mysql_error());

This query is completely valid and much easier to understand what is going on.
 
Last edited:
Top