PHP MySQL Create Database

Creating MySQL Database Using PHP

Now that you know how to establish a connection to the MySQL database server, let's proceed to create a database using SQL queries.

Before storing or accessing data, it's essential to create a database. The CREATE DATABASE statement in MySQL is used for this purpose.

Here's an example of using the CREATE DATABASE statement in SQL, which we will execute using the PHP mysqli_query() function to create a database named demo:

Example

Procedural Object Oriented PDO
Download
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "");

// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Attempt create database query execution
$sql = "CREATE DATABASE demo";
if(mysqli_query($link, $sql)){
echo "Database created successfully";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

// Close connection
mysqli_close($link);
?>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$mysqli = new mysqli("localhost", "root", "");

// Check connection
if($mysqli === false){
die("ERROR: Could not connect. " . $mysqli->connect_error);
}

// Attempt create database query execution
$sql = "CREATE DATABASE demo";
if($mysqli->query($sql) === true){
echo "Database created successfully";
} else{
echo "ERROR: Could not able to execute $sql. " . $mysqli->error;
}

// Close connection
$mysqli->close();
?>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
try{
$pdo = new PDO("mysql:host=localhost;", "root", "");
// Set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
die("ERROR: Could not connect. " . $e->getMessage());
}

// Attempt create database query execution
try{
$sql = "CREATE DATABASE demo";
$pdo->exec($sql);
echo "Database created successfully";
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}

// Close connection
unset($pdo);
?>

Tip: By setting the PDO::ATTR_ERRMODE attribute to PDO::ERRMODE_EXCEPTION, PDO will throw exceptions whenever a database error occurs, providing more robust error handling in your PHP applications.