gpt4 book ai didi

php - 如何使用foreach在表中显示左连接选择查询的记录?

转载 作者:可可西里 更新时间:2023-11-01 08:40:16 25 4
gpt4 key购买 nike

我有两个表(表 A 和表 B)。我需要在一张表中显示它们,但我对如何在表中显示记录有疑问。请看我的示例:

表A:

id   name
1 John
2 Mark
3 Nick`

表b:

id     job 
1 Encoder
2
3 Programmer`

我做了一个连接两个表的查询

select a.id, a.name, b.job from table_a a
left join table_b b on b.id=a.id
order by a.id;

使用代码点火器,

这是 Controller :

$this->db->select('a.id, a.name, b.job);
$this->db->from('table a');
$this->db->join('table b', 'b.id=a.id', 'left');
$this->db->order_by('a.id');
$query = $this->db->get();
$data["view_records"]=$query;
$this->load->view("table_name", $query);

这是 View

<table id="tablestyle" class="table table-bordered table-hover table-condensed">
<col width="50">
<col width="150">
<col width="150">
<col width="150">
<thead>
<tr>
<th><strong>ID</strong></th>
<th><strong>NAME</strong></th>
<th><strong>JOB</strong></th>
<th></th>
</tr>
</thead>
<tbody>
<?php foreach($view_records->result() as $row) { ?>
<tr>
<td><?php echo $row->a.id; ?></td>
<td><?php echo $row->a.name; ?></td>
<td><?php echo $row->b.job; ?></td>
<td><input type="submit" value="Modify" id="btnModify" class="btn btn-block btn-success btn-xs" onclick="btnModify('<?php echo $row->a.id; ?>');"/></td>
</tr>
<?php } ?>
</tbody>
</table>

最佳答案

在模型中

public function get_user()
{
$query = $this->db->query("select a.id, a.name, b.job from table_a a
left join table_b b on b.id=a.id
order by a.id");
$result = $query->result_array();
return $result;
}

在 Controller 中

$data['get_user'] = $this->model_name->get_user();

$this->load->view("view_name", $data);

在 View 中

<table id="tablestyle" class="table table-bordered table-hover table-condensed">
<col width="50">
<col width="150">
<col width="150">
<col width="150">
<thead>
<tr>
<th><strong>ID</strong></th>
<th><strong>NAME</strong></th>
<th><strong>JOB</strong></th>
<th></th>
</tr>
</thead>
<tbody>
<?php foreach($get_user as $rowItem) { ?>
<tr>
<td><?php echo $rowItem['a.id'] ?></td>
<td><?php echo $rowItem['a.name'] ?></td>
<td><?php echo $rowItem['b.job'] ?></td>
<td><input type="submit" value="Modify" id="btnModify" class="btn btn-block btn-success btn-xs" onclick="btnModify('<?php echo $rowItem['a.id'] ?>');"/></td>
</tr>
<?php } ?>
</tbody>
</table>

关于php - 如何使用foreach在表中显示左连接选择查询的记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34303809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com