PHP MySQL Create Database




In this source code example, we will see how to create a database in PHP using MySQLi.

PHP MySQL Create Database

Here is a PHP script that creates a database in MySQL server:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */

$host= "localhost";
$username= "root";
$password = "";

$mysql_connection = mysqli_connect($host, $username, $password);
 
// Check connection
if($mysql_connection === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
 
// Attempt create database query execution
$sql = "CREATE DATABASE demo_db";
if(mysqli_query($mysql_connection, $sql)){
    echo "Database created successfully";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($mysql_connection);
}
 
// Close connection
mysqli_close($mysql_connection);
?>
Output:
Database created successfully
Let's understand the above PHP script.

The mysqli_connect() function opens a new connection to the MySQL server:
$mysql_connection = mysqli_connect($host, $username, $password);
SQL query for creating a database:
$sql = "CREATE DATABASE demo_db";
The mysqli_query() function performs a query against a database:

if(mysqli_query($mysql_connection, $sql)){}
Closing MySQL server connection:
// Close connection
mysqli_close($mysql_connection);

Comments