how do I reliably insert into a table then retrieve the autonumber in a multi user system

StackOverflow https://stackoverflow.com/questions/14724939

  •  07-03-2022
  •  | 
  •  

Question

Suppose I run an insert statement like this:

        $sql = "insert into tbl_features (feature_class, feature_name, description) values (?, ?, ?)";
        $q = $pdo_conn->prepare($sql);
        $q->execute(array($_GET['new_feature_class'], $_GET['new_feature_name'], $_GET['new_description']));

I then want to retrieve the id of the row that was just inserted to use it in another table. I could use select max() but how can I be sure that nobody else has done an insert, thus giving both users the same max to try to cram into other tables? I'm happy to lock the entire table, the code gets run infrequently enough that it won't make a noticeable difference. Maybe I'm being pedantic but I want to go to bed at night knowing my code is bulletproof.

Was it helpful?

Solution

You can use lastInsertId to retrieve it: http://php.net/manual/en/pdo.lastinsertid.php.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top