简体   繁体   中英

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.

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?

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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