0

我只想支持我的类属性,以便我可以使用它们。在我的项目中,我想获取 mysql 表数据的所有结果并返回它。好吧,它运作良好,但更改返回数据时出现错误消息,如下所示:

   Trying to get property of non-object in E:\xampp\htdocs\myProject\new_27_03\login_con.php on line 26

我的代码::

非类.php

 <?php
      $doc = new Dortor();  // object  

      $doc->result("SELECT * FROM doctor");   // function call

      foreach( $doc as $doctor ) {
         echo $doctor->doc_name;     // error msg: Trying to get property of non-object in
                                   //E:\xampp\htdocs\myProject\new_27_03\login_con.php on line 26
      }
  ?>

dortor.php

  <?php
     class Dortor extends DatabaseObject {
       public $table_name = "doctor";
       public $id;
       public $doc_name;
       public $doc_pass;
       public $doc_img;     // image directory

       public function result($sql="") { 
         $result = $database->query($sql);  // run query from mysql database

         $result_array = array();   
         while( $row = $database->fetch_array($result)  ) {  // this while loop return actual result
             $result_array[] = $this->get_table_value($row);
         }
         return $result_array;
        }
     }
  ?>

数据库对象.php

  <?php
       class DatabaseObject {
           public function get_table_value($record) {
              $className = get_called_class();  // get the class name
              $object = new $className;       // object call

              $arrayValue = array();  
              $i=0;   // inital array position
              foreach( $object as $key => $value )  {
                  $arrayValue[$i] = $key;  // get the class's object attributes
                  $i++;
              } 

              $i = 1;
             foreach ($record as $key => $value) {   // fetch the database result
                 if(array_key_exists($key, $arrayValue) ) {  // check if database's column name is exist on 'arrayValue' array,
                    $object->$arrayValue[$i] = $value;  //  if exist then, store value in 'Doctor' class's object attributes
                    $i++;
                 }
              } 
             return $object;
          }
       }
  ?>
4

2 回答 2

0

您的错误可能在这里:

$doc = new Dortor();  // object  
$docs = $doc->result("SELECT * FROM doctor");   // you forgot to assign the result
foreach ($docs as $doctor) { // was looping over $doc here, instead of the result
   echo $doctor->doc_name;
}
于 2013-03-29T23:53:59.447 回答
0

It would also make sense to check the correct variable type before the foreach loop starts:

if ( is_array( $doc)  )
{
 foreach( $doc as $doctor ) 
  {
    // foreach code
  }
}
else
{
  echo '$doc is no valid object';
  var_dump($doc);
}

So you can find out, that's the problem.

于 2013-03-29T23:57:57.163 回答