Home >Database >Mysql Tutorial >How do I create a new MySQL database and user with specific permissions using PDO in PHP?
MySQL databases hold critical data, prompting developers to create tools to manage and interact with them efficiently. One popular framework for database handling in PHP is PDO (PHP Data Objects). With PDO, you can perform a wide range of operations, including creating new databases.
Creating a Database with PDO
To create a new MySQL database using PDO, you don't need to specify the database name in the PDO connection string. Instead, use mysql:host=localhost and ensure you have the necessary privileges.
<?php $host = "localhost"; $user = "newuser"; $pass = "newpass"; $db = "newdb"; try { $dbh = new PDO("mysql:host=$host", $user, $pass); $dbh->exec("CREATE DATABASE `$db`; CREATE USER '$user'@'localhost' IDENTIFIED BY '$pass'; GRANT ALL ON `$db`.* TO '$user'@'localhost'; FLUSH PRIVILEGES;") or die(print_r($dbh->errorInfo(), true)); } catch (PDOException $e) { die("DB ERROR: " . $e->getMessage()); }
In this example, we connect with the username and password of the root user, create a new database named newdb, a user with restrictions to only access the newdb database, and grant the new user all privileges on the new database.
The above is the detailed content of How do I create a new MySQL database and user with specific permissions using PDO in PHP?. For more information, please follow other related articles on the PHP Chinese website!