0

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_description" => $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>

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.