如何使用PDO从mysql创建数据库和表?

问题描述 投票:0回答:2

我对这段代码很困惑。由于我是 PDO 新手,我需要一些帮助才能完全理解下面的这个东西。它在 MySQL 中成功创建数据库,但没有创建表。我不知道这段代码有什么问题。请有人帮忙。

错误内容为:

数据库创建成功

创建数据库产品

SQLSTATE[3D000]:无效的目录名称:1046 未选择数据库

$host    = "localhost";
$user    = "root";
$pass    = "";

try{
    $sql     =  "CREATE DATABASE products";

    $pdo     = new PDO('mysql:host=$host', $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->exec($sql);
    echo "Database created successfully";


    $create_products = "CREATE TABLE  products (
            id INT(6) AUTO_INCREMENT NOT NULL,
            type VARCHAR(10) NOT NULL,
            firstname VARCHAR(40) NOT NULL,
            mainname VARCHAR(40) NOT NULL,
            title VARCHAR(50) NOT NULL,
            price INT (10) NOT NULL,
            numpages int(5) NOT NULL,
            playlength int(10) NOT NULL,
            discount int(10) NOT NULL,
            PRIMARY KEY (`id`))";
    $pdo->query($create_products);

    $pdo->query("INSERT INTO products 
                            (type, firstname, mainname, title, price, numpages, playlength, discount) 
                    values ('book', 'willa', 'cather', 'my antonia', 4.22, 200, NULL, 0 )");

    $pdo->query( "INSERT INTO products 
                            ( type, firstname, mainname, title, price, numpages, playlength, discount) 
                    values ('cd', 'the', 'clash', 'london calling', 4.22, 200, 60, 0 )");

    $pdo->query( "INSERT INTO products 
                            (type, firstname, mainname, title, price, numpages, playlength, discount) 
                    values ('shop', NULL, 'pears', 'soap', 4.22, NULL, NULL, 0 )");

    $pdo->query( "INSERT INTO products 
                            (type, firstname, mainname, title, price, numpages, playlength, discount) 
                    values ('book', NULL, 'johnson', 'shampoo', 4.22, 200, NULL, 0 )");

}
catch (PDOException $e) {
    echo $sql . "<br>" . $e->getMessage();
}
php mysqli pdo
2个回答
2
投票

创建数据库后使用它,以便 PDO 知道它正在使用哪个数据库。

$pdo     = new PDO('mysql:host=$host', $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec($sql);
echo "Database created successfully";
$pdo->exec('USE products');  // <<---- add this to your code

1
投票

通常,当您打开 PDO 连接时,您会指定要连接的数据库。当您创建数据库时,您当然不能这样做。

因此,请关闭连接,然后使用指定的新数据库重新打开它

$host    = "localhost";
$user    = "root";
$pass    = "";
    
try{
    $pdo = new PDO("mysql:host=$host", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = "CREATE DATABASE products;";
    $pdo->exec($sql);
    echo "Database created successfully";

    $pdo->close();

    $pdo = new PDO("mysql:host=$host;dbname=products", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // your create table code here
    . . .
© www.soinside.com 2019 - 2024. All rights reserved.