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
  •  | 
  •  

문제

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.

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top