严重性:通知消息:尝试获取非对象的属性

时间:2017-03-02 01:48:04

标签: mysql codeigniter model-view-controller codeigniter-3

我在尝试从MySQL数据库中提取多行数据并在我的网页上显示其内容时收到错误。由于我是Code Igniter的新手,我不知道如何解决这个错误:

严重性:注意 消息:尝试获取非对象的属性

以下是与错误相关的代码。

型号:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class news_model extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }

function get_news()
{
    $query = $this->db->query("SELECT * FROM news WHERE active = 1");
    if ($query->num_rows() > 0) 
    {
        foreach($query->result() AS $row) 
        {
            $array[] = get_object_vars($row);
        }
        return $array;
    }
}

}?>

控制器:

    <?php
class profile extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('url','html'));
        $this->load->library('session');
        $this->load->database();
        $this->load->model('user_model');
        $this->load->model('news_model');
    }

    function index()
    {
        $details = $this->user_model->get_user_by_id($this->session->userdata('uid'));
        $data['uname'] = $details[0]->fname . " " . $details[0]->lname;
        $data['uemail'] = $details[0]->email;
        $data['ustorenumber'] = $details[0]-> storenumber;
        $data['urank'] = $details[0]-> rank;
        $data['news'] = $this->news_model->get_news();
        $this->load->view('profile_view', $data);//Error reported on this line.
    }
}

查看:

                <?php
                foreach($news AS $row) {
                    echo '<p>' . $row->content . '</p>';//Error reported on this line
                }
            ?>

完全错误:

 A PHP Error was encountered

Severity: Notice

Message: Trying to get property of non-object

Filename: views/profile_view.php

Line Number: 82

Backtrace:

File: C:\xampp\htdocs\cig\application\views\profile_view.php
Line: 82
Function: _error_handler

File: C:\xampp\htdocs\cig\application\controllers\profile.php
Line: 22
Function: view

File: C:\xampp\htdocs\cig\index.php
Line: 315
Function: require_once

1 个答案:

答案 0 :(得分:0)

在对象格式的模型返回结果中。就像这个..

function get_news()
{
    $query = $this->db->query("SELECT * FROM news WHERE active = 1");
    if ($query->num_rows() > 0) 
    {
        return $query->result();//returns result in object format
    }
}

在视图中使用$row['content']的{​​{1}}

$row->content;插页
 <?php
            foreach($news AS $row) {
                echo '<p>' . $row['content']. '</p>';//Error reported on this line
            }
        ?>