开发者

PHP & MYSQL: checking whether certain DB exists in the server, from a php code executing mysql command

开发者 https://www.devze.com 2023-02-28 15:34 出处:网络
I want my php code to check whether a certain DB exists, by means of running some sql query andd parsing the result.

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 ni开发者_运维知识库ce way to do it?

Thanks

Gidi


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.


As a simple solution, you could just use:

SHOW DATABASES LIKE <YOUR DB NAME>;

See the SHOW DATABASES Syntax manual page for more information.


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() or mysqli::select_db(), to try connecting to your specific database.

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


Keeping it in code, you could do

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

Might be quicker too.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号