MySQL Create Database
Creating a database is usually a one-off step run by an admin — not your app at runtime. Still worth knowing the syntax.
Via PHP
PHP
$pdo = new PDO('mysql:host=localhost', 'root', '');
try {
$pdo->exec('CREATE DATABASE shop CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci');
echo 'created';
} catch (PDOException $e) {
echo $e->getMessage();
}
Connect without the dbname parameter — you don't have one yet.
Idempotent — won't error if it exists
SQL
CREATE DATABASE IF NOT EXISTS shop
CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci;
The mysql CLI is the more common path
SHELL
mysql -u root -p mysql> CREATE DATABASE shop CHARACTER SET utf8mb4; mysql> GRANT ALL PRIVILEGES ON shop.* TO 'shop_app'@'localhost' IDENTIFIED BY '...'; mysql> FLUSH PRIVILEGES;
For real apps — use migrations
Don't ship "create DB" code in your app. Use a migration tool that tracks schema changes:
| Tool | Where it lives |
|---|---|
| Laravel migrations | artisan migrate |
| Doctrine Migrations | Symfony + Doctrine apps |
| Phinx | Standalone, framework-agnostic |
| Flyway | Java-based but works for any DB |
Charset, collation, and you
- utf8mb4 is the only character set worth picking — handles every Unicode codepoint including emoji.
- utf8mb4_unicode_ci sorts by Unicode rules; utf8mb4_0900_ai_ci (MySQL 8) is even better.
Tip: Production app users should NOT have
CREATE DATABASE privileges. Run schema operations as a separate, restricted DBA account.Example
Example
<?php
$pdo = new PDO('mysql:host=localhost', 'root', '');
$pdo->exec('CREATE DATABASE shop CHARACTER SET utf8mb4');
Try it Yourself »
Exercise
Make the CREATE DATABASE re-runnable.
CREATE DATABASE
shop;
Three words.
Discussion
Loading…