filips filips - 3 months ago 8
SQL Question

MySQL error - “You have an error in your SQL syntax"

My code is:

if (isset($_POST['add'])) {
$query = "INSERT INTO ".$dbPrefix."posts (`id`, `user`, `name`, `link`, `content`, `date`, `private`, `password`) VALUES (NULL, '$user', '$name', '$link', '$content', '$date', '$private', '$pass');";
$mysqli->query($query) OR $status = 'Oprostite, pri dodajanju je prišlo do težave.';
$id=$mysqli->insert_id;
foreach ($_POST['categories'] as $category) {
$categoryQuery.="INSERT INTO ".$dbPrefix."category_posts (`categoryID`, `postID`) VALUES ('".$category."','".$id."');";
}
$mysqli->query($categoryQuery) OR $status = $mysqli->error;
}
echo $status;


My variable $_POST is:


Array
(
[name] => ((((((((((
[description] => ))))))
[keywords] =>
[categories] => Array
(
[0] => 1
[1] => 2
[2] => 3
)

[private] => 0
[password] =>
[date] => 0
[datetime] =>
[add] => Dodaj
)


If I print the query and run it in phpMyAdmin there is no problem, otherwise we will display an 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 'INSERT INTO fc_category_posts (`categoryID`, `postID`) VALUES ('2','116');INSERT' at line 1


Query is:

INSERT INTO fc_category_posts (`categoryID`, `postID`) VALUES ('1','116');INSERT INTO fc_category_posts (`categoryID`, `postID`) VALUES ('2','116');INSERT INTO fc_category_posts (`categoryID`, `postID`) VALUES ('3','116');

Answer

If you can only pass the one INSERT then why not do it like this;

INSERT INTO fc_category_posts (`categoryID`, `postID`) 
VALUES ('1','116'),('2','116'),('3','116');

Saves you running multiple INSERT INTO statements.

Comments