I'm trying to have a system that checks if it exists, if it does then overwrite if not then insert. I have an error in this code but I cannot see it for the life of me. I've tried this two different ways, neither work.
mysqli_query($con,"IF (SELECT COUNT(*) FROM saves
WHERE name='$_POST[name]') > 0
BEGIN
UPDATE saves SET entity='$_POST[saveEntity]' WHERE name='$_POST[name]'
END
ELSE
BEGIN
INSERT INTO saves (`name`, `ID`, `entity`)
VALUES ('$_POST[name]', NULL, '$_POST[saveEntity]')
END");
OR
mysqli_query($con,"IF EXISTS(SELECT * FROM saves WHERE name='$_POST[name]')
BEGIN
UPDATE saves SET entity='$_POST[saveEntity]' WHERE name='$_POST[name]'
END
ELSE
BEGIN
INSERT INTO saves (`name`, `ID`, `entity`)
VALUES ('$_POST[name]', NULL, '$_POST[saveEntity]')
END");
You should set primary key on "name" column and then use syntax like:
INSERT INTO saves (column1,column2,column3,...) VALUES (1,2,3,...)
ON DUPLICATE KEY UPDATE entity='your value';
Try this or you might have to adapt the +'" and '"+ i
mysqli_query($con,"IF EXISTS(SELECT * FROM saves WHERE name='"+$_POST[name]+"')
BEGIN
UPDATE saves SET entity='"
+ $_POST[saveEntity]+ "' WHERE name='"+$_POST[name]+"'
END
ELSE
BEGIN
INSERT INTO saves (`name`, `ID`, `entity`)
VALUES ('"+$_POST[name]+"', NULL, '"+$_POST[saveEntity]+"')
END");
But for the sql i would just insert where it dose not exist
then up date it all i dont know that is my thought
mysqli_query($con,"
INSERT INTO saves (`name`, `ID`, `entity`)
VALUES ('"+$_POST[name]+"', NULL, '"+$_POST[saveEntity]+"')
where name not in
(SELECT name FROM saves WHERE name)
go
UPDATE saves SET entity='"
+ $_POST[saveEntity]+ "' WHERE name='"+$_POST[name]+"'");