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

Can PDO Create New MySQL Databases in PHP?

Linda Hamilton
Release: 2024-11-10 10:34:02
Original
214 people have browsed it

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');
Copy after login

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`;");
Copy after login

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';");
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template