2011-06-17 72 views
0

型號PHP/MySQL錯誤

<?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> 

控制器

<?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 

數據庫只有一個入口......

這是我的錯誤..

遇到

一個PHP錯誤

嚴重性:4096

消息:類stdClass的客體不能合作nverted串

文件名:視圖/ bodyv.php

行號:5

+1

就像你看到的錯誤是在`body.php`(圖)文件不是在模型或控制器,告訴我們這個文件。ü試圖使用對象作爲字符串 – 2011-06-17 10:43:05

+0

opps ...我的壞我注意到它。 – sakthig 2011-06-17 10:46:32

回答

2

即使您正在使用的1 LIMIT運行->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

1
foreach($query as $a): 
echo $a; 
endforeach; 

該錯誤消息是不言自明。

你試圖通過數據庫查詢對象$query的成員進行迭代,並echo其成員爲字符串。至少其中之一是一個對象,從而該錯誤。

相反,遍歷通過$query與您的數據庫抽象提供相關的API函數來表示結果集。

(說完看着其他活動在這個問題上,它可能是「CI」允許使用的循環,因爲這API的一部分。查閱文檔找到迭代的正確方法。)

1

我認爲,所有你需要做的是添加:

$ A->標題或你想要的信息...