检查数据库是否存在(MySQL),如果不存在,则在 PHP 中创建
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4288555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a database exist (MySQL) and if not create it in PHP
提问by DomingoSL
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 脚本来检查数据库(在本地主机中,user="root", pass="")“data1”是否存在,如果不存在,则创建它。请感谢您可以为我提供的任何帮助。
回答by tim
CREATE DATABASE IF NOT EXISTS DBName;
回答by leepowers
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');
}
回答by basarat
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