Reputation: 2247
Model:
<?php
class Blogm extends CI_Model{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function get()
{
$query = $this->db->get('post', 1);
return $query->result();
}
}
?>
View:
<h2>
<?php
foreach($query as $a):
echo $a;
endforeach;
?>
</h2>
</body>
</html>
Controller:
<?php
class Blog extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->model('Blogm','',TRUE);
}
public function index(){
$data['title'] = 'Sblog';
$data['message'] = 'My Sblog';
$data['menu_item'] = array('home','contact');
$this->load->view('headerv.php', $data);
$data['query'] = $this->Blogm->get();
$this->load->view('bodyv.php', $data);
//$this->load->view('sidebarv.php');
//$this->load->view('footerv.php');
}
}
?>
Database:
id int(11) No None auto_increment
title text
MIME: text/plain latin1_swedish_ci No None
content text
MIME: text/plain latin1_swedish_ci No None
time timestamp on update CURRENT_TIMESTAMP No CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP
posted int(1) No 0
Database has only one entry…
This is my error..
A PHP Error was encountered
Severity: 4096
Message: Object of class stdClass could not be converted to string
Filename: views/bodyv.php
Line Number: 5
Upvotes: 0
Views: 265
Reputation: 3798
i think all what you need to do is add :
$a->title or the info you want ...
Upvotes: 1
Reputation: 50029
Even though you are running ->get()
with a LIMIT of 1, it still returns a result set.
What you are actually doing is, looping through your set and printing the single object, which can't be done unless it has a toString()
method. This is why CI is complaining Object of class stdClass could not be converted to string
.
Change your code to
foreach($query as $obj):
echo $obj->property; //where property is a column
endforeach;
http://codeigniter.com/user_guide/database/active_record.html
Upvotes: 2
Reputation: 385405
foreach($query as $a):
echo $a;
endforeach;
The error message is pretty self-explanatory.
You're trying to iterate through the members of the database query object $query
, and to echo
its members as strings. At least one of these is an object and thus the error.
Instead, iterate through the resultset represented by $query
with the relevant API functions provided by your database abstraction.
(Having looked at other activity on this question, it may be that "CI" allows the use of loops as part of this API. Consult the documentation to find the proper way to iterate.)
Upvotes: 1