0

私は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() に無効な引数が指定されました」

4

1 に答える 1

1

こう思う

if(isset(self::$db))

で変更する必要があります

if ( ! isset(self::$db) )

self::$dbまだ設定されておらず、その逆でない場合は、設定したいとおりです。

実際に投稿したコードフラグメントから、この呼び出しのように見えます

$db = database::dataConnect();

は null 参照を返すため、null 参照を$db呼び出すことはできませんquery

于 2013-10-12T15:59:40.830 に答える