【问题标题】:PDO lastInsertId() not working for MS SQLPDO lastInsertId() 不适用于 MS SQL
【发布时间】:2012-11-24 17:02:41
【问题描述】:

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

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

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

// bindParams ...

$insertstmt->execute();

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

$dbinsert = null;

【问题讨论】:

  • 定义blank。没有blank 数据类型,所以我假设您的意思是''0falsenull 之一。使用var_exportvar_dump 来确定你得到哪一个。提及您正在使用的数据库后端(以及哪个版本)也可能会有所帮助。
  • 空白如''。 var_export 和 var_dump 也都返回 '' 。我正在使用 dblib 连接到 SQL Server 数据库。
  • var_dump('') 输出 string(0) "",所以你绝对确定这就是你在 ID 中得到的,而不是你的代码不符合你的假设或发生了以某种方式被静音的错误?如果在最后一行之前添加echo "foo"; var_dump($id); echo "bar";,会得到什么输出?
  • 我明白了。我分离出那部分代码,以便我可以正确测试它。 $id 输出'',var_dump 输出'bool(false)',var_export 输出'false'
  • 这一切似乎告诉我新插入的记录没有被返回。这个问题是由服务器上不同版本的 PDO 或 dlib 引起的吗?是否需要在 php 中进行任何配置才能使其工作?

标签: php sql-server pdo


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    我已经在我的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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-16
      • 2015-10-07
      • 2020-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多