PHP MySQL Create Database


A database holds one or more tables.

You need CREATE permission to create or delete a MySQL database.


Create MySQL Database Using MySQLi and PDO

The CREATE DATABASE statement is used to create a database in MySQL.

In the example below, a database named "myDB" is created:

Example (MySQLi - Object-oriented)

<?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); } //Create database $sql = "CREATE DATABASE myDB"; if ($conn->query($sql) === TRUE) { echo "Database created successfully"; } else { echo "Error creating database: " . $conn->error; } $conn->close(); ?>


Note Note:When you create a new database, you must specify three parameters (servername, username, and password) for the mysqli object.

Tip:If you use a different port (default is 3306), add an empty string for the database parameter, e.g.: new mysqli("localhost", "username", "password", "", port)

Example (MySQLi Procedural)

<?php $servername = "localhost"; $username = "username"; $password = "password"; //Create connection $conn = mysqli_connect($servername, $username, $password); //Check connection if (!$conn) { die("Connection failed:" . mysqli_connect_error()); } //Create database $sql = "CREATE DATABASE myDB"; if (mysqli_query($conn, $sql)) { echo "Database created successfully"; } else { echo "Error creating database: " . mysqli_error($conn); } mysqli_close($conn); ?>

Note:The following example creates a database using PDOmyDBPDO :

Example

Using PDO:

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

try {
    
$conn = new PDO("mysql:host=$servername", $username, $password);

    
// Set PDO error mode to exception
    
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
$sql = "CREATE DATABASE myDBPDO";

    
// Use exec() because no results are returned
    
$conn->exec($sql);

    echo
"Database created successfully<br>";
}
catch(
PDOException $e)
{
    echo
$sql . "<br>" . $e->getMessage();
}

$conn = null;
?>

Tip:The biggest benefit of using PDO is that when a problem occurs during database queries, the exception class can be used to handle the problem. If an exception occurs in the try{ } block, the script will stop executing and jump to the first catch(){ } block to execute code. In the above caught block, we output the SQL statement and generate an error message.

Other Extensions