phpmysqlarrayscodeignitercodeigniter-3

Array constructed in loop only stores the last iteration's data


I am trying to display data using 2 tables in CodeIgniter. I have a products table with some products and another table with the id of the products, I did the following in my controller:

public function index()
{
    $selectfeatured = $this->product->selectfeatured();
    foreach ($selectfeatured as $val) {
        $id = $val->pid;
        $data['featured'] = $this->product->featured($id);
    }
    $this->load->view('home', $data);
}

In my model,

function selectfeatured()
{
    $this->db->select('*');
    $this->db->from('featured');
    $this->db->order_by("id", "desc");
    $this->db->limit(4);
    $query = $this->db->get();
    $result = $query->result();
    return $result;
}

function featured($pid)
{
    $this->db->select('*');
    $this->db->where("id", $pid);
    $this->db->from('product');
    $query = $this->db->get();
    $result = $query->result();
    return $result;
}

This code only displays one product eventhough I have multiple products in both the tables. Can anyone please tell me what is wrong in here?


Solution

  • Make your $data['feature'] as an array:

    public function index()
    {
        $selectfeatured = $this->product->selectfeatured();
        $data['featured'] = array();
        foreach ($selectfeatured as $val) {
            $id = $val->pid;
            $data['featured'][] = $this->product->featured($id); // add new item
        }
        $this->load->view('home', $data);
    }
    

    And make sure you display the featured array right way in your view, something like this:

    <?php foreach ($featured as $feature) : ?>
        <?php foreach ($feature as $product) : ?>
            <div class="item"><img style="height:250px" src="<?php echo base_url(); ?>admin/uploads/products/<?php echo $product->pimage; ?>" alt="" class="img-responsive"></div>
            </div>
        <?php endforeach; ?>
    <?php endforeach; ?>