简体   繁体   English

尝试从数据库中读取数据并将其显示在表中,其中id是插入CodeIgniter的最后一个id

[英]Trying to read data and show it in table, from database where id is the last id that inserted CodeIgniter

I'm trying to get the data from a database and show it in a table, but the data that I want to get is the data with the latest id that was inputted. 我正在尝试从数据库中获取数据并将其显示在表中,但是我想要获取的数据是输入了最新ID的数据。

Here's my controller: 这是我的控制器:

function index(){
        $data['input_pen'] = $this->m_read->m_baca()->result();
        $this->load->view('v_read',$data);
}

Here's my model: 这是我的模型:

public function m_baca() {
        $no_lahan = $this->db->insert_id();

        $this->db->select('input_pen.no_form, 
                   lahan.jenis, 
                   lahan.penggunaan, 
                   lahan.kondisi,
                   lahan.drainase');

        $this->db->from('input_pen');
        $this->db->join('lahan', 'input_pen.no_lahan = lahan.no_lahan');
        $this->db->where('lahan.no_lahan', $no_lahan);
        $q = $this->db->get();

        return $q;
}

and here's my view 这是我的看法

<table border="1">
        <?php 
        $no = 1;
        foreach($input_pen as $p){ 
        ?>
        <tr>
            <td><?php echo $no++ ?></td>
            <td><?php echo $p->no_form ?></td>
            <td><?php echo $p->jenis ?></td>
            <td><?php echo $p->penggunaan ?></td>
            <td><?php echo $p->kondisi ?></td>
            <td><?php echo $p->drainase ?></td>
            </td>
        </tr>
        <?php } ?>
    </table>

When I run this code, will display a blank view. 当我运行此代码时,将显示一个空白视图。

What do I do to get the latest id? 如何获取最新的ID?

What is wrong? 怎么了?

Please help. 请帮忙。

Thanks. 谢谢。

May be this can help you out, if your lahan.no_lahan column is a primary key and is autoincrement field then you can get the result of your query in the following way 可能是这样可以帮助您,如果您的lahan.no_lahan列是主键且是autoincrement字段,则可以通过以下方式获取查询结果

$this->db->select('input_pen.no_form, 
               lahan.jenis, 
               lahan.penggunaan, 
               lahan.kondisi,
               lahan.drainase');

    $this->db->from('input_pen');
    $this->db->join('lahan', 'input_pen.no_lahan = lahan.no_lahan');
    $this->db->where('lahan.no_lahan', $no_lahan);
    $this->db->order_by('lahan.no_lahan', 'DESC');
    $this->db->limit('1');
    $q = $this->db->get();

using order by your primary field and setting limit to 1, so you will always get the last record inserted in that table. 在主字段中使用order并将限制设置为1,因此您将始终获得该表中插入的最后一条记录。

or the other thing you can do is, at the time where you are inserting the data in the table there you get the last inserted id something like this 或者您可以做的另一件事是,在将数据插入表中时,您会得到最后插入的ID,如下所示

function add_data($post_data){
$this->db->insert('input_pen', $post_data);
$insert_id = $this->db->insert_id();
return  $insert_id;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM