【问题标题】:How to use user_id to get users details from database and display them如何使用 user_id 从数据库中获取用户详细信息并显示它们
【发布时间】:2017-09-20 11:44:45
【问题描述】:

我正在 CodeIgniter 框架上创建一个网站,以便用户可以向网站添加产品。现在我的问题是:如何使用 products 表中的 user_id 从数据库中获取用户的详细信息并将其显示在产品旁边? 例如,当我点击一个产品时,我想要一个指向上传该产品的用户个人资料的链接,但我不知道该怎么做。

数据库表信息:

table users:

user_id (primary_key)
email
voornaam
achternaam
beschrijving


table products:

product_id (primary_key)
product_naam
product_beschrijving
user_id
category_id

我在模型文件中的函数:

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

【问题讨论】:

    标签: php codeigniter


    【解决方案1】:

    使用基于 user_id 的联接查询从数据库中的 2 个表中获取详细信息。

    像这样:

    型号:

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

    控制器:

    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.
    

    查看:

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

    【讨论】:

    • 我应该输入什么来回显它?
    • 你能用我的数据库信息改变你的代码吗?表用户:user_id (primary_key) email voornaam achternaam beschrijving 表产品:product_id (primary_key) product_naam product_beschrijving user_id category_id
    • 我的问题中也有我的数据库信息。你能改一下吗,因为我可能会混淆一些东西
    • 检查一下,我更新了我的编码,在我的视图中使用了你的数据库详细信息
    • stackoverflow.com/questions/793807/… 引用此链接以加入 2 个表
    猜你喜欢
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-19
    • 2020-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多