如果它不存在它如何创建一个表使用PHP的数据库?

I am tring to create a new database and new table if they dont exists in the sql. when i execute this code twice it works fine but when i execute it first time it does not create the table. the below is the code that i am using

$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);
        }

please Help.

When you run this the first time, you are checking if the db exists and if not exists you are creating one. But I think you need to do a

$db_selected = mysql_select_db($dbname);

after creating the database.

So you snippet will change to

$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);
}