PHP MySQL: Create Database

This entry is part 4 of 17 in the series PHP & MySQL

If allartist database is not created yet, we can create it using PHP.

<?php

$mysqli = new mysqli("127.0.0.1", "root", "");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL";
}

$sql = "create database allartist";
if (mysqli_query($mysqli, $sql)) {
    echo "Database allartist created successfully";
} else {
    echo "Error creating database";
}

?>

Notice how we execute the script below by passing it into mysqli_query().

create database allartist

The database connection $mysqli also needs to be passed into mysqli_query().

Its format is:

mixed mysqli_query (db_connection , query string, [int $resultmode])

If the database allartist is not available, we should get a created successfully message.  If we run the code below to create the same database, we should get an error 1007 since the DB allartist has already been created.

<?php

$mysqli = new mysqli("127.0.0.1", "root", "");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL";
}

$sql = "create database allartist";
if (mysqli_query($mysqli, $sql)) {
    echo "Database allartist created successfully";
} else {
    echo "Error creating database with error no: " . $mysqli->errno;
}

?>
Series Navigation<< PHP MySQL: Making connection to DB non OOP procecural style
PHP MySQL: Create Table >>