Ask Question

Menu

Need MCA Or B.tech College Project Contact Us: +91 9437911966 (Whatsapp) Students Tutorial


How to create a database in MySQL using PHP script


For create database in MySql the CREATE DATABASE statement is used.

The following example is about how to create a database in mysql without open the phpmyadmin or mysql.

Example (MySQLi Object-oriented)

<?php
$servername = "localhost";
$username = "root";
$password = "password";/* Put your password here */
/* Create connection */
$conn = new mysqli($servername, $username, $password);
/* Check connection */
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
/* Create database */
$sql = "CREATE DATABASE admin";
if ($conn->query($sql) === TRUE) {
    echo "Database admin created successfully";
}
else
{
    echo "Error creating database: " . $conn->error;
}
$conn->close();
?>

Example (MySQLi Procedural)

<?php
$servername = "localhost";
$username = "root";
$password = "password";/* Put your password here*/

/* Create connection*/
$conn = mysqli_connect($servername, $username, $password);
/* Check connection*/
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

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

mysqli_close($conn);
?>