我有一个名为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/