我想创建一个数据库。为什么不使用此代码创建数据库?
$dbname = 'regulations_db';
$con = mysql_connect("localhost","root","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_num_rows(mysql_query("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '". $dbname ."'"))) {
echo "Database $dbname already exists.";
}
else {
mysql_query("CREATE DATABASE '". $dbname ."'",$con);
echo "Database $dbname created.";
}
这是有效的,但我认为第一个是最佳做法:
if (mysql_query("CREATE DATABASE IF NOT EXISTS regulations_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
答案 0 :(得分:19)
只需做一个简单的mysql_select_db()
,如果结果为假,则继续创建。
例如,请使用另一个非常智能的StackOverflower查看the first answer here。
<?php
// Connect to MySQL
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// Make my_db the current database
$db_selected = mysql_select_db('my_db', $link);
if (!$db_selected) {
// If we couldn't, then it either doesn't exist, or we can't see it.
$sql = 'CREATE DATABASE my_db';
if (mysql_query($sql, $link)) {
echo "Database my_db created successfully\n";
} else {
echo 'Error creating database: ' . mysql_error() . "\n";
}
}
mysql_close($link);
?>
答案 1 :(得分:5)
解决此问题的三个步骤:
答案 2 :(得分:1)
如果您使用的是MySQLi面向对象的方法,则可以使用以下代码,此代码与先前的答案类似,只是该方法有所不同,我只是说这是因为如果有人使用MySQLi的面向对象的方法,则可以直接使用此代码。
$servername = "localhost";
$username = "mysql_user";
$password = "user_password";
$dbName = "databaseName";
// Connect to MySQL
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// If database is not exist create one
if (!mysqli_select_db($conn,$dbName)){
$sql = "CREATE DATABASE ".$dbName;
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
}else {
echo "Error creating database: " . $conn->error;
}
}
此外,您可以参考W3school网站here.
祝你好运! :D