[英]Fatal error: Uncaught Error: Call to a member function query() on null in C:\xampp\htdocs\shop\index.php
I have a problem with my code I'm getting this error message我的代码有问题 我收到此错误消息
Fatal error: Uncaught Error: Call to a member function query() on null in C:\xampp\htdocs\shop\index.php:11 Stack trace: #0 {main} thrown in C:\xampp\htdocs\shop\index.php on line 11 Fatal error: Uncaught Error: Call to a member function query() on null in C:\xampp\htdocs\shop\index.php:11 Stack trace: #0 {main} thrown in C:\xampp\htdocs\shop\ index.php 在第 11 行
<?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
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;
}
You forgot to create PDO
connection:您忘记创建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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.