如果表没有使用PHP存在,如何创建一个SQL表?

时间:2017-05-18 10:17:58

标签: php sql

如果数据库中没有表,我正在尝试创建一个表 - 使用PHP。

以下是我正在使用的代码:

 $conn = mysql_connect($dbhost, $dbuser, $dbpass);
    if(!$conn)
    {
            die('Failed to connect to server: ' . mysql_error());
            exit;
    }
    $db_selected = mysql_select_db($dbname);
    if(!$db_selected)
    {
           $db_selected = " CREATE DATABASE $dbname ";
    }
    $usertb1 = mysql_query("select 1 from $usertb LIMIT 1");
    if( $usertb1 !== FALSE )
    {
           $sql = "CREATE TABLE $usertb( uid INT(20) AUTO_INCREMENT UNIQUE KEY NOT NULL,name VARCHAR(40),email varchar(40) PRIMARY KEY NOT NULL)";
    }
    $typetb1 = mysql_query("select 1 from $typetb LIMIT 1");
    if( $typetb1 !== FALSE)
    {
           $sql1 = "CREATE TABLE $typetb( uid INT(20) NOT NULL, type ENUM('QUERYHOMEWEB','QUERYHOMEAPP','ANSWERCART') NOT NULL ,unsubscribe TINYINT(1) NOT NULL,bounce TINYINT(1) NOT NULL,complaint TINYINT(1) NOT NULL, PRIMARY KEY (uid,type), FOREIGN KEY(uid) WHERE promo_user(uid))";
    }

请告诉我这段代码有什么问题。

1 个答案:

答案 0 :(得分:0)

您需要将CREATE TABLE的sql更改为CREATE TABLE IF NOT EXISTS

$conn = mysql_connect($dbhost, $dbuser, $dbpass);
    if(!$conn)
    {
            die('Failed to connect to server: ' . mysql_error());
            exit;
    }
    $db_selected = mysql_select_db($dbname);
    if(!$db_selected)
    {
           $db_selected = " CREATE DATABASE $dbname ";
    }
    $usertb1 = mysql_query("select 1 from $usertb LIMIT 1");
    if( $usertb1 !== FALSE )
    {
           $sql = "CREATE TABLE IF NOT EXISTS $usertb( uid INT(20) AUTO_INCREMENT UNIQUE KEY NOT NULL,name VARCHAR(40),email varchar(40) PRIMARY KEY NOT NULL)";
    }
    $typetb1 = mysql_query("select 1 from $typetb LIMIT 1");
    if( $typetb1 !== FALSE)
    {
           $sql1 = "CREATE TABLE IF NOT EXISTS $typetb( uid INT(20) NOT NULL, type ENUM('QUERYHOMEWEB','QUERYHOMEAPP','ANSWERCART') NOT NULL ,unsubscribe TINYINT(1) NOT NULL,bounce TINYINT(1) NOT NULL,complaint TINYINT(1) NOT NULL, PRIMARY KEY (uid,type), FOREIGN KEY(uid) WHERE promo_user(uid))";
    }