我是 PHP 的初学者。我正在尝试从数据库中获取数据,但出现以下错误“致命错误:在第 22 行的 C:\xampp\htdocs\phpExamPrep\studentDB.php 中的非对象上调用成员函数 query() " 很抱歉,我必须包含所有代码,这只是为了帮助您帮助我。谢谢我有以下课程
class database
{
private static $dsn = 'mysql:local=localhost;dbname=test1';
private static $username ='me';
private static $password ='me';
public static $db;
private function __construct()
{
}
public static function dataConnect()
{
if(isset(self::$db))
{
try
{
self::$db = new PDO(self::$dsn, self::$username, self::$password);
}
catch(PDOException $e)
{
$error_message = $e->getMessage();
include 'database_error.php';
exit();
}
}
return self::$db;
}
}
class studentDB
{
public static function getAllRecords()
{
require 'database.php';
$query = 'select * from student';
$db = database::dataConnect();
$result = $db->query($query); //This part is giving error
$students = array();
foreach($result as $row)
{
$stud = new student($row['firstname'],$row['lastname']);
$stud->setID($row['id']);
$students[]=$stud;
}
return $students;
}
}
<?php
include 'studentDB.php';
$stx =studentDB::getAllRecords();
foreach ($stx as $r)
{
echo $r->getFirstName().' '.$r->getLastName().' '.$r->getID();
}
?>
when I changed if(isset(self::$db)) to if(!isset(self::$db)), the error becomes
“警告:在第 25 行的 C:\xampp\htdocs\phpExamPrep\studentDB.php 中为 foreach() 提供的参数无效”