这是代码
<?php
$servername = "localhost";
$usrname = "root";
$pwd = "";
$db = "test_db";
// connect to the database
$conn= mysqli_connect($servername, $usrname, $pwd,$db);
if (!$conn){
die('connection failed' . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE IF NOT EXISTS test_db";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully<br>";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
?>
我不确定发生了什么,因为我确信我在打字时没有犯错误。尽管我做了 CREATE DATABASE 语句,但它不断向我显示有一个未知的数据库。 我不知道是否还需要做其他事情,但从所有方面来看,代码应该可以工作。 它应该回显“数据库创建成功”或错误消息。
`<?php
$servername = "localhost";
$usrname = "root";
$pwd = "";
//$db = "test_db";
// connect to the database
$conn= mysqli_connect($servername, $usrname, $pwd);
if (!$conn){
die('connection failed' . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE IF NOT EXISTS test_db";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully<br>";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
?>`
您的代码很好,您只需从 mysqli_connect() 中删除 $db 即可。 因为您请求将“test_db”连接到该数据库,但该数据库尚不存在。
公共函数__construct(){ if (!isset($this->conn)) { $this->conn = new mysqli($this->主机, $this->用户名, $this->密码, $this->数据库);
if ($this->conn->connect_error) {
die('Cannot connect to the database server: ' . $this->conn->connect_error);
}
}
}
<?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);
?>
$conn= mysqli_connect($servername, $usrname, $pwd,$db);
您正在尝试连接到最初不存在的数据库,因此您会收到致命错误。
尝试使用 try catch 块创建新数据库
try{
$conn= mysqli_connect($servername, $usrname, $pwd,$db);
}cath(Exception $e){
//your code
}