What are the best practices for checking if a database exists in PHP before creating it?

When creating a new database in PHP, it is important to check if the database already exists to avoid errors or overwriting existing data. One way to do this is by querying the information_schema database to see if the desired database name already exists. If the database does not exist, then you can proceed with creating it.

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Check if the database exists
$result = $conn->query("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'your_database_name'");

if ($result->num_rows == 0) {
    // Database does not exist, create it
    $sql = "CREATE DATABASE your_database_name";
    if ($conn->query($sql) === TRUE) {
        echo "Database created successfully";
    } else {
        echo "Error creating database: " . $conn->error;
    }
} else {
    echo "Database already exists";
}

$conn->close();
?>