PHP : MySQL Create Database
A database is a container for your tables. Before you save any data, you need a database. The MySQL command to create a new database is CREATE DATABASE. In this chapter we create the student database with PHP.
Syntax
CREATE DATABASE database_name;
-- Better: do not give an error if it already exists
CREATE DATABASE IF NOT EXISTS database_name
CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci;
The character set utf8mb4 lets you store all languages and emoji in the database. It is a good default for new databases.
Create a database using PHP
First we connect to the MySQL server (see PHP : MySQL Connect), but without choosing a database, because it does not exist yet. Then we run the query with mysqli_query().
<?php
$database_server = 'localhost';
$database_username = 'root';
$database_password = '';
// Connect to the MySQL server (no database yet)
$conn = mysqli_connect($database_server, $database_username, $database_password);
if (!$conn) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
// Create the database
$sql = "CREATE DATABASE IF NOT EXISTS student CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Output:
Tutorials Class - Output Window
Database created successfully
How the code works
- We connect to MySQL with
mysqli_connect()using only the server, username and password. - We write the SQL query in a variable, and run it with
mysqli_query(). It returns true when the query works. - If there is an error,
mysqli_error()tells the reason. - Because of
IF NOT EXISTS, running the script again does not give an error.
Note:
You can check the new database in phpMyAdmin. It appears in the list on the left side. Use DROP DATABASE student to delete a database, but be careful, it deletes all its tables and data.
Summary
CREATE DATABASEcreates a new database.- Connect without a database name when you create the database.
- Use
IF NOT EXISTSto avoid errors, andutf8mb4for full language support. - Next chapter: PHP : MySQL Create Table.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| Display MySQL data in an HTML table using mysqli_fetch_array() |