简体   繁体   中英

PDO lastInsertId() not working for MS SQL

I am running an insert query using PDO and then getting the newly created Id with lastInsertId(). This is all working on my localhost environment.

When I move the exact same code onto a server, the lastInsertId() is always returning blank, even though the insert statement works and inserts the new row into the database. Would this be a setting in my configuration? Any help is appreciated.

$insertstmt = $dbinsert->prepare($insertsql);

// bindParams ...

$insertstmt->execute();

// always blank
$id = $dbinsert->lastInsertId();

$dbinsert = null;

我最终使用以下方法替换了lastInsertId(): http ://php.net/manual/en/pdo.lastinsertid.php#105580

$temp = $sth->fetch(PDO::FETCH_ASSOC);

I've describe a solution for this problem on my blog . I couldn't directly modify sql queries in the code, so I extended the PDO class in this way

class BetterPDO extends \PDO
{
    protected $stmt;
    protected $withIdentitySelect;

    public function prepare($statement, $driver_options = null)
    {
        $this->$withIdentitySelect = false;

        if (preg_match('/^insert/i', $statement)) {
            $statement = "{$statement}; select SCOPE_IDENTITY() AS 'Identity';";
            $this->$withIdentitySelect = true;
        }

        $this->stmt = parent::prepare($statement, is_array($driver_options) ? $driver_options : []);
        return $this->stmt; 
    }

    public function query($statement)
    {              
        $this->$withIdentitySelect = false;

        if (preg_match('/^insert/i', $statement)) {
            $statement = "{$statement}; select SCOPE_IDENTITY() AS 'Identity';";
            $this->$withIdentitySelect = true;
        }

        $this->stmt = parent::query($statement);
        return $this->stmt;     
    }

    public function lastInsertId($name = null)
    {
        $lastIndex = 0;

        if (($this->$withIdentitySelect) && ($this->stmt->columnCount() > 0)) {
            $lastIndex = $this->stmt->fetchColumn(0);
            $this->stmt->closeCursor();
        }

        return $lastIndex;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM