【问题标题】:Severity: Notice Message: Trying to get property of non-object严重性:通知消息:试图获取非对象的属性
【发布时间】:2017-07-21 14:07:04
【问题描述】:

我在尝试从我的 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

【问题讨论】:

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


    【解决方案1】:

    在模型中以对象格式返回结果。像这样..

    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'] insetad of $row-&gt;content;

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多