MySQL Create DB

Ma Mahalakshmi V Updated 14 Nov 2026
4 min read ·Lesson 193 of 255

Creating a Database

In simple terms: A MySQL server can hold many databases — one for your shop, one for your blog, one for testing. Before creating tables, you need a database to put them in. Creating it is a one-time setup step, usually done with a single SQL statement.

Technically: CREATE DATABASE creates a new, empty database (in MySQL, the terms "database" and "schema" are synonyms). Its character set and collation become the defaults for all tables created inside it. From PHP, the statement is sent with mysqli::query(), which returns true on success for statements that do not produce result rows.


The SQL Statement

CREATE DATABASE IF NOT EXISTS gocourse_shop
    CHARACTER SET utf8mb4
    COLLATE utf8mb4_0900_ai_ci;
PartMeaning
CREATE DATABASE gocourse_shopCreate a database with this name
IF NOT EXISTSDo nothing (instead of failing) if it already exists
CHARACTER SET utf8mb4Store text as full UTF-8, supporting every language and emoji
COLLATE utf8mb4_0900_ai_ciRules for comparing and sorting text (MySQL 8's default for utf8mb4)

Collations in Practice

A collation decides whether 'Chennai' = 'chennai' is true and how names are sorted:

CollationComparisonNotes
utf8mb4_0900_ai_ciAccent-insensitive, case-insensitiveDefault in MySQL 8; modern Unicode rules
utf8mb4_unicode_ciCase-insensitiveWidely supported, also on MariaDB
utf8mb4_binExact byte comparisonCase-sensitive; useful for tokens and codes

With a case-insensitive collation, searching for asha@example.com finds Asha@Example.com, and a UNIQUE index treats them as duplicates — usually what you want for emails and usernames.


Creating a Database From PHP

Creating databases requires the CREATE privilege, which the normal application user should not have (see MySQL Database). A setup script therefore connects with an administrative account, typically from the command line during installation or deployment:

<?php
// bin/create-database.php — run with: php bin/create-database.php
$name = 'gocourse_shop';

if (!preg_match('/^[a-zA-Z0-9_]{1,64}$/', $name)) {
    exit("Invalid database name.\n");
}

try {
    $admin = new mysqli(
        getenv('DB_HOST') ?: '127.0.0.1',
        getenv('DB_ADMIN_USER') ?: 'root',
        getenv('DB_ADMIN_PASSWORD') ?: '',
    );
    $admin->set_charset('utf8mb4');

    $admin->query("CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci");

    $status = $admin->warning_count === 0 ? 'created' : 'already existed';
    echo "Database $name is ready ($status).\n";
} catch (mysqli_sql_exception $e) {
    fwrite(STDERR, "Could not create the database: " . $e->getMessage() . "\n");
    exit(1);
}

Output (first run)

Database gocourse_shop is ready (created).

Output (second run)

Database gocourse_shop is ready (already existed).

How It Works

  1. The connection is opened without a database name, because the database does not exist yet.
  2. query() sends the SQL; on failure, it throws a mysqli_sql_exception (PHP 8.1+ default).
  3. With IF NOT EXISTS, an existing database does not cause an error; MySQL issues a warning instead (code 1007, "database exists"), which warning_count reveals. This makes the script safe to run repeatedly — it is idempotent.
  4. Errors go to STDERR, and exit(1) signals failure to deployment tools and shell scripts.

Why the Name Is Validated

Database, table, and column names (identifiers) cannot be passed as prepared-statement parameters — placeholders only work for values. If a name ever comes from configuration or input, validate it against a strict pattern and wrap it in backticks, as shown. MySQL identifiers are limited to 64 characters.


Checking and Selecting Databases

<?php
$admin = new mysqli('127.0.0.1', getenv('DB_ADMIN_USER') ?: 'root', getenv('DB_ADMIN_PASSWORD') ?: '');

$result = $admin->query("SHOW DATABASES LIKE 'gocourse%'");

while ($row = $result->fetch_row()) {
    echo $row[0] . "\n";
}

$admin->select_db('gocourse_shop');
echo "Current database: " . $admin->query('SELECT DATABASE()')->fetch_row()[0] . "\n";

Output (example)

gocourse_shop
gocourse_shop_test
Current database: gocourse_shop
  • SHOW DATABASES LIKE '...' lists databases matching a pattern (only those the user may access).
  • select_db() switches the default database for subsequent queries, equivalent to the SQL statement USE gocourse_shop.

A separate database for automated tests (gocourse_shop_test) is a common practice, so tests never touch development or production data.


Deleting a Database

DROP DATABASE IF EXISTS gocourse_shop_test;

Warning: DROP DATABASE permanently deletes the database and all its tables and data. There is no undo. Never let a web application user hold the DROP privilege, and double-check the database name in scripts — especially in production. Take a backup (for example, with mysqldump) before any destructive operation.


Where Databases Are Usually Created

EnvironmentTypical Method
Local developmentDocker environment variables (MYSQL_DATABASE), XAMPP's phpMyAdmin, or a setup script
Shared hostingThe hosting control panel (cPanel, Plesk), which also creates the user
Cloud / managed databasesThe provider's console or infrastructure-as-code tools
Automated testsTest setup scripts that create and drop a dedicated test database

Tables inside the database are then created and changed through migrations — versioned scripts kept in the project (see MySQL Create Table).


Common Mistakes

Using the Application User to Create Databases

Effect: The application account needs dangerous privileges.

Fix: Use a separate administrative account for setup.

Forgetting the Character Set

Effect: An older server default (such as latin1) can break non-English text.

Fix: Always specify CHARACTER SET utf8mb4.

Inserting Names From Input Into SQL

Effect: SQL injection through identifiers.

Fix: Validate names strictly and quote them with backticks.

Running Setup Scripts Without IF NOT EXISTS

Effect: The second run fails with "database exists".

Fix: Make setup scripts idempotent.


Best Practices

  • Create databases with utf8mb4 and an explicit collation.
  • Perform database creation with an administrative account, not the application user.
  • Make setup scripts idempotent with IF NOT EXISTS.
  • Validate and backtick-quote identifiers that come from configuration.
  • Keep separate databases for development, testing, and production.

Official reference: https://www.php.net/manual/en/mysqli.query.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
Ask about this post
AI Ask about this post

Ask questions about MySQL Create DB and get answers drawn from it.

Signed-in readers only.