MySQL错误 - “您的SQL语法错误"

时间:2016-08-23 14:16:07

标签: php mysql sql

我的代码是:

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;

我的变量$ _POST是:

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

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

如果我打印查询并在phpMyAdmin中运行它没有问题,否则会显示错误:

  

您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,以获得正确的语法,以便在' INSERT INTO fc_category_posts(`categoryID`,`postID`)VALUES(' 2',' 116&#)附近使用39); INSERT'在第1行

查询是:

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');

2 个答案:

答案 0 :(得分:4)

如果你只能传递一个INSERT,那么为什么不这样做呢;

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

保存您运行多个INSERT INTO语句。

答案 1 :(得分:4)

只需在循环中移动查询的执行

即可
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) {

        //Note I have chnages `.=` to `=` in this statement
        $categoryQuery = "INSERT INTO ".$dbPrefix."category_posts 
                                   (`categoryID`, `postID`) 
                            VALUES ('$category','$id');";

        $mysqli->query($categoryQuery) OR $status = $mysqli->error;
    }

}
echo $status;
  

但是,您的脚本存在SQL Injection Attack的风险   看看Little Bobby Tables偶然发生了什么   if you are escaping inputs, its not safe!   使用prepared parameterized statements

     

在这个场景中,考虑在事务中运行这些内容也是有用的,这样如果一个插入失败,你就不会让darabase陷入混乱The manual for mysqli::begin_transaction