View Full Version : Problem with creating new database/tables using php

03-22-2010, 12:39 PM
I have saved the following codes as ini.php and tables.sql basically consist of mysql tables creation/insertion commands. However, I have to run the php script twice, first run will only give me the new database but no tables, only after the second run will I get the tables with the data inserted.

$user_name = "user";
$pass_word = "pass";
$database = "db";
$server = "localhost";
$db_handle = mysql_connect($server, $user_name, $pass_word) or die ("unable to connect to server");
$db_found = mysql_select_db($database, $db_handle) or die (mysql_query("CREATE DATABASE $database"));
$queryFile = 'tables.sql';
$fp = fopen($queryFile, 'r');
$sqlFile = fread($fp,filesize($queryFile));
$sqlArray = explode(';',$sqlFile);
foreach ($sqlArray as $query) {
if (strlen($query)>3){
$result = mysql_query($query,$db_handle);
if (!$result){
$sqlErrorCode = mysql_errno();
$sqlErrorText = mysql_error();
$sqlquery = $query;

Can any expert out there please tell me what have I done wrongly? And how can I achieve the creation of database & tables in one single run? Thanks in advance~

03-22-2010, 03:21 PM
right here;

$db_found = mysql_select_db($database, $db_handle) or die (mysql_query("CREATE DATABASE $database"));

your trying to select the data base, and if it doesn't exist you create it, however then you try to continue on without selecting the new database,

see what I mean? to fix, use the select db again after you create it.

03-23-2010, 03:17 AM
Where should I place the select db command? I tried after this line but it gives me the same problem.

$db_found = mysql_select_db($database, $db_handle) or die (mysql_query("CREATE DATABASE $database"));

Maybe I shouldn't try creating the database after "or die"?

03-23-2010, 03:26 AM
Nevermind, I have solved the problem by changing the line

$db_found = mysql_select_db($database, $db_handle) or die (mysql_query("CREATE DATABASE $database"));


$db_found = mysql_select_db($database, $db_handle);// or die (mysql_query("CREATE DATABASE $database"));
if (!$db_found){
mysql_query("CREATE DATABASE $database");
else {
$db = mysql_select_db($database, $db_handle);

Thanks for pointing out to use the select db again~:)