2013-05-17 47 views
1

當我得到lastInsertId()時,我的pdo連接發生了一些奇怪的事情:在90%的時間內它運行良好,但在10%的情況下它返回0(我不知道如果真的是0或FALSE)。 但在100%的情況下,我的記錄已成功插入。PDO :: lastInsertID有時不起作用

這裏是我的代碼:

function execute_insert($sql, $values) { 
    try { 
     $dbConnection = new PDO('mysql:dbname=mydb;host=localhost;charset=utf8', 'username', 'mypass'); 

     $dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); 
     $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

     $dbConnection->beginTransaction(); 
     $stmt = $dbConnection->prepare($sql); 

     $stmt->execute($values); 

     $i = $dbConnection->lastInsertId(); 

     $dbConnection->commit(); 
     return $i; 

    } catch (PDOException $e) { 
     echo "erro :S - " . $e->getMessage(); 
     die(); 
    } 
} 


//blablabla 

$sql = "INSERT INTO ai_pessoas(nome, tipo, cpf, orgao_emissor_id, 
    rg_uf, rg, telefone1, telefone2, celular1, cidade_id, cep, endereco, 
    numero,complemento,bairro, email_principal, email_secundario, email_principal_confirmado, 
    dt_nascimento, oferta_id) "; 

$sql .= "VALUES(:nome,1,:cpf,:orgaorg,:ufrg,:rg,:telefone,:outroTelefone,:celular,:cidade,:cep,:endereco,:numero,:complemento,:bairro,:email,:emailAlternativo,FALSE,:datanasc,:idOfertaAtual);"; 

$idPessoa = execute_insert($sql, 
     array(
      ':nome' => $nome, 
      ':cpf' => $cpf, 
      ':orgaorg' => $orgaorg, 
      ':ufrg' => $ufrg, 
      ':rg' => $rg, 
      ':telefone' => $telefone, 
      ':outroTelefone' => $outroTelefone, 
      ':celular' => $celular, 
      ':cidade' => $cidade, 
      ':cep' => $cep, 
      ':endereco' => $endereco, 
      ':numero' => $numero, 
      ':complemento' => $complemento, 
      ':bairro' => $bairro, 
      ':email' => $email, 
      ':emailAlternativo' => $emailAlternativo, 
      ':datanasc' => $datanasc, 
      ':idOfertaAtual' => $idOfertaAtual 
)); 

if ($idPessoa > 0){ 
    //sometimes enters here, sometimes not 
} 

我的記錄是插入跳投,但 「如果($ idPessoa> 0)」 有時合乎理工作意味着$ idPessoa爲0或FALSE。

任何線索?

非常感謝!

回答

0

您可以嘗試LAST_INSERT_ID()達到此目的。

P.S.你的功能每次連接。

P.P.S.我也看到你不處理錯誤和回滾。我認爲你的10%插入失敗了。探索關於雙重調用這個函數,因爲你在某些領域有獨特的索引。並添加檢查result of executeerrorInfo

+0

你好,謝謝你的回答。我會試試這個,如果有效,我會讓你知道的。 – pzz

+0

PS:這是一個簡單的網頁,所以我只在兩個地方使用這種連接,在不同的場合,但我會在將來修復它。 PPS:我相信這並不是失敗,因爲這個腳本在'if($ idPessoa> 0){...}'結束後有更多的行,並且它們被執行。即:'die()'命令永遠不會執行......(至少此代碼從未引發任何'PDOException')。 – pzz