MySQL Create Database
After logging into the MySQL service, we can use the create
command to create a database with the following syntax:
CREATE DATABASE database_name;
The following command demonstrates the process of creating a database named tutorialpro:
[root@host]# mysql -u root -p
Enter password:****** # After logging in, enter the terminal
mysql> create DATABASE tutorialpro;
Create Database Using mysqladmin
As a regular user, you may need specific privileges to create or delete a MySQL database.
Here, we log in as the root user, who has the highest privileges and can use the mysqladmin
command to create a database.
The following command demonstrates the process of creating a database named tutorialpro:
[root@host]# mysqladmin -u root -p create tutorialpro
Enter password:******
After successful execution of the above command, the MySQL database tutorialpro will be created.
Create Database Using PHP Script
PHP uses the mysqli_query function to create or delete a MySQL database.
This function takes two parameters and returns TRUE on success, otherwise FALSE.
Syntax
mysqli_query(connection, query, resultmode);
Parameter | Description |
---|---|
connection | Required. Specifies the MySQL connection to use. |
query | Required. Specifies the query string. |
resultmode | Optional. A constant. Can be one of the following values: MYSQLI_USE_RESULT (use this if you need to retrieve large amounts of data)<br> MYSQLI_STORE_RESULT (default) |
Example
The following example demonstrates creating a database using PHP:
Create Database
<?php
$dbhost = 'localhost'; // MySQL server host address
$dbuser = 'root'; // MySQL username
$dbpass = '123456'; // MySQL user password
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Connection error: ' . mysqli_error($conn));
}
echo 'Connection successful<br />';
$sql = 'CREATE DATABASE tutorialpro';
$retval = mysqli_query($conn, $sql);
if(! $retval )
{
die('Failed to create database: ' . mysqli_error($conn));
}
echo "Database tutorialpro created successfully\n";
mysqli_close($conn);
?>
After successful execution, the following result is returned:
If the database already exists, the following result is returned: