在 codeigniter 中匹配 mysql table 中的两列不起作用

matching two columns in mysql table in codeigniter not working

我正在尝试在 codeigniter 中使用 2 table 显示数据,我有一个产品 table 和一些产品,另一个 table 有产品的 id,我做到了控制器中的以下内容:

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);

  }

在我的模型中,

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;
        }

此代码仅显示一种产品,即使我在 table 中有多种产品,谁能告诉我这里有什么问题

变量 $data['featured'] 在一个循环中并且在每次迭代中获取新值,并在每次迭代中被覆盖,这就是为什么你只得到一个产品,你需要使用 array_push 或 '+=' 等附加其他产品。

将您的 $data['feature'] 设为数组:

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);
}

并确保在视图中正确显示 featured 数组,如下所示:

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