型号:
<?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();
}
}
?>
查看:
<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');
}
}
?>
数据库:
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
数据库只有一个条目...
这是我的错误..
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
最佳答案
即使您以 LIMIT 为 1 运行 ->get()
,它仍会返回结果集。
您实际上在做的是循环遍历您的集合并打印单个对象,除非它具有 toString()
方法,否则无法完成。这就是 CI 提示 Object of class stdClass could not be converted to string
的原因。
将您的代码更改为
foreach($query as $obj):
echo $obj->property; //where property is a column
endforeach;
http://codeigniter.com/user_guide/database/active_record.html
关于PHP/MySQL 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6384546/