我可以在 PHP 中使用 PDO 创建数据库吗
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2583707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I create a database using PDO in PHP
提问by Xerri
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 表吗?
回答by Jingshao Chen
Yes, you can.
是的你可以。
The dsnpart, 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:
下面是一个来自 install.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());
}
?>
回答by Haim Evgi
yes , its same like run a regular query like "CREATE TABLE ..."
是的,它就像运行像“CREATE TABLE ...”这样的常规查询一样

