2014-06-27 199 views
1

我是新來的笨。可有人請告訴如何在模型控制器通過$row['main_products_cat_id'];'id'=> 'my id here',幫助我。我嘗試了很多方法,但是失敗了。笨將數據傳遞給控制器​​

謝謝!

這是我的模型

function cart_product_records($id){ 

     $this->db->from('tbl_sub_products'); 
     $this->db->where('tbl_sub_products.sub_product_id', $id); 
     $query = $this->db->get(); 

     foreach ($query->result_array() as $row){ 

      echo $row['main_products_cat_id']; 
      echo $row['sub_product_id']; 
      echo $row['sub_product_name']; 
      echo $row['sub_product_description']; 
      echo $row['sub_product_image']; 
      echo $row['sub_product_price'];  
     } 
     return $query->result();  
} 

這是我的控制器

function shopping_cart(){ 

     $id = $this->input->get('id');  
     if($query = $this->mod_products->cart_product_records($id)){ 

      $data['result'] = array(

         'id'  => 'my id here', 
         'qty'  => my qty here, 
         'price' => my price here, 
         'name' => 'my product name here' 

        ); 
     } 

} 

回答

1

首先 - 你應該在你的模型不echo數據 - 你真的應該只echo在視圖中的文件數據。

數據流動的方式首先是將$id從控制器傳遞到mod_products模型中的cart_product_records函數。模型然後運行查詢並從數據庫獲取數據。此數據由$query->result_array()$query->result()代表(你用這兩種,但你應該只使用一個,一次)。

所以你就必須return $query->result()它發送您的數據備份到您的控制器。數據將存儲在$query變量中,因爲您有$query = $this->mod_products->cart_product_records($id)

如果我是你,我會if語句添加!empty()檢查的,所以它看起來像這樣:

if(!empty($query = $this->mod_products->cart_product_records($id))){ 

然後,根據你想從$query得到什麼數據,你要麼會想建立一個循環(這將使您解壓多個ID,價格等),或者你可以從$query檢索特定的值,比如$query[0][main_products_cat_id](假設$query是一個數組)或$query[0]->main_products_cat_id(如果它是一個對象)。

我希望有幫助!

0

$查詢保存數據庫結果的對象。所以,你會在你的控制器的$ data數組中執行此操作。

$data['result'] = array(
    'id' => $query->main_products_cat_id, 
    // carry on... 
); 
+0

訪問我認爲這會是'$ query [0] - > main_products_cat_id' – Dan

+0

你是對的。我會從模型中返回$ query [0]。 – Craig

0

我這麼想的任何意義,寫

echo $row['main_products_cat_id']; 
.... 

在循環創建數組作爲

foreach ($query->result_array() as $row){ 

      $return_array[] = $row; 
     } 
     return $return_array 

和控制器,你可以

$query['your_id']; 
+0

謝謝:D:D – user3766509