检查数据库是否存在(MySQL),如果没有在PHP中创建它

时间:2022-09-25 23:21:09

So i want to write a php script who checks in the data base (in localhost, user="root", pass="") "data1" exists, and if is not, create it. Please thanks for any help you can give me with this.

因此我想编写一个php脚本,它检查数据库(在localhost中,user="root", pass="")“data1”存在,如果不是,创建它。谢谢你给我的帮助。

4 个解决方案

#1


27  

CREATE DATABASE IF NOT EXISTS DBName;

#2


11  

Check the return value of mysql_select_db - this function will return true when the database exists and can be selected - i.e., the database might exist but the current user may not have permission to access the database. This may be enough to determine in PHP if the database exists - as long as you can guarantee that the PHP MySQL database user will always have access to this database when it exists.

检查mysql_select_db的返回值——当数据库存在并可以被选中时,该函数将返回true—即。,数据库可能存在,但当前用户可能没有权限访问数据库。这可能足以在PHP中确定数据库是否存在——只要您能够保证PHP MySQL数据库用户在该数据库存在时始终能够访问该数据库。

mysql_connect('localhost', 'root', '');
if (!mysql_select_db('mydb')) {
    echo("creating database!\n");
    mysql_query('CREATE DATABASE mydb');
    mysql_select_db('mydb');
}

#3


1  

Send the following to mysql from your php code :
CREATE DATABASE IF NOT EXISTS YourDB;
Documentation : http://dev.mysql.com/doc/refman/5.0/en/create-database.html

从php代码中向mysql发送以下命令:如果不存在数据库,则创建数据库;文档:http://dev.mysql.com/doc/refman/5.0/en/create-database.html

#4


0  

If you want to use PHP to check if database exists or not, you can try this, someone has already answered it.

如果你想用PHP检查数据库是否存在,你可以尝试一下,有人已经回答过了。

#1


27  

CREATE DATABASE IF NOT EXISTS DBName;

#2


11  

Check the return value of mysql_select_db - this function will return true when the database exists and can be selected - i.e., the database might exist but the current user may not have permission to access the database. This may be enough to determine in PHP if the database exists - as long as you can guarantee that the PHP MySQL database user will always have access to this database when it exists.

检查mysql_select_db的返回值——当数据库存在并可以被选中时,该函数将返回true—即。,数据库可能存在,但当前用户可能没有权限访问数据库。这可能足以在PHP中确定数据库是否存在——只要您能够保证PHP MySQL数据库用户在该数据库存在时始终能够访问该数据库。

mysql_connect('localhost', 'root', '');
if (!mysql_select_db('mydb')) {
    echo("creating database!\n");
    mysql_query('CREATE DATABASE mydb');
    mysql_select_db('mydb');
}

#3


1  

Send the following to mysql from your php code :
CREATE DATABASE IF NOT EXISTS YourDB;
Documentation : http://dev.mysql.com/doc/refman/5.0/en/create-database.html

从php代码中向mysql发送以下命令:如果不存在数据库,则创建数据库;文档:http://dev.mysql.com/doc/refman/5.0/en/create-database.html

#4


0  

If you want to use PHP to check if database exists or not, you can try this, someone has already answered it.

如果你想用PHP检查数据库是否存在,你可以尝试一下,有人已经回答过了。