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);
?>


Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, bool given in /www/wwwroot/studentstutorial.com/includes/get_article.php on line 13