Вопрос

I am wondering how exactly does lastInsertId() work. Atm, I am using it like this to get the id of the inserted row so I can use this id in other sections of the code. For example:

$stmt = $db->prepare('INSERT INTO image_table (image_name, image_size) VALUES (:image_name, :image_size)'); 

$stmt->execute(array(
    'image_name' => $photoName,
    'image_size' => $image_size / 1024, 
    ));

$lastInsertId = $db->lastInsertId('yourIdColumn');

Okay, my question is:

1) Does this script get the lastInsertIdfor the SQL insert that was done in that particular script?

2) What happens, for example say, 3 different users inserted data into the same table just a few nano seconds difference. Something like this:

this script -> Inserts to row id 1
Another user -> Inserts to row id 2
Another user -> Inserts to row id 3

In that case, would the lastInsertId() return the value 1 since it was the last id for the row that was inserted by that script or will it return 3 since that was the last id by the time the script came to the line that executes lastInsertId() function?

Это было полезно?

Решение

  1. The id of the last sql insert in that scripts execution (not say, another competing insert for another user).

  2. When you have 3 inserts, it gets you the lastInsertId() like it states, the LAST one, not all 3, not 2... just the last one. Combat this by running your inserts individually and fetching the id, OR just search based on insert criteria if you need to pull that data again. inserts by different users/session, see answer #1, the lastInsertId() applies for the specific user/session/execution, not for all operations. There are basic MYSQL db temp operations happening in the background as well that would return ids if that was true.

Hope that helps.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top