English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

MySQL Create Database

After logging into the MySQL service, we can use the create command to create a database, the syntax is as follows:

CREATE DATABASE database_name;

The following commands simply demonstrate the process of creating a database, the data name is w3codebox:

[root@host]# mysql -u root -p   
Enter password:******  # Log in and enter the terminal
mysql> create DATABASE w3codebox;

Create a database using mysqladmin

Using a regular user, you may need specific permissions to create or delete MySQL databases.

So we log in as the root user here, the root user has the highest privileges and can use the mysql mysqladmin command to create a database.

The following commands simply demonstrate the process of creating a database, the data name is w3codebox:

[root@host]# mysqladmin -u root -p create w3codebox
Enter password:******

After executing the above command successfully, the MySQL database w will be created3codebox.

Create a database using a PHP script

PHP uses the mysqli_query function to create or delete MySQL databases.

This function has two parameters, it returns TRUE on success, otherwise it returns FALSE.

Syntax

mysqli_query(connection, query, resultmode);
ParametersDescription
connectionRequired. Specifies the MySQL connection to use.
queryRequired, specifies the query string.
resultmode

Optional. A constant. It can be any of the following values:

  • MYSQLI_USE_RESULT(use this if you need to retrieve a large amount of data)

  • MYSQLI_STORE_RESULT(default)

Online Example

The following examples demonstrate how to create a database using PHP:

<?php
$dbhost = 'localhost';  // MySQL Server Host Address
$dbuser = 'root';            // MySQL Username
$dbpass = '123456';          // MySQL Username Password
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Connection error: ' . mysqli_error($conn));
}
echo 'Connection successful<br /';
$sql = 'CREATE DATABASE w3codebox';
$retval = mysqli_query($conn,$sql );
if(! $retval )
{
    die('Database creation failed: ' . mysqli_error($conn));
}
echo "Database w3codebox created successfully\n";
mysqli_close($conn);
?>

The following result will be returned after a successful execution:


If the database already exists, the following result will be returned after execution: