PHP MySQL Create Database with PDO

 In this source code example, we will see how to create a MySQL database in PHP with PDO.

PHP MySQL Create Database with PDO

Here is a PHP script that creates a database in MySQL server:

<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
    $host= "localhost";
    $username= "root";
    $password = "";
    $db_name = "test_db";

    try{
        $conn = new PDO("mysql:host=$host;dbname=$db_name", $username, $password);
        // Set the PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        // Print host information
        echo "Connect Successfully. Host info: " . 
    $conn->getAttribute(constant("PDO::ATTR_CONNECTION_STATUS"));
    } catch(PDOException $e){
        die("ERROR: Could not connect. " . $e->getMessage());
    }

    // SQL create database query execution
    try{
        $sql = "CREATE DATABASE demo";
        $conn->exec($sql);
        echo " Database created successfully";
    } catch(PDOException $e){
        die("ERROR: Could not able to execute $sql. " . $e->getMessage());
    }
    
    // Close connection
    unset($conn);
?>
Let's understand the above PHP script.

Create an instance of the PDO class to make a connection to a MySQL database:

 $host= "localhost";
    $username= "root";
    $password = "";
    $db_name = "test_db";

    try{
        $conn = new PDO("mysql:host=$host;dbname=$db_name", $username, $password);
        // Set the PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        // Print host information
        echo "Connect Successfully. Host info: " . 
    $conn->getAttribute(constant("PDO::ATTR_CONNECTION_STATUS"));
    } catch(PDOException $e){
        die("ERROR: Could not connect. " . $e->getMessage());
    }
SQL query to create a new database:
 $sql = "CREATE DATABASE demo";
Execute SQL query:

 $conn->exec($sql);

Comments