How to Create MySQL Database Using PHP Functions

PHP Functions to Create MySQL Database

To access and manipulate MySQL database, you have to first create MySQL database. You can create MySQL database easily by using the PHP functions and MySQL query. The execution of the MySQL query can be done by using the PHP.

In the older version of the PHP, developers used mysql_create_db() function. But, since from PHP 4.3, The function mysql_create_db() is depreciated and cannot be used anymore.

There are two alternatives you can use to create MySQL database.

  1. mysqli_query()
  2. pdo::__query()

Which Function is Suitable to Create MySQL Database

You can use both mysqli and PDO functions to create MySQL database. The mysqli supports both procedural and object-oriented API but PDO supports only the Object-oriented API.

PDO supports more than twelve databases and mysqli supports only MySQL database. However, MySQL provides the easiest interface to use and execute a query and create a database.

If you have decided to not to move from MySQL database to other, mysqli is the best choice for your project.

How to Create MySQL Database Using PHP

Below are the syntaxes you can use to execute the query and create mysql database using PHP.

Using mysqli Procedural
The mysqli procedural is the simplest way to understand PHP coding for developers. You can use this method to create a database for your project.

Below is the simple example to use in your project and test it in the local Xamp or Wamp server. The hostname, username, and password are given below taken for the localhost. If you using another server, you can change the below-given credentials.

Using mysqli Object-oriented
Developing an application, Object-oriented is the best practice to design an code. You can make the database connection, create a query and execute the query using PHP object-oriented programming.

The process is same but the way of coding is different. Below is the object-oriented way of coding you can use and copy to your project code to create a database using PHP.