我可以在PHP中使用PDO创建数据库吗 [英] Can I create a database using PDO in PHP
问题描述
我想创建一个使用PDO与MySQL交互的类.我可以使用PDO创建一个新的MySQL表吗?
I want to create a class which uses PDO to interact with MySQL. Can I create a new MySQL table using PDO?
推荐答案
是的,可以.
dsn
部分是PDO构造函数的第一个参数,不必具有数据库名称.您可以简单地使用mysql:host=localhost
.然后,如果您具有适当的特权,则可以使用常规的SQL命令来创建数据库和用户等.
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.
以下是install.php中的一个示例,它以root用户身份登录,创建一个数据库,一个用户,并向用户授予对新创建的数据库的所有特权:
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
$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());
}
?>
这篇关于我可以在PHP中使用PDO创建数据库吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!