Corfitz.
Corfitz.

Reputation: 1884

PDO MySQL check if database exists

What would be the proper way of asking wether or not a SCHEMA exists in a MySQL Database?

I am programming in PDO and basically my script should be something like this:

if (databaseExists($db)) {
    // Do something
}

And for the function:

function databaseExists($db) {
     SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = $db;
     if so - return true;
     else - return false;
}

My question is actually, how to implement the SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = $db statement. Do I have to use a $conn which doesn't have a database defined? And how would I return the results? Do I have to fetch the data, or is it just possible to make a count?

Upvotes: 0

Views: 5128

Answers (1)

Chris
Chris

Reputation: 754

Just create your connection directly to the info schema and run your query.

$pdo = new PDO(
               'mysql:host=hostname;dbname=INFORMATION_SCHEMA',
               'username',
               'password'
);

From there, your function should work once build out.

Upvotes: 3

Related Questions