SQL CREATE TABLE语法错误

时间:2014-03-16 10:37:33

标签: php mysql database

我正在尝试制作500个表,所有表都命名为[1-500]并且只有时间戳和相应的值(总视图)

<?php
$i = 1;
while ($i<500) {
    $con=mysqli_connect("localhost","user","pass","database");
    if (mysqli_connect_errno($con))
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
    $sql = "CREATE TABLE \"".$i."\" ( 
    'TheTime' INT UNSIGNED PRIMARY KEY, 
    'TotalViews' INT UNSIGNED
    )";
    if (!mysqli_query($con, $sql))
      {
      die('Error: ' . mysqli_error($con));
      };
    echo "1 table created added: ".$i;
    mysqli_close($con);
$i++;
    }
?>

但是我收到错误:错误:您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册,以便在第1行使用“1”('TheTime'INT UNSIGNED PRIMARY KEY,'TotalViews'INT UNSIGNED)附近的正确语法。

我做错了什么?我应该以不同的方式完成这项工作吗?

3 个答案:

答案 0 :(得分:0)

您不能使用单引号括起来的列名,可以使用反引号

所以

'TheTime'

应该是

`TheTime` 

'TotalViews'

`TotalViews` 

答案 1 :(得分:-1)

表名:100说,应该是反叛。

我正在贪婪地将所有名字放在反叛中,但除了保留字和不寻常的名字外,它们都没有必要。

这是经过测试的代码:

<?php
$i = 1;
while ($i<5) {
    $con=mysqli_connect("localhost","test","test","testmysql");
    if (mysqli_connect_errno($con))
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
    $sql = 'CREATE TABLE `'.$i.'` ('
    .'`TheTime` INT UNSIGNED PRIMARY KEY,'
    .'`TotalViews` INT UNSIGNED)';
    if (!mysqli_query($con, $sql))
      {
      die('Error: ' . mysqli_error($con));
      };
    echo "1 table created added: ".$i;
    mysqli_close($con);
$i++;
    }
?>

答案 2 :(得分:-1)

首先,您应该在开始循环之前移动连接。 对于DB名称,使用`而不是“,对于字段使用`而不是'符号:

<?php
$con = mysqli_connect("localhost", "user", "pass", "database");
if (mysqli_connect_errno($con)) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();

    die();
}

$i = 1;    
while ($i < 500) {
    $sql = "CREATE TABLE `" . $i . "` (
    `TheTime` INT UNSIGNED PRIMARY KEY,
    `TotalViews` INT UNSIGNED
    )";

    if (!mysqli_query($con, $sql)) {
        die('Error: ' . mysqli_error($con));
    }

    echo "1 table created added: " . $i;
    $i++;
}

mysqli_close($con);

PS:我建议你使用面向对象的mysqli界面,它更简单。详情:http://ua1.php.net/manual/en/mysqli.quickstart.dual-interface.php