Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a database exist (MySQL) and if not create it in PHP

Tags:

php

mysql

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.

like image 202
DomingoSL Avatar asked Nov 26 '10 21:11

DomingoSL


2 Answers

CREATE DATABASE IF NOT EXISTS DBName;
like image 116
tim Avatar answered Sep 21 '22 05:09

tim


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');
}
like image 41
leepowers Avatar answered Sep 23 '22 05:09

leepowers