MySQL databases are created with the SQL CREATE DATABASE statement. The PHP account must have the required CREATE privilege.
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.
<?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'
);
?>
<?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.
SHOW CREATE DATABASE newdb;
<?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
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.