I'm having trouble with a mysqli_multi_query.
I am able to INSERT INTO
multiple times, but as soon as I include a DELETE
, all subsequent queries do not work. Interestingly, this query works fine when pasted into the phpMyAdmin SQL box.
SET @contact_id := 1;
INSERT INTO `contacts_tags` (`contact_id`, `tag_id`)
SELECT * FROM (SELECT @contact_id, 1) AS tmp
WHERE NOT EXISTS (
SELECT `contact_id`, `tag_id` FROM `contacts_tags`
WHERE `contact_id` = @contact_id AND `tag_id` = 1
);
DELETE FROM `contacts_tags`
WHERE `contact_id`=@contact_id AND `tag_id` NOT IN (1);
All queries up to the DELETE
query execute as expected from my php code.
Adding a further queries as logs (see below), Step 1, @contact_id, Step 2a, Step 2b and Step 2c are all inserted. The 'Last' one does not. (And of course neither does the DELETE
one.
INSERT INTO `tf_logs` (`query`) VALUES ('Step0');
SET @contact_id := 1;
INTO `tf_logs` (`query`) VALUES ('Step1');
INSERT INTO `contacts_tags` (`contact_id`, `tag_id`)
SELECT * FROM (SELECT @contact_id, 1) AS tmp
WHERE NOT EXISTS (
SELECT `contact_id`, `tag_id` FROM `contacts_tags`
WHERE `contact_id` = @contact_id AND `tag_id` = 1
);
INSERT INTO `tf_logs` (`query`) VALUES (@contact_id);
INSERT INTO `tf_logs` (`query`) VALUES ('Step 2a');
INSERT INTO `tf_logs` (`query`) VALUES ('Step 2b');
INSERT INTO `tf_logs` (`query`) VALUES ('Step 2c');
DELETE FROM `contacts_tags`
WHERE `contact_id`=@contact_id AND `tag_id` NOT IN (1);
INSERT INTO `tf_logs` (`query`) VALUES ('Last');
To create this query, I incrementally append values to a string, then use mysqli_multi_query
, as below. To check exactly what the variable contains, I have emailed myself the final query. Copying and pasting the email contents into phpMyAdmin executes the queries exactly as intended.
$queryString = "";
$queryString .= "INSERT INTO `tf_logs` (`query`) VALUES ('Step0'); ";
$queryString .= "
SET @contact_id := $contactId; ";
//...and so on
if(mysqli_multi_query($connection,$queryString)) {
echo "Success.";
$to = "abc@xyz.com";
$subject = "SQL query";
$headers = "From: abc@xyz.com";
mail($to,$subject,$queryString,$headers);
} else {
echo "Error.";
}
I'm sure I'm missing something obvious here, but a few days of googling has driven me to insanity. Thanks in advance!