CodeIgniter Forums
How to get the last Inserted ID after insert data using the query builder ? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: How to get the last Inserted ID after insert data using the query builder ? (/showthread.php?tid=74529)



How to get the last Inserted ID after insert data using the query builder ? - Poetawd - 10-05-2019

Hello !

Does anyone knows how to get the last Inserted ID after insert data using the query builder class?

In CI 3 I just used:
PHP Code:
$this->db->insert_id(); 

What would be the equivalent in CI 4 ?

PHP Code:
    public function insertNewCandidate($candidate) {

        $db      = \Config\Database::connect();
        $builder $db->table('dados_candidates');
        
        $query 
$builder->insert($candidate);

        if( $query ):
            
            
return ?????????????;
            
        
else: 

            return FALSE;
            
        
endif;
        
    


And YES, I do want to use query builder for this... 

I tried to find it in $db, $builder and $query... But it is not there....


RE: How to get the last Inserted ID after insert data using the query builder ? - Poetawd - 10-05-2019

(10-05-2019, 07:44 PM)donpwinston Wrote: Did you try:

$query = $db->query("SOME QUERY");

$id = $query->resultID;

This worked:

PHP Code:
return $db->insertID(); 

The problem is that when you search the User Guide for "insert id" or "insert_id" it returns 0 results.... That is why I couldn´t find it.

But it is there: https://codeigniter4.github.io/userguide/database/helpers.html 

Thank you !

Confused


RE: How to get the last Inserted ID after insert data using the query builder ? - InsiteFX - 10-06-2019

Working With Databases - Query Helper Functions