PHP MySQL Create Database
Using PHP to Create a MySQL Database
Now that you know how to bind to the MySQL database server, let's move on to the next phase. This tutorial will teach you how to build a database using SQL queries.
We must first build a database before we can save or access the data. To create a new database in MySQL, use the CREATE DATABASE
expression.
Let's start by creating a SQL query with the Build DATABASE expression, then passing it to the PHP mysqli query()
function to execute it and finally create our database. The example below generates a database called prototype.
<?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();
?>