我可以在 PHP 中使用 PDO 创建数据库吗? [英] Can I create a database using PDO in PHP?

查看:28
本文介绍了我可以在 PHP 中使用 PDO 创建数据库吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个使用 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 commands to create a database and users, etc.

以下是来自 install.php 文件的示例.它使用 root 登录,创建一个数据库,一个用户,并授予用户对新创建的数据库的所有权限:

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

这篇关于我可以在 PHP 中使用 PDO 创建数据库吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆