简体   繁体   中英

MySQL error thrown on valid syntax

I'm having a MySQL error and I can't for the life of me figure it out. 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; check the manual that corresponds to your MySQL server version for the right syntax to use near 'group) VALUES ('as12')' at line 1

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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