如果不存在则使用 mysqli + php 创建数据库

Create DB if not exists using mysqli + php

如果数据库名称不存在,我正在尝试使用 mysqli 创建一个数据库,使用以下代码:

<?php

$link = mysqli_connect("localhost", "root", "", "php1") ; 
if(mysqli_connect_errno()){
    echo mysqli_connect_error();
    $query = "CREATE DATABASE php1";
    if(mysqli_query($link, $query)){
        echo "Success";
    } else {
        echo "Failure";
    }
}


?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>        
        <a href="signup.php"><button type="button">Sign Up!</button></a>
        <a href="login.php"><button type="button">Log In</button></a>
    </body>
</html>

代码检查了数据库,但它不存在。接下来我想创建数据库,如果它不存在但我总是收到以下错误:

Warning: mysqli_connect(): (HY000/1049): Unknown database 'php1' in E:\xampp\htdocs\PhpProject1\index.php on line 3

Unknown database 'php1'

Warning: mysqli_query() expects parameter 1 to be mysqli, boolean given in E:\xampp\htdocs\PhpProject1\index.php on line 7

Failure

这样我无法创建新的数据库。有人知道如何纠正这个问题吗?

解决此问题的三个步骤:

  1. 连接时不要指定数据库名称。
  2. 你的 SQL 语句应该是 CREATE DATABASE IF NOT EXISTS php1.
  3. 调用 mysqli_select_db($link, 'php1') 使其成为您连接的默认数据库。
// Enable error reporting for mysqli
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Connection to MySQL server without database name.
$connect = new mysqli('localhost', 'my_user', 'my_password');

// Set the desired charset after establishing a connection
$connect->set_charset('utf8mb4');

// Create database if not exists.
$databaseName = 'database_name';
$query = 'CREATE DATABASE IF NOT EXISTS ' . $databaseName;

// Use the new database for all future SQL queries.
mysqli_select_db($connect, $databaseName);

More information about mysqli_connect : https://www.php.net/manual/en/mysqli.construct.php

$connection = '';
$connection = new mysqli("db", "root", "example");
$query = mysqli_query($connection, "SHOW DATABASES LIKE 'company'");
$result = mysqli_num_rows($query);

if($result <=0){
$create = mysqli_query($connection, "CREATE DATABASE IF NOT EXISTS company;");
echo "Database created successifully";
}