如果它们在sql中不存在,我想创建一个新的数据库和新表。当我执行此代码两次它工作正常,但当我第一次执行它时,它不会创建表。 以下是我正在使用的代码
$dbhost = '7.0.0.1';
$dbuser = 'root';
$dbpass = '123';
$dbname = 'promo_gmail';
$maxcharinaline = 1000;
$delimeter = ',';
$usertb = "promo_userb";
$typetb = "promo_typeb";
// Now just insert the data one by one assuming its valid
{
$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";
}
mysql_query($db_selected,$conn);
$usertb1 = mysql_query("select 1 from $usertb LIMIT 1");
if( $usertb1 == FALSE )
{
$usertb1 = "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)";
mysql_query($usertb1,$conn);
}
$typetb1 = mysql_query("select 1 from $typetb LIMIT 1");
if( $typetb1 == FALSE )
{
$typetb1 = "CREATE TABLE IF NOT EXISTS $typetb ( uid INT(20) , type ENUM('WEB','APP','AT') NOT NULL ,unsubscribe TINYINT(1) NOT NULL,bounce TINYINT(1) NOT NULL,complaint TINYINT(1) NOT NULL, FOREIGN KEY (uid) REFERENCES promo_user (uid) , PRIMARY KEY (uid,type))";
mysql_query($typetb1,$conn);
}
请帮助。
答案 0 :(得分:0)
第一次运行时,您正在检查数据库是否存在,如果不存在,则表示您正在创建数据库。但我认为你需要做一个
$db_selected = mysql_select_db($dbname);
创建数据库后。
因此,您的代码段将更改为
$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";
}
//Create the new database
mysql_query($db_selected,$conn);
//Select the new database
$db_selected = mysql_select_db($dbname);
//Go ahead with your table queries
$usertb1 = mysql_query("select 1 from $usertb LIMIT 1");
if( $usertb1 == FALSE )
{
$usertb1 = "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)";
mysql_query($usertb1,$conn);
}