0

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

2

1 Answer 1

2

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])) ."';
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.