2013-07-09 46 views
0

得到不同的結果,我試圖讓從笨與模式SQL查詢結果選擇所有屬性,但它返回一個PHP錯誤,但是當我指定給正確答案的一些屬性但查詢太​​長而無法寫入。選擇所有,並從表中的一些屬性,笨

這2模式選擇,我已經嘗試給不同的結果。

首先

類model_kemiskinan擴展CI_Model {

..... //這裏

function get_kemiskinan_provinsi(){ 
    $this->tahun = "2011"; 
    $this->kodeProv = "31";   
    $this->query = "select * from kemiskinan where id_provinsi = ".$this->kodeProv." and tahun = ".$this->tahun;   
    $this->result = $this->db->query($this->query);     
    return $this->result->result(); 
} 

然後構造的controlller傳遞

public function testquery(){   
    $this->load->model('model_kemiskinan');     
    $data['hasil'] = $this->model_kemiskinan->get_kemiskinan_provinsi();   
    $data['main_content'] = 'test';   
    $this->load->view('template', $data);  
} 

和查看'測試'用這些c迴應它頌:

if(is_array($hasil)){   
    foreach ($hasil as $baris) {    
     echo $baris->tahun; 
     echo $baris->id_provinsi;    
     echo "<br/>"; 
    } 

,結果是這個

A PHP Error was encountered 
Severity: Notice 
Message: Undefined property: stdClass::$tahun 

但是,如果我改變看起來像這樣的選擇模式:

$this->query = "select tahun, id_provinsi from kemiskinan where id_provinsi = ".$this->kodeProv." and tahun = ".$this->tahun;   

它將工作正確

有沒有關於選擇所有模式的解決方案?

-Thanks在─

回答

1

像文檔(http://ellislab.com/codeigniter/user-guide/database/examples.html)說:

$query = $this->db->query('SELECT name, title, email FROM my_table'); 

foreach ($query->result() as $row) 
{ 
    echo $row->title; 
    echo $row->name; 
    echo $row->email; 
} 

echo 'Total Results: ' . $query->num_rows(); 

您可以通過調用結果()只得到一個行,所以你需要通過的foreach調用它:

function get_kemiskinan_provinsi(){ 
    $this->tahun = "2011"; 
    $this->kodeProv = "31";   
    $this->query = "select * from kemiskinan where id_provinsi = ".$this->kodeProv." and tahun = ".$this->tahun;   
    $this->result = $this->db->query($this->query); 

    $res = array();    
    foreach ($this->result->result() as $row) 
    { 
     $res[] = $row; 
    } 
    return $res; 
} 

請認識到,在結果對象的字段是區分大小寫的!如果你的數據庫中有一個名爲「Tahun」的字段,那麼「select tahun ...」將在mysql中起作用,並且會爲你提供一個可以訪問$ res-> tahun的對象。

如果「選擇* ... ...」,那麼你只能訪問它像這樣:$水庫> Tahun(與首都圈T)

+0

後,我試圖修改的部分,同樣的錯誤仍然會出現。 我的控制器和視圖怎麼樣? - 感謝之前 - –

+0

你可以做一個print_r($ hasil);在視圖請 – steven

+0

陣列([0] => stdClass的對象([否] => 55 [Id_provinsi] => 31 [Tahun] => 2011 [Jmlh_Pend_miskin1] => 363.42 [Jmlh_Pend_miskin2] => 0.00 [Jmlh_Pend_miskin3] => 363.42 [persentase_Pend_miskin1] => 3.75 [persentase_Pend_miskin2] => 0.00 [persentase_Pend_miskin3] => 3.75 [Garis_kemiskinan1] => 355480.00 [Garis_kemiskinan2] => 0.00 [Garis_kemiskinan3] => 355480.00 [IKP1_1] => 0.60 [IKP1_2] IKP1_3] => 0.60 IKP2_1] => 0.15 IKP2_2] => 0.00 [IKP2_3] => 0.15)) –

相關問題