php 致命错误:未捕获的mysqli_sql_异常错误:未知的数据库'test_db',即使我以编程方式创建了该数据库,我仍然不断收到此错误

ecbunoof  于 2022-11-28  发布在  PHP
关注(0)|答案(3)|浏览(248)

下面是代码

<?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语句,但它一直显示我有一个未知的数据库。我不知道是否还有其他事情需要做,但从所有方面来看,代码应该工作。它应该回显“数据库创建成功”或错误消息。

67up9zun

67up9zun1#

`<?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”到这个已经不存在的数据库。

nukf8bse

nukf8bse2#

<?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);
?>

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

tjrkku2a

tjrkku2a3#

如果您有任何问题,请与我们联系。
您正尝试连接到最初不存在的数据库,因此收到致命错误。
尝试使用try catch块创建新数据库

try{
$conn= mysqli_connect($servername, $usrname, $pwd,$db);
}cath(Exception $e){
//your code
}

相关问题