MySQL Create DB

sa sahaya jerish Updated 20 Oct 2026
4 min read ·Lesson 146 of 155
In this post

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. Creatin

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 Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement 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 PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else Slicing Strings User-defined Functions Slicing Strings PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword 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 PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning 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 Debugging PHP Project: Image Upload Gallery
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.