Reputation:
I was studying and was a following a CodeIgniter Tutorial about database selecting methods. One of it's method was this one.
It was it's Model file called 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;
}
}
?>
Controller File called 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);
}
}
?>
and View file called 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>
When I try to run localhost/ci/ in my browser, an error occurs saying:
A PHP Error was encountered
Severity: Notice
Message: Undefined property: stdClass::$contents
Filename: views/home.php
Line Number: 13
It seems like my $contents variable has no value, but I am pretty sure that my database has contents for each corresponding entry. Just like what the image below shows:
Where did I go wrong? The tutorial I was following didn't experience error? Why I am getting this error?
Upvotes: 1
Views: 2307
Reputation: 1796
try like this will for for you
<?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();
}
}
}
?>
and in view file
<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>
Upvotes: 0
Reputation: 12117
DB active record library select()
method takes input query fields in first param only that can array or string, see below
$this->db->select(array('title','contents'));
//OR
$this->db->select('title,contents');
Upvotes: 1