1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php
define('DB_HOST', '127.0.0.1'); // use ip address instead of `localhost`
// existing user that has permission to create database and grant access
define('DB_ROOT_USER', 'root');
define('DB_ROOT_PASS', 'rootpass');

// the database you want to create
$dbname = 'my_new_db';
// specific user for this particular database
$dbuser = 'my_new_db_user';
$dbpass = 'new_dbpassword';

try {
// login with root user
$dbh = new PDO('mysql:host='.DB_HOST, DB_ROOT_USER, DB_ROOT_PASS);

// create database
$dbh->exec(
"CREATE DATABASE `$dbname`;
CREATE USER '$dbuser'@'localhost' IDENTIFIED BY '$dbpass';
GRANT ALL ON `$dbname`.* TO '$dbuser'@'localhost';
FLUSH PRIVILEGES;"
)
or die(print_r($dbh->errorInfo(), true));

// use database
$dbh = new PDO('mysql:host='.DB_HOST.';dbname='.$dbname, DB_ROOT_USER, DB_ROOT_PASS);

// optional: import existing sql file if you have
$imported = $dbh->exec(file_get_contents('existingdata.sql'));
if ($imported === false) { // even if success, it may also return some code
die(print_r($dbh->errorInfo(), true));
}

} catch (PDOException $e) {
die("DB ERROR: ". $e->getMessage());
}

References: