phpmysqlcodeignitersql-insertlast-insert-id

Execute an INSERT query and get the new record's autoincremented id in CodeIgniter


This is my statement which I am using.

$sql = "INSERT INTO store (shop_id, shop_index, items) VALUES ('$shop_id','65535','4')";
$this->db->query($sql);
return shop_st;

shop_st is the primary key which is auto incremented and I want to return it. I want to know whether my query is correct or wrong.


Solution

  • In terms of codeigniter's syntax, if you enable the database helper, you can do something like this:

    $data = array(
       'shop_st' => NULL,
       'shop_id' => $shop_id ,
       'shop_index' => '65535' ,
       'items' => '4'
    );
    
    $this->db->insert('mytable', $data); 
    

    I don't think there's anything more 'right' than your method, except you can do this.

    return $this->db->insert_id(); //shop_st
    

    which will get you your last inserted id.

    This answer is just to raise make you aware of codeigniter's built in helpers.

    The database helper can be found here.