1

I want my php code to check whether a certain DB exists, by means of running some sql query andd parsing the result.

What would be a nice way to do it?

Thanks

Gidi

4 Answers 4

1

Run SHOW DATABASES and loop over the results with PHP to check for the existence.

If it were only one database, you could also add a condition to the SQL query directly and simply check if it returned a result or not with PHP. This would avoid the loop.

Sign up to request clarification or add additional context in comments.

2 Comments

what do you mean by condition? I am looking for one certain db
Yeah, just one database add the LIKE condition. See middaparka's example or the docs.
1

As a simple solution, you could just use:

SHOW DATABASES LIKE <YOUR DB NAME>;

See the SHOW DATABASES Syntax manual page for more information.

Comments

1

I suppose you could connect to your server, and issue a show databases statement.

It'll get you a list of all database that you can access, on your server.


I suppose you could also connect to your server, and, then, call [`mysql_select_db()`][2] or [`mysqli::select_db()`][3], to try connecting to your specific database.

If it doesn't exist, that function will most likely fail -- and return false.

Comments

1

Keeping it in code, you could do

mysql_connect('host','user','pass');
$dbExists=mysql_select_db('db_name');

Might be quicker too.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.