Creating a MySQL database from PHP

MySQL databases are created with the SQL CREATE DATABASE statement. The PHP account must have the required CREATE privilege.

CREATE DATABASE

CREATE DATABASE IF NOT EXISTS newdb
CHARACTER SET utf8mb4;

Creating a database does not automatically select it for subsequent statements. Select it explicitly with USE in a SQL client or include the database name in the application's DSN/connection configuration.

PDO for a fixed database name

<?php
$pdo = new PDO(
    'mysql:host=localhost;charset=utf8mb4',
    'username',
    'password',
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
$pdo->exec(
    'CREATE DATABASE IF NOT EXISTS newdb CHARACTER SET utf8mb4'
);
?>

Dynamic database names need identifier validation

<?php
$dbName = 'training_2026';
if (!preg_match('/^[A-Za-z0-9_]+$/', $dbName)) {
    throw new InvalidArgumentException('Invalid database name');
}
$pdo->exec(
    'CREATE DATABASE IF NOT EXISTS `' . $dbName . '` CHARACTER SET utf8mb4'
);
?>

Prepared-statement placeholders represent data values, not SQL identifiers such as database or table names. Validate identifiers strictly before composing them into SQL.

Verify the database definition

SHOW CREATE DATABASE newdb;

Historical mysql_create_db()

<?php
// Historical only: mysql_connect() and mysql_create_db() were removed from PHP.
$link = mysql_connect('localhost', 'username', 'password');
mysql_create_db('new_db', $link);
?>

Database tutorial · List databases · Connect with PDO/MySQLi · SHOW TABLES · CREATE TABLE

← All PHP & MySQL topics




Subscribe to our YouTube Channel here



plus2net.com




SQL Video Tutorials










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer