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

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

How can I see these warnings ?
You can use mysqli_get_warnings(). see php.net/manual/en/mysqli.get-warnings.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.