dskm94301 2017-09-20 11:44
浏览 66
已采纳

如何使用user_id从数据库中获取用户详细信息并显示它们

I'm making a website on the CodeIgniter framework so users can add products to the website. Now my question is: How do I use the user_id in the products table to get the user's details from the database and display them next to the product? So for example when I click on a product I want to have a link to the profile of the user who uploaded the product but I'm not sure how I can do that.

Database tables information:

table users:

user_id (primary_key)
email
voornaam
achternaam
beschrijving


table products:

product_id (primary_key)
product_naam
product_beschrijving
user_id
category_id

My function in model file:

public function get_product_details($product_id) {
    $this->db->select('products.*, users.*');
    $this->db->from('products');
    $this->db->join('users', 'users.user_id = products.user_id', 'left');
    $this->db->where('product_id', $product_id);
    $query = $this->db->get();
    $result = $query->row_array();
    if (!empty($result)) {
        return $result;
    } else {
        return array();
    }
}
  • 写回答

1条回答 默认 最新

  • dongwei1855 2017-09-20 11:58
    关注

    Use join query based on user_id fetch details from 2 tables in database.

    Like this:

    Model:

    public function get_product_details($product_id)
    {
        $this->db->select('users.user_id,users.email,users.voornam,products.product_id,products.category_id,products.product_naam');
        $this->db->from('users');
        $this->db->join('products','products.user_id = users.user_id');
        $this->db->where('product_id', $product_id);
        $query = $this->db->get();
        if($query->num_rows()>0)
        {
           return $query->result_array();
        }
    }
    

    Controller:

    public function edit($product_id)
    {
        $data['products_list'] = $this->your_model->get_product_details($product_id);
        $this->load->view('your_view_filename',$data);
    }
    
    // data from $data['products_list'] in controller.
    

    View:

    <?php print_r($products_list); //for refference
        foreach($products_list as $row)
                        {
                        ?>
                        <tr>
                            <td><?php echo $row['email'];?></td>
                            <td><?php echo $row['voornam'];?></td>
                            <td><?php echo $row['product_naam'];?></td>
                                etc...
                         </tr>
       <?php } ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳