【问题标题】:Trying to get property of non-object while trying to fetch data from database尝试从数据库中获取数据时尝试获取非对象的属性
【发布时间】:2017-08-14 06:44:34
【问题描述】:
  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;
    
    }
    }
    

在 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>';
    }
    

在 test.php 中,我试图从 users 表中获取数据,但它显示“尝试在第 12 行的 test.php 中获取非对象的属性。”

请帮忙。 谢谢。

【问题讨论】:

  • 我认为你的 database table 为空
  • 您的 DB 文件中没有构造函数,但在您的 test.php 文件中,您正在使用参数创建一个新实例。
  • 当您使用非对象变量作为对象时会出现此通知。嗯...一定是你的mysqli_fetch_array-东西。也许尝试重写那一点。
  • @WasteD 我现在能做什么?我不知道如何使用构造函数。
  • 试试这个$result = $connection-&gt;query($sql); if(!$result)[ echo $connection-&gt;error; }

标签: php json mysqli


【解决方案1】:

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

将此添加到db.php

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

像这样设置变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-26
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    • 2021-01-02
    相关资源
    最近更新 更多