1

I am about to create a row in a table. This will generate a orderID with Auto_increment. Next I want this number (orderID) pulled out, and I need this number to be 100% from the newly constructed row. My suggestion is the following code.

Will this be safe even if 1.000.000 users run the same routine at same time?

$this->conn->beginTransaction();
try
{
    // Create User Table
    $stmt = $this->conn->prepare("INSERT INTO moneytransactionstbl(trnsUserID) 
                                  VALUES(:trnsUser_ID)");

    $stmt->bindparam(":trnsUser_ID",$userID);

    $stmt->execute();   

    // Get the Order ID 
    $trnsOrderID = $this->conn->lastInsertId();

    // Commit this rutine run
    $this->conn->commit();

    return $trnsOrderID;
}
catch(PDOException $ex)
{
    echo $ex->getMessage();
    $this->conn->rollBack();
}
showdev
  • 28,454
  • 37
  • 55
  • 73
Hans Pede
  • 89
  • 1
  • 9
  • 2
    Possible duplicate of [Thread safety of MySql's Select Last\_Insert\_ID](http://stackoverflow.com/questions/30959678/thread-safety-of-mysqls-select-last-insert-id) –  Jul 03 '16 at 04:03
  • **Spoiler alert** you'll be fine –  Jul 03 '16 at 04:04
  • If you use innodb not only will 1M be safe, but there is a good chance 1.3M will be gap allocated. So fear not. – Drew Jul 03 '16 at 04:51
  • hmm okay, @Terminus, that means I actually can skip `beginTransaction();`? – Hans Pede Jul 03 '16 at 05:15
  • If your only reason for having it was for the `lastinsertid` then I'd say yea. –  Jul 03 '16 at 05:17

0 Answers0