How to create a new database with PHP & PDO

How to create a new database with PHP & PDO

Creating a new databse with PHP and PDO :

<?php

// Hosting details
$host="localhost";
$root="root";
$root_password="rootpass";

// New database user, password & database name
$user='newuser';
$pass='newpass';
$db="newdb";

// Create database connnection
try {
$dbh = new PDO("mysql:host=$host", $root, $root_password);

// Exectute
$dbh->exec("CREATE DATABASE `$db`;
CREATE USER '$user'@'localhost' IDENTIFIED BY '$pass';
GRANT ALL ON `$db`.* TO '$user'@'localhost';
FLUSH PRIVILEGES;")

// Error catching

or die(print_r($dbh->errorInfo(), true));

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

A new database with the name “newdb” will have been created. Ive got other code that takes the database name from a form and assigns it to the variable $db. If anyone needs a working example of that ill post it.

Leave a Reply

Be the First to Comment!

Notify of

wpDiscuz