CodeIgniter Forums

Full Version: mysqli $this->db->insert_id constantly returns 0
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone i have been using codeigniter for 8 years now...

i am having an issue when switching from the mysql driver to the mysqli driver from the application/config/database.php


when i switch to mysqli $this->db->insert_id constantly returns 0... when i was using the old mysql driver it was working fine... i cant find anyone else with the same issue... i had the same issue with codeigniter 2.x... my pconnect is set to true... even when i set my pconnect is set to false i get the same result...


i do a standard:

$this->db->insert('gallery_gal', $data);
$this->db->insert_id(); // returns 0 every time

the id value is set as auto_increment on the gallery_gal table with the id field called "id_gal"

Can someone please help me with this...


here is my db configuration

$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'buzzdb',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => TRUE,
'db_debug' => TRUE,
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);

Thanks in advance...
Is this with CI3? You might try turning off "save_queries". Not sure but worth a try. Actually, I don't even see that parameter in the docs?
I tried makingĀ 'save_queries' => FALSE as you said...

it still didn't work Smile
try removing it entirely. I don't see that as a db option in the docs?
i tried removing it totally.. it didn't change anything... i still get $this->db->insert_id() = 0 after i insert a record...
'save_queries' just adds the last executed query to an array, so that it can be later returned by last_query(); it doesn't affect anything else but memory usage.

In fact, having 'save_queries' turned on (which is the default, even when you don't have it in the config) may help you debug the issue ... Do a var_dump($this->db->last_query()) right before calling insert_id().

Does it show an INSERT query? If not, there's your problem.
MySQLi resets the insert id upon committing the transaction (intended behaviour). When it's without a transaction, I think that behaviour differed between PHP versions, due to a bug. Try wrapping it in a transaction, by calling trans_begin(), then the insert(), then the insert_id(), then commit().