Is it possible to check if num rows in a table is 0 then perform an insert, all in ONE sql statement?
Here’s my query that I tried but it says I have a syntax error:
$query =
"IF (SELECT COUNT(ID) FROM votes WHERE userid = $userid AND itemid = $itemid AND itemtype=1) = 0
INSERT INTO votes (itemtype, itemid, userid) VALUES (1, $itemid, $userid)
SELECT 1 AS result
ELSE
SELECT 0 AS result
END IF";
I know the SELECT COUNT bit works successfully on its own.
NO IDEA if this is the best way of solving this, but it will work. Basically, it simply causes an error if the condition is false, and so it prevents insert: