In the previous tutorial, we learned to establish a connection between PHP and MySQL using MySQLi and PDO. After making the connection, the very next step is to create a database. In this article, you will learn how to create a MySQL database in PHP.

Create New Database using MySQLi (object-oriented)

PHP provides CREATE DATABASE statement to the new database. In the following example, we will create a new database “firstDB”.

<?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: In the above example, you can see that the mysqli object is receiving three arguments $servername, $username, and $password.

  • However, this object receive more than three arguments for some other configurations, but these three arguments are mandatory to establish the connection.
  • If you want to set empty string for database, pass “” in the fourth parameter of the mysqli function.
  • Like, if you want to specify the port number at which the connection should establish between the PHP and MySQL, pass the port number as the fifth parameter of the mysqli object.

Create New Database using 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);
?>

Create New Database using PDO

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

try {
  $conn = new PDO("mysql:host=$servername", $username, $password);
  // set the 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;
?>

Using PDO is a great way to catch errors in the database queries or connections. As we can write the connection or query code in try {} block. If the connection or query produces any error, it will be caught in the catch {} block.

Reference to the MySQL official documentation to create a database here.