简体   繁体   English

在有效语法上抛出MySQL错误

[英]MySQL error thrown on valid syntax

I'm having a MySQL error and I can't for the life of me figure it out. 我有一个MySQL错误,我不能为我的生活搞清楚。 I've used the exact same code multiple times successfully on my site (although never with a single column). 我在我的网站上成功地多次使用完全相同的代码(尽管从不使用单个列)。 Anyone see what I'm doing wrong? 有谁看到我做错了什么?

try{
        $conn = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuser, $dbpass);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        if(!empty($_POST['group'])){
            $sql = "INSERT INTO Groups (group) VALUES (:group)";
            $query = $conn->prepare($sql);

            if($query->execute(array(":group" => $_POST['group']))){
                echo 'Successfully created user. <a href="dashboard.php">Go back to admin page</a>';
            }
            else{
                echo 'Something went wrong. Contact the Admin. <a href="dashboard.php">Go back to admin page</a>';
            }
        }
        else{
            echo 'Group cannot be empty. <a href="dashboard.php">Go back to admin page</a>';
        }
    }
    catch(PDOException $e){
        echo $e->getMessage();
    }

The error I'm getting is: 我得到的错误是:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法中有错误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'group) VALUES ('as12')' at line 1 查看与您的MySQL服务器版本对应的手册,以便在第1行的'group)VALUES('as12')附近使用正确的语法

I've been sitting over it for an hour and I'm hoping for some external input to help figure it out. 我一直坐在它上面一个小时,我希望得到一些外部输入来帮助解决这个问题。

您不能在查询中使用MySQL保留字 (其中哪个group是一个)作为标识符(列,表等)。如果要使用这样的单词,则必须将其包装在反引号中。

INSERT INTO Groups (`group`) VALUES (:group)

group is a reserved word . 组是一个保留字 You could put it in backticks but in general you should try to avoid using reserved words as column names. 你可以把它放在反引号中,但一般来说你应该尽量避免使用保留字作为列名。

Best way forward is to modify the schema, change the column name to group_name or something. 最好的方法是修改架构,将列名更改为group_name或其他内容。

ALTER TABLE Groups CHANGE `group` group_name VARCHAR(100); -- must repeat old column spec

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM