简体   繁体   中英

Check if database already exists

I want the database to be created only if it does not exist. Now that the database exist, nothing happening but the following message is displayed anyway: Database created successfully. I would like this message to be displayed only when the database is created and not when it already exists. How to check if a database exists? This is my code.

<?php
 
    $mysql = @mysqli_connect("localhost", "test", "test"); 

    if(!($mysql)) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
        exit();
      }

    $myDB = "CREATE DATABASE IF NOT EXISTS myDB";

    if ((mysqli_query($mysql, $myDB))) {
        echo "Database created successfully";
      } else {
        echo "Error creating database: " . mysqli_error($mysql);
      }


      mysqli_close($mysql); 
    ?>

When you try to create a database with IF NOT EXISTS in MySQL, a warning is also returned.

I would then suggest to check for the eventual returned warning like this:

$myDB = "CREATE DATABASE IF NOT EXISTS myDB";

if ((mysqli_query($mysql, $myDB))) {
       if (mysqli_warning_count($mysql) == 0) { 
            echo "Database created successfully";
       }
} else {
       echo "Error creating database: " . mysqli_error($mysql);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM