致命错误:未捕获的错误:在C:\xampp\htdocs\shop\index.php中对空值调用成员函数query()

velaa5lx  于 2022-11-21  发布在  PHP
关注(0)|答案(1)|浏览(72)

我的代码有问题我收到此错误消息
致命错误:未捕获的错误:在C:\xampp\htdocs\shop\index.php中对空值调用成员函数query():11堆栈跟踪:在第11行的C:\xampp\htdocs\shop\index.php中抛出了#0 {main}
索引. php

<?php

require_once __DIR__.'/function/database.php';

$sql = 'SELECT id, title, description, price FROM products';

$result = getDB()->query($sql);
require __DIR__.'/templates/main.php';

./函数/数据库. php

<?php 
function getDB() { 
    static $db;

    if ($db instanceof PDO){ 
        return $db; 
    }

    require_once CONFIG_DIR.'/database.php'; 

    $dsn = sprintf("myqsl:host=%s;dbname=%s;charset=%s",DB_HOST,DB_DATABASE,DB_CHARSET); 

    return $db; 
}
tyky79it

tyky79it1#

您忘记创建PDO连接:

<?php 
function getDB(){ 
    static $db; 
    if($db instanceof PDO){ 
        return $db; 
    } 
    require_once CONFIG_DIR.'/database.php'; 
    $dsn = sprintf("myqsl:host=%s;dbname=%s;charset=%s",DB_HOST,DB_DATABASE,DB_CHARSET); 
    $db = new PDO($dsn); // ← HERE
    return $db; 
}

相关问题