我可以在PHP中使用PDO创建一个数据库吗?

时间:2022-12-19 00:57:19

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

我想创建一个使用PDO与MySQL交互的类。我可以使用PDO创建一个新的MySQL表吗?

2 个解决方案

#1


91  

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 command to create database and users, etc.

dsn部分是PDO构造函数的第一个参数,它不需要有数据库名。您可以简单地使用mysql:host=localhost。然后,如果您有适当的特权,您可以使用常规SQL命令创建数据库和用户等。

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

下面是一个安装示例。php,它与root登录,创建一个数据库,一个用户,并授予用户所有的特权给新创建的数据库:

<?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());
    }
?>

#2


-1  

yes , its same like run a regular query like "CREATE TABLE ..."

是的,就像运行常规查询,比如“CREATE TABLE…”

#1


91  

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 command to create database and users, etc.

dsn部分是PDO构造函数的第一个参数,它不需要有数据库名。您可以简单地使用mysql:host=localhost。然后,如果您有适当的特权,您可以使用常规SQL命令创建数据库和用户等。

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

下面是一个安装示例。php,它与root登录,创建一个数据库,一个用户,并授予用户所有的特权给新创建的数据库:

<?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());
    }
?>

#2


-1  

yes , its same like run a regular query like "CREATE TABLE ..."

是的,就像运行常规查询,比如“CREATE TABLE…”