【问题标题】:CREATE TABLE IF NOT EXISTS failing when the table exists [duplicate]表存在时如果不存在则创建表失败[重复]
【发布时间】:2013-05-09 09:59:16
【问题描述】:

我有以下代码:

$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 查询的执行吗?换句话说,如果表存在,它是否应该退出该 if 语句并且根本不回显任何内容,并且不尝试执行查询?

只是试图找到最好的方法来“创建一个不存在的表”而不向用户输出任何内容。

【问题讨论】:

标签: php mysql mysqli mysql-error-1050


【解决方案1】:
I use your script in mysql is true:
mysql> select version();
+-----------+
| version() |
+-----------+
| 5.5.30    |
+-----------+
1 row in set (0.01 sec)

$queryCreateUsersTable = "CREATE TABLE IF NOT EXISTS `sun_channel` (
    `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`)
)";
$res = mysql_query($queryCreateUsersTable);
var_dump($res);
die;

//show bool(true)

【讨论】:

    【解决方案2】:

    您应该收到警告,而不是错误。你运行的是什么版本? 无论如何,如果您想在 SQL 查询之前显示错误,请键入以下内容: 设置 sql_notes = 0; 然后输入 SET sql notes=1;查询后。

    【讨论】:

    猜你喜欢
    • 2021-07-08
    • 2010-12-03
    • 1970-01-01
    • 2013-05-26
    • 2010-09-19
    • 1970-01-01
    • 2019-07-16
    • 1970-01-01
    相关资源
    最近更新 更多