致命错误:未捕获错误:在C:\examplep\htdocs\shop\index.php中的null处调用成员



我的代码有问题,我收到了这个错误消息

致命错误:未捕获错误:在C:\xamplep\htdocs\shop\index.php:11中对null调用成员函数query((堆栈跟踪:#0{main}在C:\xamp\htdocs \shop \index.php的第11行中抛出

index.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; 
}

您忘记创建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; 
}

最新更新