2012-12-06 53 views
2

我正在運行使用PDO的插入查詢,然後使用lastInsertId()獲取新創建的Id。這一切都在我的本地主機環境。PDO lastInsertId()不適用於MS SQL

當我將完全相同的代碼移動到服務器上時,即使insert語句正常工作並將新行插入到數據庫中,lastInsertId()始終返回空白。這是我的配置中的設置嗎?任何幫助表示讚賞。

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

// bindParams ... 

$insertstmt->execute(); 

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

$dbinsert = null; 
+3

定義了'blank'。沒有'空白'數據類型,所以我假設你的意思是'''','0','false','null'之一。使用['var_export'](http://php.net/var_export)或['var_dump'](http://php.net/var_dump)來確定你得到的是哪一個。它也可能有助於提及您正在使用的數據庫後端(以及在哪個版本中)。 – phihag

+0

空白如''。 var_export和var_dump都返回''。我正在使用dblib連接到SQL Server數據庫。 – Drew

+0

'var_dump('')'outputs'string(0)「」',所以*你絕對可以肯定*這就是你在ID中得到的,而不是你的代碼不符合你的假設或者發生錯誤已經以某種方式沉默了?如果你添加'echo「foo」;後續代碼var_dump($ ID);回聲「酒吧」;'在最後一行之前,你會得到什麼輸出? – phihag

回答

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