I'm trying to check if a record already exists in my table and if it doesn't I want to execute an insert... using a prepared statement. Can anyone tell me what's wrong below? I've written the code with error checking and it basically says the query is poo :) I am atrocious when it comes to SQL and pretty much anything programming related so I really do appreciate any wisdom that shared on this dodgy looking quest... Thanks!
$mysqli = mysqli_connect($config['host'], $config['user'], $config['pass'], $config['db']);
$timestamp = time();
$stmt = $mysqli->prepare("IF NOT EXISTS (SELECT id FROM course_licence_cart WHERE userid = ? AND courseid = ? AND lmsid = ?) BEGIN INSERT INTO course_licence_cart (lmsid, userid, courseid, assigned_by, assigned_on) VALUES (?, ?, ?, ?, ?) END");
foreach($_POST['assignTo'] as $assignTo){
$stmt->bind_param('iiiiiiii', $assignTo, $_POST['course'], $core['id'], $core['id'], $assignTo, $_POST['course'], $userInfo['id'], $timestamp);
$stmt->execute();
}
FYI: This takes place after a form submission, I've checked ALL of the variables and they're all good, and the process itself works perfectly (I have it working without the IF NOT EXISTS
), it's just this new query type mixed with prepared statements that has totally thrown me off.
-- UPDATE --
I ran the following directly:
IF NOT EXISTS (SELECT `id` FROM `course_licence_cart` WHERE `userid` = '175' AND `courseid` = '1' AND `lmsid` = '1') BEGIN INSERT INTO `course_licence_cart` (`lmsid`, `userid`, `courseid`, `assigned_by`) VALUES ('1', '175', '1', '175') END
In which I get the error:
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 NOT EXISTS (SELECT `id` FROM `course_licence_cart` WHERE `userid` = '175' AND' at line 1