MYSQL Create Database

Last Updated: February 24, 2022

Use CREATE DATABASE command to create the database

Need CREATE privileges to create and delete MYSQL database

Example (MySQLi Object-oriented)

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

// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
echo 'Connected successfully<br/>';  

// Create database
$sql = "CREATE DATABASE invoiceDB";
if ($conn->query($sql) === TRUE) {
  echo "Database created successfully";
} else {
  echo "Error creating database: " . $conn->error;
}

$conn->close();
?> 

Output

Connected successfully
Database created successfully

If you need to specify the port number then you can use the following line of code

mysqli("localhost", "username", "password", "", port)

Example MYSQLi Procedural

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

// Create connection
$conn = mysqli_connect($host, $username, $password);
// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}

// Create database
$sql = "CREATE DATABASE invoiceDB";
if (mysqli_query($conn, $sql)) {
  echo "Database created successfully";
} else {
  echo "Error creating database: " . mysqli_error($conn);
}

mysqli_close($conn);
?> 

Example PDO

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

try {
  $conn = new PDO("mysql:host=$host", $username, $password);
  // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $sql = "CREATE DATABASE invoiceDB";
  // 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;
?> 
Test