未定义的属性:Code Igniter中的stdClass :: $ contents

时间:2014-10-29 06:36:55

标签: php html database codeigniter codeigniter-2

我正在学习,并且是关于数据库选择方法的CodeIgniter教程。其中一种方法就是这个。

这是名为data_model.php的模型文件:

<?php
    class Data_model extends CI_Model{
        function getAll(){
        $this->db->select('title','contents');
        $this->db->from('data');
        $this->db->where('id',1);           
        $q = $this->db->get();

        if ($q->num_rows() > 0){
            foreach($q->result() as $row){
                $data[] = $row;
            }
        }
        return $data;           
    }
}
?>

控制器文件名为site.php

<?php
class Site extends CI_Controller{
    function index(){
        $this->load->model('data_model');
        $data['rows'] = $this->data_model->getAll();
        $this->load->view('home',$data);        
    }   
}
?>

和查看文件名为home.php:

<html>
    <head>
        <title>
        </title>
        <meta http-equiv="Content-Type" content="text/html"; charset=UTF-8>     
    </head>
    <body>
        <div id="container">
            <p>My view has been loaded.</p>         
            <?php foreach($rows as $r) : ?>
            <h1><?php echo $r->title; ?></h1>
            <div><?php echo $r->contents; ?></div>
            <?php endforeach; ?>    
        </div>
    </body>
 </html>

当我尝试在浏览器中运行localhost / ci /时,会出现错误:

A PHP Error was encountered
Severity: Notice
Message: Undefined property: stdClass::$contents
Filename: views/home.php
Line Number: 13

好像我的$ contents变量没有值,但我很确定我的数据库有每个相应条目的内容。就像下图所示:

enter image description here

我哪里出错了?我关注的教程没有遇到错误?为什么我收到此错误?

2 个答案:

答案 0 :(得分:1)

数据库活动记录库select()方法只在第一个参数中输入可以是数组或字符串的输入查询字段,见下文

$this->db->select(array('title','contents'));
//OR
$this->db->select('title,contents');

答案 1 :(得分:0)

尝试这样会为你

<?php
    class Data_model extends CI_Model{
        function getAll(){
        $this->db->select('title,contents');
        $this->db->from('data');
        $this->db->where('id',1);           
        $q = $this->db->get();

        if ($q->num_rows() > 0){
            return $q->result(); 
        }          
    }
}
?>

并在视图文件中

<html>
    <head>
        <title>
        </title>
        <meta http-equiv="Content-Type" content="text/html"; charset=UTF-8>     
    </head>
    <body>
        <div id="container">
            <p>My view has been loaded.</p>         
            <?php foreach($rows as $r) { ?>
            <h1><?php echo $r->title; ?></h1>
            <div><?php echo $r->contents; ?></div>
            <?php } ?>    
        </div>
    </body>
 </html>