The following program demonstrates Creating a Database and User Using PDO in PHP.

To begin with we need to be ready with the user’s name and database. So, first, we create the variables server, and user, and pass with the values localhost, root as the username, and a blank password. this is the default username and password available for every database in phpMyAdmin.

Since we want to create a database with a specified username, we need to have three more variables dbname, new_user, and new_pass containing specific values. In order to connect with the MySQL server, we need to create an object of the PDO class and pass the necessary parameters into its constructor.

Basically, the constructor of the PDO class takes four parameters. At the same time, the first parameter represents the data source name and contains information about the host and the database name. Similarly, the second and third parameters represent the username and password respectively. Likewise, the fourth parameter represents the options that are specific to a database driver. However, it is optional.

In order to create a database, we need not specify the database in DSN. After that, we can create our query. So we create a string that contains the Create Database command, Create User Command, and Grant All command. Further, we need to call the exec() method using the PDO object to run all these commands.



   $con=new PDO("mysql:host=$server", $user, $pass);
   $sql="create database ".$dbname."; create user '$new_user'@'localhost' identified by '$new_pass'; grant all on ".$dbname.".* to '$new_user'@'localhost';";
  // echo $sql;
   $con->exec($sql) or die(print_r($con->errorInfo(), true));
catch(PDOException $ex)
 die('Error Creating database: '.$ex->getMessage());


As can be seen in phpMyAdmin, the database has been created.

The Result of Creating a Database and User Using PDO in PHP
The Result of Creating a Database and User Using PDO in PHP

Checking Privileges in phpMyAdmin
Checking Privileges in phpMyAdmin

Also, note that the privileges have been assigned to the newly created user.

A New User is Created with All Privileges Using PDO
A New User is Created with All Privileges Using PDO

Further Reading

Examples of Array Functions in PHP

Basic Programs in PHP

Registration Form Using PDO in PHP

Inserting Information from Multiple CheckBox Selection in a Database Table in PHP

PHP Projects for Undergraduate Students

Architectural Constraints of REST API

REST API Concepts

Creating a Classified Ads Application in PHP