PDO lastInsertId()不适用于MS SQL

时间:2012-12-06 15:56:34

标签: php sql-server pdo

我正在使用PDO运行插入查询,然后使用lastInsertId()获取新创建的Id。这一切都在我的localhost环境中工作。

当我将完全相同的代码移动到服务器上时,lastInsertId()始终返回空白,即使insert语句有效并将新行插入数据库。这是我配置中的设置吗?任何帮助表示赞赏。

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

// bindParams ...

$insertstmt->execute();

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

$dbinsert = null;

2 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:0)

我在blog上描述了这个问题的解决方案。我无法直接修改代码中的sql查询,所以我以这种方式扩展了PDO类

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;
    }
}