How to create a database in MySQL using PHP script

Create a database in MySQL (phpMyAdmin) using PHP script.


In this tutorial, you will learn how to create or make a database in mysql (phpmyadmin) using PHP Script or code. 

So, you don't to have to open your mysql application i.e phpMyAdmin, instead we will create it by code by using its host, username and password.

Let's create a file named createdb.php and run this file after pasting below code and the database name will create as blogDB.

1st Example in (MySQLi Object-oriented)
<?php

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

    /* Create DB Connection */
    $conn = new mysqli($host, $username, $password);

    /* Check DB connection */
    if ($conn->connect_error)
    {
        die("Connection failed: " . $conn->connect_error);
    }

    /* Create your database */
    $sql = "CREATE DATABASE blogDB";
    if ($conn->query($sql) === TRUE)
    {
        echo "Database created successfully";
    }
    else
    {
        echo "Error creating database: " . $conn->error;
    }
   
    $conn->close();
?>


2nd Example in (MySQLi Procedural)
<?php
    $host = "localhost";
    $username = "root";
    $password = "";

    /* Create DB Connection*/
    $conn = mysqli_connect($host, $username, $password);

    /* Check DB connection*/
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

    /* Create your database*/
    $query = "CREATE DATABASE blogDB";
    if (mysqli_query($conn, $query))
    {
        echo "Database created successfully";
    }
    else
    {
        echo "Error creating database: " . mysqli_error($conn);
    }

    mysqli_close($conn);
?>


We have successfully created the Database in php mysql.

Thanks for reading...

© Copyright - 2018 - 2022 | All rights reserved at Funda of Web IT