CREATE TABLE IF NOT EXISTS失败表已经存在(CREATE TABLE IF

2019-09-03 06:12发布

我有以下代码:

$db_host = 'localhost';
$db_port = '3306';
$db_username = 'root';
$db_password = 'root';
$db_primaryDatabase = 'dsl_ams';

// Connect to the database, using the predefined database variables in /assets/repository/mysql.php
$dbConnection = new mysqli($db_host, $db_username, $db_password, $db_primaryDatabase);

// If there are errors (if the no# of errors is > 1), print out the error and cancel loading the page via exit();
if (mysqli_connect_errno()) {
    printf("Could not connect to MySQL databse: %s\n", mysqli_connect_error());
    exit();
}

$queryCreateUsersTable = "CREATE TABLE IF NOT EXISTS `USERS` (
    `ID` int(11) unsigned NOT NULL auto_increment,
    `EMAIL` varchar(255) NOT NULL default '',
    `PASSWORD` varchar(255) NOT NULL default '',
    `PERMISSION_LEVEL` tinyint(1) unsigned NOT NULL default '1',
    `APPLICATION_COMPLETED` boolean NOT NULL default '0',
    `APPLICATION_IN_PROGRESS` boolean NOT NULL default '0',
    PRIMARY KEY  (`ID`)
)";

if(!$dbConnection->query($queryCreateUsersTable)){
    echo "Table creation failed: (" . $dbConnection->errno . ") " . $dbConnection->error;
}

其输出...

Table creation failed: (1050) Table ' dsl_ams . USERS ' already exists

我不明白的是:不IF NOT EXISTS应该取消如果该表已经存在的SQL查询的执行? 换句话说,如果该表存在,应该不是退出,如果语句并没有什么回音了所有,而不是试图执行查询?

只是试图找到“创建一个表,如果它不存在”没有任何输出给用户的最佳方式。

Answer 1:

试试这个

$query = "SELECT ID FROM USERS";
$result = mysqli_query($dbConnection, $query);

if(empty($result)) {
                $query = "CREATE TABLE USERS (
                          ID int(11) AUTO_INCREMENT,
                          EMAIL varchar(255) NOT NULL,
                          PASSWORD varchar(255) NOT NULL,
                          PERMISSION_LEVEL int,
                          APPLICATION_COMPLETED int,
                          APPLICATION_IN_PROGRESS int,
                          PRIMARY KEY  (ID)
                          )";
                $result = mysqli_query($dbConnection, $query);
}

它检查看看是否有什么是表,如果它返回NULL你没有一个表。

也没有BOOLEAN在mysql中的数据类型,你应该INT和插入到表时,它只是设置为1或0。 你也不需要使用单引号周围的一切,只是当你被硬编码数据导入查询。

像这样...

$query = "INSERT INTO USERS (EMAIL, PASSWORD, PERMISSION_LEVEL, APPLICATION_COMPLETED, APPLICATION_IN_PROGRESS) VALUES ('foobar@foobar.com', 'fjsdfbsjkbgs', 0, 0, 0)";

希望这可以帮助。



Answer 2:

为了避免试图创建表之前,在你的PHP输出什么,测试表。 例如,

$querycheck='SELECT 1 FROM `USERS`';

$query_result=$dbConnection->query($querycheck);

if ($query_result !== FALSE)
{
 // table exists
} else
{
// table does not exist, create here.
}

最好的祝愿,



Answer 3:

你怎么样只显示错误,如果错误号是不是1050?

if(!$dbConnection->query($queryCreateUsersTable)){
  if($dbConnection->errno != 1050){
    echo "Table creation failed: (" . $dbConnection->errno . ") " . $dbConnection->error;
  }
}


文章来源: CREATE TABLE IF NOT EXISTS fails with table already exists