Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How efficient is Last_insert_id?

I recently came across a problem where I needed to be able to grab the last ID of a query I've inserted on a page. The process was quite simple, but I'd like some reassurance on how the process is done. Here's how my code is:

$query30 = $db->query("INSERT `mybb_quickexample` SET `player1` = '".$row19[username]."', `player2` = '".$row18[username]."', `games` = '".$numberofgames."'")or die(       mysqli_error());

As you can see I have just inserted something into mybb_quickexample, which then generates an ID. Now in the code directly under it, I try to locate the ID.

$mmid = $db->insert_id(); 

foreach($_POST['optiontitle'] as $val){
$val = $db->escape_string($val); //
echo $val;
$query30 = $db->query("INSERT `mybb_quickexample2` SET `gid` = '".$id."', `mid` = '".$mmid."', `optiontitle` = 'OPTION TITLE', `option1` = '$val'")or die(      mysqli_error());

}

As you can see, it grabs the recent ID and puts it into the new table. Allowing for these 2 tables to correspond with each other later on when I need them to.

However, does insert_last_id grab the last row inserted into the database or the last row inserted into the database on the page? Now I'm not entirely sure of the mechanics behind this, but I ask this because, what if a person was to load this page at the same exact time as another person? Would there be unmatched ID grabs or would the code still work?

like image 285
Josh Potter Avatar asked May 02 '15 17:05

Josh Potter


People also ask

What will be the value of LAST_INSERT_ID () for the newly created table?

With no argument, LAST_INSERT_ID() returns a 64-bit value representing the first automatically generated value successfully inserted for an AUTO_INCREMENT column as a result of the most recently executed INSERT statement.

What does the function LAST_INSERT_ID?

The LAST_INSERT_ID function returns the last AUTO_INCREMENT value on a client-by-client basis, so it will only return the last AUTO_INCREMENT value for your client. The value can not be affected by other clients. Executing the LAST_INSERT_ID function does not affect the value that LAST_INSERT_ID returns.


1 Answers

insert_last_id returns the last inserted ID of the very same SQL session/connection (see MySQL manual). - The SQL server does not know about your pages. As long as the connection/session is not shared there are no problems (such as race conditions).

It's also possible to get the last inserted ID using SQL only: select LAST_INSERT_ID(); or use it directly in a following SQL query in order to reduce client-server round-trips like insert table B set foreign_id=LAST_INSERT_ID(),data="something"; (note, however, if the following SQL statement also has an auto increment column the next LAST_INSERT_ID() call would return the newest inserted ID; see MySQL manual)

like image 91
MrTux Avatar answered Oct 21 '22 14:10

MrTux