Create MySQL Database

PHP Create a MySQL Database
  • In mysql database you can create database and in database create one or many data tables, but you need to be a create privileges for create a database.
  • For example to create a database
MySQLi Object-Oriented

If run program in your local server like XAMPP, WAMPP, etc. so your server credentials like...

$servername= "localhost";
$username = "root";
$password= ""; (blank)

<?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 student";

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

$conn->close();
?>

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 student";

if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

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 student";

// use exec() because no results are returned
$conn->exec($sql);
echo "Database created successfully
";
} catch(PDOException $e) {
echo $sql . "
" . $e->getMessage();
}

$conn = null;
?>