With MySQL/PDO, I believe PDO::lastInsertID() returns the ID of the last inserted object for the connection. I have my PDO object contained in a singleton object that any method can call so there's only one database connection per HTTP request to the server.
class Database {
public $db;
private static $dsn;
private static $instance;
private function __construct()
{
$this->db = new PDO( self::$dsn );
}
public function __destruct()
{
$this->db = null;
}
public static function getInstance()
{
if ( !isset( self::$instance ) ) {
$object = __CLASS__;
self::$instance = new $object;
}
return self::$instance;
}
}
$database = Database::getInstance();
$handle = $database->db->prepare(); // etc etc etc
Correct me if I'm wrong but I believe each HTTP request to Apache spawns a separate PHP instance, so I don't think that singleton would be shared between those PHP instances and since there's no concurrency in the code, I think it should be happening linearly. So I don't think this case could happen:
- Method A inserts a row with Query A
- Method B inserts a row with Query B
- Method A asks for the last inserted ID expecting Query A's result, getting Query B's instead
- Method B asks for the last inserted ID expecting and getting Query B's result
Already read these, no answer found:
PDO Last Insert ID always the right one? http://php.net/manual/en/pdo.lastinsertid.php