Home >Database >Mysql Tutorial >Can PDO Create New MySQL Databases in PHP?

Can PDO Create New MySQL Databases in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-11-10 10:34:02238browse

Can PDO Create New MySQL Databases in PHP?

Creating a MySQL Database with PDO in PHP

While PDO simplifies database interactions in PHP, one may wonder if it enables creating new database tables.

Can PDO Create New Databases?

Yes. PDO allows for database creation by specifying a DSN (Data Source Name) without a specific database name. This DSN typically includes the host and port information.

Example:

$dsn = 'mysql:host=localhost';
$pdo = new PDO($dsn, 'root', 'rootpass');

With the PDO object, you can execute SQL commands to create a database, users, and grant privileges.

Creating a Database:

To create a new database named "newdb," you can use the following SQL statement:

$pdo->exec("CREATE DATABASE `newdb`;");

Creating a User and Granting Privileges:

To create a new user named "newuser" with password "newpass" and grant all privileges on the "newdb" database, use the following SQL statement:

$pdo->exec("CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'newpass';");
$pdo->exec("GRANT ALL ON `newdb`.* TO 'newuser'@'localhost';");

Conclusion:

By using PDO in PHP, you can create new MySQL databases and manage users and privileges effectively. This functionality provides flexibility and control over database management tasks within your PHP applications.

The above is the detailed content of Can PDO Create New MySQL Databases in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn