How do I create a database if it doesn't exist, using PHP?

后端 未结 2 1021
迷失自我
迷失自我 2021-01-13 08:47

How do I create a database if it doesn\'t exist, using PHP?

2条回答
  •  梦毁少年i
    2021-01-13 09:32

    Since you mention WAMP I'll assume you're talking about MySQL.

    It can be tricky. Assuming that your PHP script runs with all the required credentials (which is by itself a questionable idea), you can run this query:

    SHOW DATABASES
    

    If the DB does not show up there, you can assume it doesn't exist and create it with one of these queries:

    CREATE DATABASE foo ....
    

    or:

    CREATE DATABASE IF NOT EXISTS foo ...
    

    Right after that, you need to check the return value for whatever PHP function you are using (e.g. mysql_query). The above queries will fail if your user is now allowed to see all the existing databases or it's not allowed to create new databases.

    In general, I find the whole concept kind of scary. Handle it with care! ;-)

提交回复
热议问题