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
Mary-Kate OlsenOriginal
2024-11-09 14:54:02814browse

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);
  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);

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!

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