In the earlier article we saw how databases can be created via MySQL command prompt or PhpMyadmin if you are using wamp or xamp. From this article onward, we shall see how PHP script is used to perform data manipulation tasks. In this article, we shall see how to create database.
The query to create database is as follows.
CREATE DATABASE dbname
Creating Database via Object Oriented MySQLi
To create database via object oriented MySQLi, you simply need to create object of mysqli and call the query function on it. The database generation query is passed to this function as a parameter. Have a look at the following example.
Using MySQLi for Database Creation connect_error) { die("Connection not established: " . $connection->connect_error); } // Creating Database $query = "CREATE DATABASE Patient"; if ($connection->query($query) === TRUE) { echo "Successful database creation"; } else { echo "Unable to create database " . $connection->error; } $connection->close(); ?>
The above code creates a database named ‘Patient’ from the server
Creating Database via Procedural MySQLi
For procedural MySQLi database creation simple replace mysqli object creation with mysqli_connect function. This is demonstrated in the following example.
Using MySQLi for Database creation connect_error) { die("Connection not established: " . $connection->connect_error); } // Creating Database $query = "CREATE DATABASE Patient"; if ($connection->query($query) === TRUE) { echo "Successful database creation"; } else { echo "Unable to create database " . $connection->error; } $connection->close(); ?>
It is pertinent to mention that close function is being called on the $connection object. This function basically closes PHP’s connection with the database.