Reputation: 8604
I have this code:
if(!mysql_connect($host,$user,$passwd)){ die("Hoops, error! ".mysql_error()); }
...no error from here.
if(!mysql_select_db($db,$connect)){
$create_db = "CREATE DATABASE {$db}";
mysql_query($create_db,$connect);
mysql_query("USE DATABASE {$db}",$connect);
}
..."no database selected" error from here. I would like to select database if it exists and if doesn't then create it and select it.
Why is my code not right?
Thank you in advance
Upvotes: 0
Views: 1592
Reputation: 8604
I would like to thank to all of you, however I found fault on my side. This script was in class and one of variables were not defined inside this class. So I'm really sorry. I don't know how to consider the right answer, but I noticed my mistake after reading Clayton's answer about not properly set parameters, so I guess he is the winner ;)
Upvotes: 0
Reputation: 901
you could try w3schools website. They have a very simple and easy to learn tutorial for selecting database. The link is : http://www.w3schools.com/php/php_mysql_select.asp Hope this help :)
Upvotes: 0
Reputation: 2960
Where are you saving the value returned by mysql_connect()? Don't see it here. I assume $host, $user, $password and $db are properly set ahead of time. But you're passing a param to mysql_select_db that may not be properly set.
$connect = mysql_connect($host,$user,$passwd);
if (!$connect) {
die('Could not connect: ' . mysql_error());
}
if(!mysql_select_db($db,$connect)) ...
Start by checking to see if you can select without the CREATE query first. Try a simple SELECT query to start. If you can connect, select the db, and execute a SELECT query, that's one step. Then try the CREATE query. If that doesn't work, it's almost certainly a matter of permissions.
Upvotes: 3
Reputation: 15320
Why not simply use the CREATE DATABASE IF NOT EXISTS syntax instead?
Something like this ...
$con = mysql_connect('localhost');
$sql = 'CREATE DATABASE IF NOT EXISTS {$db}';
if (mysql_query($sql, $con)) {
print("success.\n");
} else {
print("Database {$db} creation failed.\n");
}
if(!mysql_select_db($db,$connect)){
print("Database selection failed.\n");
}
Upvotes: 1
Reputation: 25205
You might need database create permissions for the user attempting to create the database. Then you need to operate on a valid connection resource. $connect never looks to be assigned to the connection resource.
Upvotes: 1
Reputation: 267059
Change the line
mysql_query($create_db,$connect);
mysql_query("USE DATABASE {$db}",$connect);
To
mysql_query($create_db,$connect);
mysql_select_db($db);*
and it should work.
Upvotes: 0
Reputation: 57815
You should check the return value of mysql_query() - currently if any of those calls fail you won't know about it:
if(!mysql_select_db($db,$connect)){
if (!mysql_query("CREATE DATABASE $db", $connect)) {
die(mysql_error());
}
if (!mysql_select_db($db, $connect)) {
die(mysql_error());
}
}
Upvotes: 0