E
E
Ellik2015-11-05 19:37:09
PHP
Ellik, 2015-11-05 19:37:09

Using lastInsertId() inside a transaction, can you be sure that the ID will not be taken from another transaction in the global sense?

$db->beginTransaction();
        /*****/
        $sql = "INSERT INTO products (name, price) VALUES (:name, :price)";
        $sth = $db->prepare($sql);
        $sth->execute(
          array(
            ':name'=>$product['main']['name'],
            ':price'=>$product['main']['price'],
          )
        );
        // Получаем id последней вставленной записи
        $idProduct = $db->lastInsertId();

        /*****/
        foreach ($product['attributes'] as $attribute) {
          $sql = "INSERT INTO productAttribute (idProduct, nameAttribute) VALUES (:idProduct, :nameAttribute)";
          $sth = $db->prepare($sql);
          $sth->execute(
            array(
              ':idProduct'=>(int)$idProduct,
              ':nameAttribute'=>$attribute['attribute'],
            )
          );
        }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dimonchik, 2015-11-05
@Ellik

lastInsertId() is unique per table
Why is PDO::lastInsertId returning the wrong ID on frequent database inserts?

A
Alexander Melekhovets, 2015-11-05
@Blast

Yes, for mysql it is possible.
https://dev.mysql.com/doc/refman/5.7/en/mysql-inse...
That is, the last generated ID in the current connection is taken.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question