PHP Create a MySQL Database

Creating a MySQL database using PHP involves executing a SQL query that creates a new database. Here’s an example of how to create a new MySQL database using PHP:

// MySQL server configuration
$servername = "localhost";
$username = "root";
$password = "";
// Create a connection
$conn = mysqli_connect($servername, $username, $password);
// Check the connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
// Create a new database
$dbname = "mydatabase";
$sql = "CREATE DATABASE $dbname";
if (mysqli_query($conn, $sql)) {
    echo "Database created successfully";
} else {
    echo "Error creating database: " . mysqli_error($conn);
// Close the connection

In this example, we first define the configuration for the MySQL server by specifying the server name, username, and password. We then create a connection to the server using the mysqli_connect() function and store the connection in a variable called $conn. We check if the connection was successful using the mysqli_connect_error() function and terminate the script if there was an error.

Next, we define the name of the new database we want to create in the $dbname variable and create a SQL query that creates a new database using the CREATE DATABASE statement. We then execute the query using the mysqli_query() function and check if it was successful. If it was successful, we print a message indicating that the database was created successfully. Otherwise, we print an error message with the details of the error using the mysqli_error() function.

Finally, we close the connection using the mysqli_close() function.