Forum Moderators: coopster

Message Too Old, No Replies

IF statement with MySQL

         

jackvull

10:31 am on Mar 9, 2006 (gmt 0)

10+ Year Member



I'm trying to check whether a record exists in the table before I perform an INSERT.
WITH SQL Server you can use an IF statement but is ther a way to do this in MySQL with inline code in PHP?

$sSQL = "IF (SELECT TrackID
FROM TempShoppingBasket
WHERE TrackID = ".$_GET['tid'].") >= 1
THEN
INSERT INTO TempShoppingBasket (SessionID, TrackID, LUpdate)
SELECT '".session_id()."', ".$_GET['tid'].", now()
END IF;";

FalseDawn

12:30 pm on Mar 9, 2006 (gmt 0)

10+ Year Member



Try using NOT EXISTS (for mysql 4.1+)

eg
INSERT INTO TABLE blah
WHERE NOT EXISTS (SELECT * FROM TABLE WHERE condition)

If you don't have subquery support, a select count(*) followed by an insert if the count returns 0 is usually pretty fast as long as the count condition uses an index.