2011-02-14 145 views
0

我在codeigniter中執行以下查詢,無法弄清楚如何讓第二個查詢工作。我如何從我的第一個查詢中獲取一組值,並在第二個查詢中使用這些值?Codeigniter數據庫查詢問題

function application() 
{ 
    $user_id = $this->tank_auth->get_user_id(); 
    $this->db->select('app_id')->from('using')->where('user_id' , $user_id); 
    $query = $this->db->get(); 

    $row = $query->result_array(); 

    if ($query->num_rows() > 0) : 
    $this->db->select('app_name')->from('applications')->where('id' , $row['app_id']); 
    $body['query'] = $this->db->get(); 
    endif; 

    $this->load->view('apps_view', $body); 

如果我註釋掉第二個查詢和var_dump($row); 它給我: 陣列(2){[0] =>數組(1){[「APP_ID」] =>串(1)「2 「} [1] => array {1} {[」app_id「] => string(1)」3「}}

我決定做多個查詢而不是連接,因爲我將添加額外的列從第二個查詢中選擇。

感謝您的幫助。

+0

什麼第二個查詢的回報? – 2011-02-14 17:41:15

回答

2

您是否期待第一個查詢返回僅爲一個行?

如果是這樣,那麼你應該使用:

$query = $this->db->get(); 

$row = $query->row(); 

$app_id = $row->app_id; 
//etc 

這不是從你的問題不清楚。

如果您第一查詢返回(或可返回)多行,那麼你需要做的是:

$query = $this->db->get(); 

if ($query->num_rows() > 0) : 
    foreach($query->result_array() as $row) 
    { 
     $this->db->select('app_name') 
       ->from('applications') 
       ->where('id' , $row['app_id']); 
    } 

    $body['query'] = $this->db->get(); 
endif; 
// etc 

你很可能需要爲我不知道調整代碼你的期望的結果是。你看得到差別嗎?

如果你返回result_array你有一系列的結果(很好奇!) - 因此你的var_dump爲什麼有[0]=> array(1)等等 - 每個返回的行都有一個數組。

如果您只希望/期望從第一個查詢返回一個結果,則應該使用row來代替。

希望這是有道理的 - 應該推動正確的方向。

編輯 事實上,這可能是正確的語法:

$query = $this->db->get(); 

if ($query->num_rows() > 0) : 
    $this->db->select('app_name')->from('applications'); 
    foreach($query->result_array() as $row) 
    { 
     $this->db->where('id' , $row['app_id']); 
     // build the `where...` string with iteration/result/row 
    } 

    $body['query'] = $this->db->get(); // now we get the data. 
endif; 
// etc 
+0

看到我的編輯..我認爲這就是你在〜 – Ross 2011-02-14 17:59:49