2013-05-15 69 views
0

我有下面的代码失败:CREATE TABLE IF NOT EXISTS当表中存在

$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语句,并且根本不回显任何内容,而不尝试执行查询?

只是试图找到“如果它不存在就创建表”的最佳方式,而不向用户输出任何内容。

+2

东西不对。 [见可能愚蠢](http://stackoverflow.com/q/3302476/168868)([和这一个](http://stackoverflow.com/q/7019018/168868))进行一些维护? – Charles

+0

它肯定看起来像是同样的问题,很好找! –

+0

迄今为止没有骰子... http://puu.sh/2TEHp.png - 它真的,真的不存在.. –

回答

1

你应该得到一个警告,而不是一个错误。你正在运行什么版本? 无论如何,如果你想要显示错误,请在你的SQL查询之前输入: SET sql_notes = 0; 然后键入SET sql notes = 1;查询后。

+0

我正在运行以下版本... http://puu.sh/2TFbO.png –

0
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) 
相关问题