Can I create a database using PDO in PHP?

前端 未结 2 1261
青春惊慌失措
青春惊慌失措 2020-11-27 12:21

I want to create a class which uses PDO to interact with MySQL. Can I create a new MySQL table using PDO?

相关标签:
2条回答
  • 2020-11-27 13:13

    Yes, you can.

    The dsn part, which is the first parameter of the PDO constructor, does not have to have a database name. You can simply use mysql:host=localhost. Then, given you have the right privilege, you can use regular SQL commands to create a database and users, etc.

    Following is an example from an install.php file. It logs in with root, create a database, a user, and grant the user all privilege to the new created database:

    <?php
    
        $host = "localhost";
    
        $root = "root";
        $root_password = "rootpass";
    
        $user = 'newuser';
        $pass = 'newpass';
        $db = "newdb";
    
        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;")
            or die(print_r($dbh->errorInfo(), true));
    
        }
        catch (PDOException $e) {
            die("DB ERROR: " . $e->getMessage());
        }
    ?>
    
    0 讨论(0)
  • 2020-11-27 13:17

    Yes, it's the same, like running a regular query like "CREATE TABLE ...".

    0 讨论(0)
提交回复
热议问题