Search code examples
phpmysqldatabasecodeignitercodeigniter-3

matching two columns in mysql table in codeigniter not working


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 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 even though 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; ?>