1

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); 
    ?>
ADyson
  • 57,178
  • 14
  • 51
  • 63
mateoo88
  • 33
  • 7
  • you could query the schema, then decide if to create the table or not, example: http://sqlfiddle.com/#!9/a6c585/214013/0 – Lawrence Cherone Aug 14 '21 at 00:40
  • You need to stop manually checking for errors. Please read: [Should we ever check for mysqli_connect() errors manually?](https://stackoverflow.com/q/58808332/1839439) and [Should I manually check for errors when calling “mysqli_stmt_prepare”?](https://stackoverflow.com/q/62216426/1839439) – Dharman Aug 14 '21 at 10:24

1 Answers1

2

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);
}
lefred
  • 111
  • 3