私はPHPの初心者です。データベースからデータを取得しようとしていますが、「致命的なエラー: C:\xampp\htdocs\phpExamPrep\studentDB.php の 22 行目の非オブジェクトでメンバー関数 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() に無効な引数が指定されました」