简体   繁体   中英

CodeIgniter display last id

I want to display as a value of textbox the last id of my record and then increment it.

This is what I have:

view.php

          <?php 
            $id = $this->db->insert_id();
            $newId = $id + 1;
            $data = array(
                    'name'        => 'customercode',
                    'id'          => 'inputCustomerCode',
                    'type'        => 'text',
                    'readonly'    => 'true',
                    'class'       => 'form-control',
                    'value'       => 'CUST0000' . $newId
            );
            echo form_input($data);
            ?>

But it's just displaying CUST00001 ? What am I doing wrong in here? Help is much appreciated and needed. Thanks.

Instead of using $id = $this->db->insert_id(); you may use following code:

$query = $this->db->query("SELECT id FROM mytable ORDER BY id DESC LIMIT 1");
$id = $query->row()->id;

$newId = $id + 1;

$data = array(
   'name'        => 'customercode',
   'id'          => 'inputCustomerCode',
   'type'        => 'text',
   'readonly'    => 'true',
   'class'       => 'form-control',
   'value'       => 'CUST' . str_pad($id+1, 5, '0', STR_PAD_LEFT)
   );

echo form_input($data);

you can get last inserted id with $this->db->insert_id(); if you want to use this for multiple places, please take this in a variable and use that variable.

you can use $this->db->insert_id() after insert query.

$id = $this->db->insert_id();

you can use a simple query to get max id

$query = $this->db->query("SELECT MAX (id) FROM table");
$id = $query->row()->id;

and use $id in form

 'value'       => 'CUST0000' . $id + 1

Instead of

$this->db->insert_id()+1

You need to display $newId . Make sure you have queried for the last Id. $this->db->insert_id() returns only when you have inserted some record. If you haven't , then you need to query to get the last inserted id. You can use this simple query.

SELECT id FROM mytable ORDER BY id DESC LIMIT 1

$this->db->insert_id()

The insert ID number when performing database inserts.

Looked at http://ellislab.com/codeigniter/user_guide/database/helpers.html and the first function is $this->db->insert_id();

This also works with active-record inserts...

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