尝试从数据库中获取数据时尝试获取非对象的属性

时间:2017-08-14 06:44:35

标签: php json mysqli

  1. db.php中

    <?php
    class DB{
    
    protected $db_name = '';
    protected $db_user = '';
    protected $db_pass = '';
    protected $db_host = '';
    
    public function connect() {
    
        $connect_db = new mysqli( $this->db_host, $this->db_user, $this->db_pass, $this->db_name );
    
        if ( mysqli_connect_errno() ) {
    
            printf("Connection failed: %s\n", mysqli_connect_error());
            exit();
        }
    
        return $connect_db;
    
    }
    }
    
  2. 在DB.php中尝试为数据库创建连接。

    1. test.php的

      <?php
      
      require('DB.php');
      
      $db = new DB('localhost', 'root', '', 'test');
      $connection = $db->connect();
      
      
      $sql ="SELECT * FROM users";
      $result = $connection->query($sql);
      
      if ($result->num_rows > 0) {
          while($row = mysqli_fetch_array($result)) {             
      
              array_push($responseData,
              array('uid' => $row[0],
                  'u_name' => $row[1],
                  'u_pass' => $row[2],
                  'u_fname' => $row[3],
                  'u_email' => $row[4],
                  'u_status' => $row[5],
                  'u_notes'=>$row[6]));
          }
      
              echo json_encode(array("result"=>$responseData));
          }
      
      else {
          echo '<div class="callout callout-danger">No data found...</div>';
      }
      
    2. 在test.php中,我试图从用户表中获取数据,但它说&#34;试图在第12行的test.php中获取非对象的属性。&#34;

      请帮忙。 谢谢。

1 个答案:

答案 0 :(得分:0)

您必须在constructor文件中创建db.php。否则你的变量都是空的。

将此添加到db.php

function __construct($hostname, $username, $pw, $db) {
    $this->db_host = $hostname;
    $this->db_user = $username;
    $this->db_pass = $pw;
    $this->db_name = $db;
}

像这样设置变量。