2

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

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

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

// bindParams ...

$insertstmt->execute();

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

$dbinsert = null;
4

2 回答 2

4

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

$temp = $sth->fetch(PDO::FETCH_ASSOC);
于 2012-12-06T19:59:53.440 回答
0

我已经在我的博客上描述了这个问题的解决方案。无法直接修改代码中的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;
    }
}
于 2017-09-04T10:48:54.057 回答