开发者

Loading data in CodeIgniter

I am getting only one featured item with this code in CodeIgniter. I want to get 5 different featured items.

My model:

    // GET THE FEATURED PRODUCTS
    function getMainFeature(){
        $data = array();
        $this->db->select("id, a_title, a_description, a_image");
        $this->db->where('a_featured', true);
        $this->db->where('a_status', 'active');
        $this->db->order_by("rand()");
        $this->db->limit(5);

        $Q = $this->db->get('articles');

        if($Q->num_rows() >0){
            foreach($Q->result_array() as $row){
                $data = array(
                    "id" => $row['id'],
                    "a_name" => $row['a_title'],
                    "a_des开发者_如何学JAVAcription" => $row['a_description'],
                    "a_image" => $row['a_image']
                );
            }
        }
        $Q->free_result();
        return $data;
    }

My controller:

function index(){


    //get featured
    $data['mainfeature'] = $this->MArticles->getMainFeature();
    $data['main'] = 'template/main/home';
    //load data and template
    $this->load->vars($data);
    $this->load->view('template/main/main_template');
}

My views:

<li>
<?php 
foreach($mainfeature as $feat){

echo "<img src='".$mainfeature['a_image']."' border='0' align='left' width='320' height='320'/> \n";

}
?>
</li>


The reason is this...

    if($Q->num_rows() >0){
        foreach($Q->result_array() as $row){
            $data = array(         //<-----------HERE
                "id" => $row['id'],
                "a_name" => $row['a_title'],
                "a_description" => $row['a_description'],
                "a_image" => $row['a_image']
            );
        }
    }

You are overwriting (re-assigning) your $data variable every time you iterate the loop.

Instead of the above, try this...

    $data = array();        //declare an empty array as $data outside the loop
    if($Q->num_rows() >0){
        foreach($Q->result_array() as $row){
            $data[] = array(          //using square brackets will push new elements onto the array $data
                "id" => $row['id'],
                "a_name" => $row['a_title'],
                "a_description" => $row['a_description'],
                "a_image" => $row['a_image']
            );
        }
    }

This way you will be returning the $data as an array of all results of your query, instead of re-assigning it and only ending up with a single result.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜