Viewed   70 times

Are there any options to get the last insert id of a new record in CodeIgniter?

$last_id = $this->db->insert('tablename',
    array('firstcolumn' => 'value',
    'secondcolumn' => 'value')

Considering the table consits of fields id (autoincrement) firstcolumn and secondcolumn.

This way you can use the insert id in the following code.



Shame on me...

I looked at the user guide and the first function is $this->db->insert_id();

This also works with activerecord inserts...

EDIT: I updated the link

Sunday, September 4, 2022

INSERT, UPDATE and DELETE in PostgreSQL have a RETURNING clause which means you can do:


Then the query will return the value it inserted for id for each row inserted. Saves a roundtrip to the server.

Sunday, November 27, 2022

Hm, understand. As I see the subquery's source code in line 27, it wants to call _compile_select or get_compiled_select. If you can check in CI's DB_active_rec.php the _compile_select is protected so you can't access from Subquery (it isn't subclass of db).

Possible solution: _compile_select() should public or class Subquery should be extend of CI's db class. I think you should report this to author of Subquery.

Or you can extend the CI's db class :)

Sorry - I want to write it as a comment.

Sunday, December 18, 2022

Try this code it might help you :

Here dashboard is the name of controller

//this will route as localhost/appFolder/admin/index
  $route['admin'] = 'dashboard'; // for your index page

//this will route as localhost/appFolder/admin/method_name
 $route['admin/(:any)'] = 'dashboard/$1';

//this will route as localhost/appFolder/admin/method_name/param1
$route['admin/(:any)/(:any)'] = 'dashboard/$1/$2';

Link the route Like

// for your index page
<a href="<?php echo base_url('admin/index'); ?>"></a>

// for your other pages
<a href="<?php echo base_url('admin/method_name'); ?>"></a>

To link the other controller defined just like

 <a href="<?php echo base_url('otherControllerName/method_name'); ?>"></a>
Sunday, September 4, 2022

Ok i solved it!

i added an int output parameter called last_id, before the end tag i included this statement:

select last_insert_id() into last_id;

In PHP i execute:

$db -> execQuery('call aggiungi_categoria('.$parametri['id_categoria_principale'].',"'.$parametri['nome'].'","'.$parametri['sigla'].'",'.$parametri['stato'].',@lastId);');

and finally

$lid = $db ->execQuery('select @lastId;');
Saturday, September 10, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :