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

时间:2015-12-16 04:13:19

标签: php mysql codeigniter foreach left-join

我有两张桌子(表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;

使用codeigniter,

这是控制器:

$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);

这是视图

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

1 个答案:

答案 0 :(得分:1)

在模型中

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

在控制器中

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

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

在视图中

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