So i want to write a php script who checks in the data base (in localhost, user="root", pass="") "data1" exists, and if is not, create it. Please thanks for any help you can give me with this.
Asked
Active
Viewed 3.6k times
3 Answers
29
CREATE DATABASE IF NOT EXISTS DBName;

tim
- 970
- 4
- 12
- 20
-
2i need to know in php if the data base exist, how can i? – DomingoSL Nov 26 '10 at 21:19
11
Check the return value of mysql_select_db
- this function will return true when the database exists and can be selected - i.e., the database might exist but the current user may not have permission to access the database. This may be enough to determine in PHP if the database exists - as long as you can guarantee that the PHP MySQL database user will always have access to this database when it exists.
mysql_connect('localhost', 'root', '');
if (!mysql_select_db('mydb')) {
echo("creating database!\n");
mysql_query('CREATE DATABASE mydb');
mysql_select_db('mydb');
}

leepowers
- 37,828
- 23
- 98
- 129
-
mysql(i)_select_db is intended to only to change the default database for the connection and you already need a connection to test it. So while it may work, probably not the best solution. – ılǝ Feb 13 '14 at 11:45
1
Send the following to mysql from your php code :
CREATE DATABASE IF NOT EXISTS YourDB;
Documentation : http://dev.mysql.com/doc/refman/5.0/en/create-database.html

basarat
- 261,912
- 58
- 460
- 511
-
-
Try connecting to the database. If it succeeds the database is there. If it does not observe the error to determine the cause :) – basarat Nov 26 '10 at 21:22
-
Or you can use the method documented here as the accepted solution : http://stackoverflow.com/questions/838978/how-to-check-if-mysql-database-exists – basarat Nov 26 '10 at 21:23