Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter insert_id() function retrieve correctly the last insert id?

I been programming 3~4 years ago, and I remember that in some 2005 php security book about the safety of using mysql_insert_id to retrieve the last_inser_id.

In the book says that if there is several request to the server at the same time (thousands), could make the retrieve of last_insert_id wrong, ending with user's id pointing to other users.

Now we are in 2013, what you guys have to says about this, and especially using codeigniter insert_id().

pd: I tried to find relevant info about my question in other places but I didnt found something concrete.

like image 318
Jose Faro Avatar asked Oct 23 '13 20:10

Jose Faro


People also ask

How to get the last INSERT id in CodeIgniter?

CodeIgniter 4 Query Builder insertID()Using the Query Builder Class, we can INSERT and retrieve the Last Insert ID value, leveraging the built-in $builder insertID() method, which is called on the $db connection instance. Again, visiting the URL, /cicrud/home/users, executes the users() Home Controller method.

How do you get the last inserted record in CI?

Well, lucky for you.... getting the last database inserted ID using CodeIgniter is very simple. All you need to do is call the $this->db->insert_id(); function after you have just finished inserting a new row into the database and this will return that last 'unique' ID.

What does INSERT ID do in CodeIgniter?

Codeigniter provide method insert_id() to get last inserted id. insert_id() is function of "db" library. db library provides several function for connecting database task. insert_id() will return id of last inserted record.

What is Insert_batch?

insert is for inserting one record and insert_batch is for inserting multiple records.


1 Answers

Whoever wrote that book is full of crap. LAST_INSERT_ID() is specific to the connection, and the connection is specific to current invocation of the script. I can't think of a way to break this without re-writing some PHP source code after a night of heavy drinking.

Maybe if you're using persistent connections, and then if the last connection did an insert, and then you called LAST_INSERT_ID() before doing a successful insert yourself [you check your return values, right?], then maybe you might get a bad value. However, I have a very hard time imagining that this is possible.

So long as you're running LAST_INSERT_ID() immediately after the INSERT you just did it's always going to return the proper value.

Here's how you could break it if you really wanted:

$db_obj->insert('some data');
$db_obj->some_function_that_also_inserts_but_i_forgot_it_does_that('derp');
$id = $db_obj->last_insert_id();
like image 106
Sammitch Avatar answered Sep 30 '22 09:09

Sammitch