Home > Database > Mysql Tutorial > How to Create a MySQL Database using PDO in PHP?

How to Create a MySQL Database using PDO in PHP?

Mary-Kate Olsen
Release: 2024-11-09 14:54:02
Original
817 people have browsed it

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:

  1. 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);
    Copy after login
  2. 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);
    Copy after login

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

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!

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