2

Basically, I want to create a database, but I know there will be problem if you want to create a mysql database that already exists. So how can I check if it already exists in PHP?

Here's the psuedo-code:

if (database exist)
{do nothing}

//if it doesn't exist
else 
{create the database}

Now I already know how to create the database it self. That's easy for me, I just don't know how to check if one already exists.

Ebadly.Decipher
  • 79
  • 2
  • 3
  • 10

4 Answers4

7
SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'DBName'

If you just need to know if a db exists so you won't get an error when you try to create it, simply use (From here):

CREATE DATABASE IF NOT EXISTS DBName;
Ronny K
  • 3,641
  • 4
  • 33
  • 43
4

All these return false if the DB can't be selected. This means it does not exists OR you don't have the permission to access.

bool mysql_select_db ( string $database_name [, resource $link_identifier = NULL ] )

bool mysqli_select_db ( mysqli $link , string $dbname )

Also possible with PDO. Or mysqli as object:

try {
    $mysqli = new mysqli("localhost", "my_user", "my_password");
} catch (\Exception $e) {
    echo $e->getMessage(), PHP_EOL;
}
if ($mysqli->select_db('your_database') === false) {
    // Create db
}
Daniel W.
  • 31,164
  • 13
  • 93
  • 151
1

Since you want to check if it exists and if it doesn't, you want to create it, you could do both at once. I assume you have the privileges necessary to perform the following action:

CREATE DATABASE IF NOT EXISTS <name of the database>;
federico-t
  • 12,014
  • 19
  • 67
  • 111
0

Just go ahead and attempt to create the table. MySQL will throw an error you can test for if the table already exists.

If you just want to avoid an error an have the table created anyway then you can add an IF NOT EXISTS clause to your CREATE statement.