PHP MySQL无法创建表

时间:2014-02-26 12:27:03

标签: php mysql

这是我的代码。但每次创建表 tblStudents 时都会出现错误。这是为什么?需要尽快解决。

<?php

$con=mysqli_connect("localhost","root","noor.xbyte","fathis_quran_class");
if (mysqli_connect_errno()) {
  echo '&lt;h1>Error Connecting to the database!&lt;/h1>';
} else {
  $sql = "CREATE TABLE tblStudents
  (
  index INT NOT NULL AUTO_INCREMENT,
  PRIMARY KEY(index),
  fullName CHAR(30) NOT NULL,
  dateOfBirth DATE NOT NULL,
  SID TINYINT NOT NULL,
  address CHAR(30) NOT NULL,
  level TINYINT NOT NULL,)";
  if (mysqli_query($con,$sql)) {
    echo 'Table "tblStudents" created successfully!';
  } else {
    echo 'Error creating table "tblStudents"';
  }
}

?>;

4 个答案:

答案 0 :(得分:5)

你有一些错误,这是正确的陈述

CREATE TABLE `table_name`
(
  `index` INT NOT NULL AUTO_INCREMENT,
  PRIMARY KEY(`index`),
  fullName CHAR(30) NOT NULL,
  dateOfBirth DATE NOT NULL,
  SID TINYINT NOT NULL,
  address CHAR(30) NOT NULL,
  level TINYINT NOT NULL
)

你犯的错误是:

  • index是一个保留的关键字,因此请使用反引号`index`作为列名
  • 在“TINYINT NOT NULL”之后有一个额外的逗号(,)。

答案 1 :(得分:2)

为字段'index'指定另一个名称。你不能使用它,因为它是保留字。

答案 2 :(得分:1)

此处index是保留关键字。

所以,你需要添加一个倾斜(`)来索引。

更正后的代码:

CREATE TABLE tblStudents
(
  `index` INT NOT NULL AUTO_INCREMENT,
  PRIMARY KEY(`index`),
  fullName CHAR(30) NOT NULL,
  dateOfBirth DATE NOT NULL,
  SID TINYINT NOT NULL,
  address CHAR(30) NOT NULL,
  level TINYINT NOT NULL
)

答案 3 :(得分:0)

**Try below code,I think it will work fine..** 




<?php

    $con=mysqli_connect("localhost","root","noor.xbyte","fathis_quran_class");
    if (mysqli_connect_errno()) {
      echo '&lt;h1>Error Connecting to the database!&lt;/h1>';
    } else {
      $sql = "CREATE TABLE tblStudents(

      index int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY (`index`),
      fullName varchar(30) NOT NULL,
      dateofbirth date NOT NULL,
      SID tinyint(4) NOT NULL,
      address varchar(30) NOT NULL,
      level tinyint(4) NOT NULL);
      if (mysqli_query($con,$sql)) {
        echo 'Table "tblStudents" created successfully!';
      } else {
        echo 'Error creating table "tblStudents"';
      }
    }

    ?>;