2011-11-30 40 views
0

我只是嘗試這種代碼:PDO,收到錯誤,如果採取

public function create_account($username, $password, $email) { 
    $password = sha1($password); 
    $activation_key = md5($username . $email); 

    $this->STH = $this->DBH->prepare("INSERT INTO users(username, password, email, activation_key, created) VALUES(:username, :password, :email, :activation_key, :created)"); 
    $this->STH->bindParam(':username', $username); 
    $this->STH->bindParam(':password', $password); 
    $this->STH->bindParam(':email', $email); 
    $this->STH->bindParam(':activation_key', $activation_key); 
    $this->STH->bindParam(':created', time()); 
    $this->STH->execute(); 

    if ($this->DBH->lastInsertId()) { 
     //$this->send_mail($username, $email); 
     return true; 
    } else { 
     //Log 
    } 
} 

現在它工作,確實如此。但就在一分鐘前,我錯過了a)SQL語句,導致數據未被插入。我嘗試了try {} catch塊 - 但我沒有收到任何錯誤,仍然 - 是否假設是這樣? 我怎樣才能解決這個代碼,正確登錄PDO的錯誤(如果接受)

+2

可能相關:[如何從PDO擠出錯誤消息?](http://stackoverflow.com/q/3726 505) –

回答

1

​​返回一個布爾值 - 只檢查它。基本上,你可以使用它像這樣:

if ($this -> STH -> execute() === false) { 
    print_r($this -> STH -> errorInfo()); 
} 
+2

此外,如果您添加try/catch塊並且您有多個插入,則可能需要嘗試使用事務並在發生異常時進行回滾... – Homer6

1

您是否嘗試過捕捉使用錯誤:

try { 
    $this->STH->execute(); 
} catch (PDOException $pdostmtex) { 
    echo('Exception encountered: '.$pdostmtex->getCode().' -> '.$pdostmtex->getMessage()); 
    exit; 
} 

,並確保您的錯誤報告是:

http://php.net/manual/en/function.error-reporting.php取出並僅作爲參考:

// Report all errors except E_NOTICE 
// This is the default value set in php.ini 
error_reporting(E_ALL^E_NOTICE); 

// Report all PHP errors (see changelog) 
error_reporting(E_ALL);