我是PHP的初学者。我正在尝试从数据库中获取数据,但出现了以下错误“致命错误:对C:\xampp\htdocs\phpExamPrep\studentDB.php中非对象的成员函数查询()的调用22行”很抱歉,我必须包含所有代码,这只是为了帮助您。谢谢,我有以下课程
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()提供的参数无效”
发布于 2013-10-12 23:59:41
我想这是
if(isset(self::$db))必须在中更改
if ( ! isset(self::$db) )因为您想要设置self::$db,如果它还没有设置,并且不是相反的。
从您实际发布的代码片段来看,它看起来像这个调用
$db = database::dataConnect();返回对$db的空引用,因此不能对空引用调用query。
https://stackoverflow.com/questions/19336195
复制相似问题