Alex Rivera | Logout

Can I create a database using PDO in PHP?

Asked 2010-04-06T09:11:30.747
54

I want to create a class which uses PDO to interact with MySQL. Can I create a new MySQL table using PDO?

Edit
Report

1 Answer

119

Yes, you can.

The dsn part, which is the first parameter of the PDO constructor, does not have to have a database name. You can simply use mysql:host=localhost. Then, given you have the right privilege, you can use regular SQL commands to create a database and users, etc.

Following is an example from an install.php file. It logs in with root, create a database, a user, and grant the user all privilege to the new created database:

<?php

$host = "localhost";

$root = "root";
$root_password = "rootpass";

$user = 'newuser';
$pass = 'newpass';
$db = "newdb";

$dbh = new PDO("mysql:host=$host", $root, $root_password);

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

if you need to execute other queries using this new database, you can run a USE query and so this newly created database will be selected:

$dbh->query("USE`$db`");
$dbh->query(/* any other query against the new database /*);
answered 2011-07-01T14:41:16.750

Your Answer