MySQLi - Create Database
A database consists of one or more tables. To create or to delete a MySQL database, appropriate privilege is required. Along with this, the database name should be unique within the RDBMS.
The CREATE DATABASE statement is used to create a database in MySQL. For example, to create a database named "myDatabase", the following query can be used:
CREATE DATABASE myDatabase
Along with this, to connect to the MySQL server, mysqli_connect() function can be used. After establishing the connection, mysqli_query() function can be used to perform the query to create a new database.
Create a MySQL Database - Object-oriented style
The example below demonstrates how to create a database named "myDatabase" in object-oriented style.
<?php $servername = "localhost"; $username = "username"; $password = "password"; //establishing connection $mysqli = new mysqli($servername, $username, $password); //checking connection if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: ". $mysqli->connect_error; exit(); } //query for creating database $sql = "CREATE DATABASE myDatabase"; //executing the query if (!$mysqli->query($sql)) { echo "Error creating database: ". $mysqli->error; } else { echo "Database created successfully."; } //closing the connection $mysqli->close(); ?>
Create a MySQL Database - Procedural style
To obtain the same result using procedural style, the following script can be used.
<?php $servername = "localhost"; $username = "username"; $password = "password"; //establishing connection $mysqli = mysqli_connect($servername, $username, $password); //checking connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: ". mysqli_connect_error(); exit(); } //query for creating database $sql = "CREATE DATABASE myDatabase"; //executing the query if (!mysqli_query($mysqli, $sql)) { echo "Error creating database: ". mysqli_error($mysqli); } else { echo "Database created successfully."; } //closing the connection mysqli_close($mysqli); ?>
Complete MySQLi Reference
For a complete reference of all properties, methods and functions of PHP MySQLi extension, see MySQLi Reference.