...

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



starvos
03-22-2010, 11:39 AM
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;
break;
}
}
}
fclose($fp);


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~

angst
03-22-2010, 02: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.

starvos
03-23-2010, 02: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"?

starvos
03-23-2010, 02: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"));

to


$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~:)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum