Nubcake
Nubcake

Reputation: 35

SQL Query IF EXISTS not working

I have the following sql query that I want to run with PHP. Why doesn't it work?

IF EXISTS(SELECT * FROM content WHERE site_id ='". $id ."') BEGIN
UPDATE content SET
titel = '". htmlentities($connect->real_escape_string($data[0])) ."',
content = '". htmlentities($connect->real_escape_string($data[1])) ."'
WHERE site_id ='". $id ."'
END
ELSE
BEGIN
INSERT INTO content (site_id, titel, content)
VALUES (
'". $id ."',
'". htmlentities($connect->real_escape_string($data[0])) ."',
'". htmlentities($connect->real_escape_string($data[1])) ."'
)
END

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF EXISTS(SELECT * FROM content WHERE site_id ='1') BEGIN UPDATE content SET tit' at line 1

Upvotes: 0

Views: 111

Answers (1)

Richard St-Cyr
Richard St-Cyr

Reputation: 995

I suppose that site_id is a unique key in your table. Use the solution proposed by @Saty

INSERT INTO content (site_id, titel, content)
VALUES (
  '". $id ."',
  '". htmlentities($connect->real_escape_string($data[0])) ."',
  '". htmlentities($connect->real_escape_string($data[1])) ."'
)
ON DUPLICATE UPDATE 
  titel = '". htmlentities($connect->real_escape_string($data[0])) ."',
  content = '". htmlentities($connect->real_escape_string($data[1])) ."';

Upvotes: 2

Related Questions