2

First of all, I know about PDO lastInsertId() method. Lets design a model function here:

function insert_user_file ($name, $type, $size, $content) {
        try {

        $insertfile = new PDO("mysql:host=".$server.";dbname=".$db, $mysql_login, $mysql_pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
        $insertfile->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt=$insertfile->prepare ("INSERT INTO files (name, size, type, content) VALUES (:fileName, :fileSize, :fileType, :content)");

        $stmt->bindParam(":fileName", $name);
        $stmt->bindParam(":fileSize", $size);
        $stmt->bindParam(":fileType", $type);
        $stmt->bindParam(":content", $content);
        $stmt->execute();
        //now imagine we are in a highly loaded environment and another user manages to run a similar query at this very moment of the code
        return $insertfile->lastInsertId();//then this is a wrong id!
        }
        catch(PDOException $e) {
            echo 'error: '. $e->getMessage();
        return false;
    }
}

The question is how to ensure that your are getting the actual ID of a record you just inserted. As far as I know, in highly loaded systems it might be possible that in the time of between $stmt->execute(); and return $insertfile->lastInsertId(); some other records could be inserted by some other user and/or process in the system. This is really important because i'm designing an archiving software and the user files and user data are stored in different tables. User data stores only references (ids) of the required files.

RWS
  • 538
  • 5
  • 14
  • 1
    It retrieves the last inserted ID from **that** connection. So sure, other rows can be inserted by other connections, but that will not affect your result. – Devon Bessemer Oct 02 '16 at 16:57

0 Answers0