Codeigniter将数据从模型传递到控制器

时间:2014-06-27 15:46:26

标签: php codeigniter

我是CodeIgniter的新手。有人请告诉我如何将模型中的$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'

                    );
        }

 }

3 个答案:

答案 0 :(得分:2)

首先 - 您的模型中不应该echo数据 - 您的视图文件中应该只有echo个数据。

数据流动的方式首先是将$id从控制器传递到cart_product_records模型中的mod_products函数。然后,模型运行查询并从数据库中获取数据。此数据由$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(如果它是对象)。

我希望有所帮助!

答案 1 :(得分:1)

您的 $ query 包含数据库结果对象。因此,您将在控制器的$ data数组中执行此操作。

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

答案 2 :(得分:1)

我没有任何意义去写

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

在你的循环中创建数组为

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

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

在控制器中,您可以访问

$query['your_id'];
相关问题