簡體   English   中英

選擇全部,表中的某些屬性在codeigniter中得到不同的結果

[英]select all and some attribute from a table get different result in codeigniter

我已經嘗試通過模式選擇所有屬性從codeigniter中的sql查詢中獲取結果,但是它返回PHP錯誤,但是當我在給出正確答案時指定了一些屬性,但是查詢時間太長而無法編寫時。

我嘗試過的2種模式選擇會給出不同的結果。

第一

class 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();
}

然后控制器通過

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);       
}

並在視圖“測試”中通過以下代碼對其進行響應:

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;        

它將正常工作

關於全選模式有什么解決方案嗎?

-感謝之前-

就像文檔( 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();

通過調用result()只會得到一行,因此您需要通過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。

如果您執行“ select * ....”,則只能按以下方式訪問它:$ res-> Tahun(帶大寫字母T)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM