php - 显示数据库中的记录 [codeigniter]

标签 php mysql codeigniter

我有一个名为person的表,通过id显示。该表有许多列,其中有一列名为 product_id。第二个表产品包含所有产品的名称。假设我在表 product 中有一个字段名称为 rice 的产品,他的 ID 4 位于 person 表中。当我显示人员表行时,我想显示大米而不是他的id

<?php
public function person()
{
    $id= $this->uri->segment(3);
    $query = $this->model_person->get_persons($id);
    $data['all_persons'] =$query;
    $this->load->view('admin/view_person', $data);

}
?>

模型 get_person

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

view_person.php

<?php foreach($all_persons as $p)
{
?>
    <tr>
        <th >Person name</th>
        <td ><?=$p->name;?></td>
    </tr>
    <tr>
        <th >Person affectation</th>
        <td ><?=$p->affectation;?></td>
    </tr>
    <tr>
        <th>Product name</th>
        <td><?=$p->id_product;?></td>
        <!--i want to dispay product name found in product table-->
    </tr>
<?php
}
?>

最佳答案

要获得这样的输出,您需要在模型中运行联接查询。

 public function get_persons($id)
    {
        $this->db->select("*");
         $this->db->from('person');
         $this->db->join('product', 'product.id= person.product_id');
         $this->db->where('person.id',$id);
         $query = $this->db->get();
        return $query->result();
     }

在view_person.php中只打印product_name而不是product_id

<tr>
        <th>Product name</th>
        <td><?=$p->product_name;?></td>
        <!--i want to dispay product name found in product table-->
    </tr>

关于php - 显示数据库中的记录 [codeigniter],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47039587/

相关文章:

php - 在 codeigniter 中处理多个复选框数组

php - 登录后 session 未保存

php - Quickbooks 在线 API 与 oauth2

php - PHP 中的 MySQL 查询给出了明显的错误结果

mysql - DB中的索引是什么意思?

mysql - GROUP BY 逗号分隔列表的成员

javascript - CodeIgniter AJAX文件上传,上传时$_FILE为空

php - 从组合框中获取选定的值 PHP Codeigniter

php - 在MySQLi中使用if/else的回显错误

php - 如何仅在退出另一个容器后才启动Docker容器