Error with MySQL “CREATE TABLE” query

[亡魂溺海] 提交于 2019-12-10 11:46:37

问题


I know that this has been asked hundreds of times before, but I looked around the Internet and couldn't find what could possibly be wrong with my syntax:

mysql_select_db('Projects');

        $sql = "CREATE TABLE $data[ID] (
            ID INT NOT NULL,
            Creator INT NOT NULL,
            Name VARCHAR(20) NOT NULL,
            Version VARCHAR(20) NOT NULL,
            Status VARCHAR(20) NOT NULL,
            Date VARCHAR(20) NOT NULL,
            Skript VARCHAR(20) NOT NULL,
            Filename VARCHAR(20) NOT NULL,
            Downloads INT NOT NULL,
            PRIMARY KEY(ID)
            )";

        if (mysql_query($sql)){

            echo "Created";

        }else{

            echo "Not created, ".mysql_error();

        }

I tried using backticks, quotation marks et.c but in vain. The table name (21) displayed in the error is correct.

Here's the error that I get, including the echo "Not created, ";:

Not created, 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 '23 ( ID INT NOT NULL, Creator INT NOT NULL, Name VARCHAR(20) NOT NUL' at line 1


回答1:


Rules for naming objects, including tables in MySql:

http://dev.mysql.com/doc/refman/5.1/en/identifiers.html

Identifiers may begin with a digit but unless quoted may not consist solely of digits.

you cant name your table start with digits

this will work forexample

   $sql = "CREATE TABLE 't'.$data[ID] (
        ID INT NOT NULL,
        Creator INT NOT NULL,
        Name VARCHAR(20) NOT NULL,
        Version VARCHAR(20) NOT NULL,
        Status VARCHAR(20) NOT NULL,
        Date VARCHAR(20) NOT NULL,
        Skript VARCHAR(20) NOT NULL,
        Filename VARCHAR(20) NOT NULL,
        Downloads INT NOT NULL,
        PRIMARY KEY(ID)
        )";

as you see it starts by t

or use backticks around it. like that

   `$data[ID]`



回答2:


Your query seems correct except the value of $data[ID]. You should check it.

I think the problem is with the value of the $data[ID] what is the value of it? Also, use mysqli_query() or PDO (as indicated by bestprogrammerintheworld) instead of the old mysql_query().




回答3:


You've managed to omit the most important piece of info, which is the SQL code that triggers the SQL error. But we can gather some hints from the PHP that generates it:

$sql = "CREATE TABLE $data[ID] (
            ID INT NOT NULL,

... and the error message:

near '23 ( ID INT NOT NULL

I suspect you try to run this SQL:

CREATE TABLE 23 (
    ID INT NOT NULL

If you actually want to create a table called 23 you need to quote it with backticks every single time you make use of it, including creation:

CREATE TABLE `23` (
    ID INT NOT NULL


来源:https://stackoverflow.com/questions/16121169/error-with-mysql-create-table-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!