Home >Database >Mysql Tutorial >How to Create a MySQL Database using PDO in PHP?
Creating a Database with PDO in PHP
Within PHP, the PDO (PHP Data Objects) extension serves as an interface for interacting with various database systems, including MySQL. One of the tasks that PDO allows for is the creation of new database tables.
Creation of Database Using PDO
To create a new MySQL database using PDO, you can utilize the following steps:
Establish a connection to the root database: This can be achieved by setting up a PDO connection without specifying a database name in the DSN (Data Source Name):
$dbh = new PDO("mysql:host=" . $hostname, $username, $password);
Execute CREATE DATABASE and other SQL commands: Once connected, you can employ SQL commands to create a new database, user, and grant privileges to the database.
$sql = "CREATE DATABASE " . $databaseName; $dbh->exec($sql);
Example: Installation Script
Below is an example that creates a database, a user, and grants privileges using PDO:
try { $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;"); echo "Database and user created successfully."; } catch (PDOException $e) { die("DB ERROR: " . $e->getMessage()); }
The above is the detailed content of How to Create a MySQL Database using PDO in PHP?. For more information, please follow other related articles on the PHP Chinese website!