MySQL不通过PHP创建表

时间:2016-01-23 19:53:30

标签: php mysql

我目前正在开发PHP / MySQL排名系统,但我的CREATE TABLE语句出现了问题。

这是我的代码:

mysql_select_db("DB1");
$numrows = "SELECT COUNT( * ) FROM information_schema.tables WHERE table_schema =  'DB1'";
if($numrows > 1){
    if($numrows > 2){
        $table = rand(1, $numrows);
    }else{
        $table = rand(1, 2);
    }
}else{
    $table = rand(1, 1);
}
$checkForTable = mysql_query("SELECT 1 FROM $table LIMIT 1");
if($checkForTable){
    $query = "INSERT INTO $table (name,score) VALUES($name, $score)";
    $result = mysql_query($query);
    mysql_select_db("DB2");
    $query2 = "INSERT INTO Leaderboard (name,score) VALUES($name, $score)";
    $result2 = mysql_query($query2);
    mysql_select_db("DB1");
    if($result && $result2){
        echo "<h4 style='color:green;'>Your Score Has Been Inserted</h4><hr/>";
    }else{
        echo "<h4 style='color:red;'>We encountered an error while inserting your data </h4><hr/>";
    }
}else{
    $newtable = "CREATE TABLE $table (
        id bigint AUTO_INCREMENT NOT NULL,
        name varchar(255) NOT NULL,
        score bigint(20) NOT NULL,
        PRIMARY KEY('id')
    )";
    $result = mysql_query($newtable);
    if($result){

        $query = "INSERT INTO $newtable (name,score) VALUES($name,$score)";
        $result = mysql_query($query);
        mysql_select_db("DB2");
        $query2 = "INSERT INTO Leaderboard (name,score) VALUES($name, $score)";
        $result2 = mysql_query($query2);
        mysql_select_db("DB1");
        if($result && $result2){
            echo "<h4 style='color:green;'>Your Score Has Been Inserted</h4><hr/>";
        }else{
            echo "<h4 style='color:red;'>We encountered an error while inserting your data </h4><hr/>";
        }

    }else{
        echo "TableNotCreatedException: " . mysql_error();
    }
}

当我试用我得到的代码时:

  

您的SQL语法有错误;检查与MySQL服务器版本对应的手册,以便在'1附近使用正确的语法(id bigint AUTO_INCREMENT NOT NULL,name varcha'在第1行

我一直想弄清楚这一段时间,但我没有运气。请帮助!

1 个答案:

答案 0 :(得分:1)

这是因为您的$table变量包含一个值1,您将其用作表名,因此您的查询将变为

CREATE TABLE 1(.... 

MySQL Documentation说明

  

标识符可以以数字开头,但除非引用可能不包含   只是数字。

另外,您引用列名如下所示

    PRIMARY KEY('id')

应该是

    PRIMARY KEY(`id`)