簡體   English   中英

為什么execute()出錯時不返回true?

[英]Why doesn't execute() return true on error?

請看一下我的代碼:

try {
    // db connection here
    $stm = $dbh->prepare("INSERT INTO mytable(id,token) values(NULL,$token)")->execute(); 

} catch(PDOException $e){
    if ( $stm ){
        echo 'inserting fails';
    } else {
        echo 'something else is wrong';
    }
}

-- `token` column is unique

電流輸出:

  • 該行已成功插入。
  • 它會同時為{duplicate entry}和{SQL語法}打印something else is wrong

預期產出:

  • 該行已成功插入。
  • 它顯示{重復條目}的inserting fails錯誤
  • 它為{SQL語法}打印something else is wrong

好的,如果我像下面那樣編寫我的代碼(不帶鏈接) ,則會發生預期的輸出:

$stm = $dbh->prepare("INSERT INTO mytable(id,token) values(NULL,$token)");
$stm->execute(); 

我想知道,什么時候可以鏈接那些PDO語句?

閱讀PDO文檔http://php.net/manual/zh/book.pdo.php並查看返回值。 您只能在返回對象(例如語句或結果集)時進行鏈接。

Execute( http://php.net/manual/en/pdostatement.execute.php )返回一個布爾值,而不是對象,因此我們知道它不能被鏈接。 Prepare( http://php.net/manual/en/pdo.prepare.php )返回一個語句對象,因此我們可以使用return語句鏈接另一個方法調用。

這樣想:

$stmt = $dbh->prepare("..sql..");
$bool = $stmt->execute();

這可以轉換為:

$bool = $dbh->prepare("..sql..")->execute();

因為從-> prepare()返回的是$ stmt。

只能在prepareexecute方法中引發異常。 其中任何一種都將在$stm =之前發生。 換句話說, 如果將引發異常,則始終會跳過對$stm的賦值,這意味着該變量在catch塊中根本不存在。 因此,它只能求值為false ,並且實際上會發出有關未定義的通知。

無法獲得預期的輸出的原因是,無論PDOException獲得PDOException ,編寫方式都不會使$stm為真。 如果prepareexecute失敗,則$stm將是未定義的。

我原本以為您可以通過從catch塊中刪除execute成功檢查來解決此問題,但我誤會了。 在仍然鏈接方法的同時,您無法獲得預期的輸出。

try {
   $success = $dbh->prepare("INSERT INTO mytable(id,token) values(NULL,$token)")->execute();
   if (!$success) {
       // This can never be reached. If your have set PDO::ERRMODE_EXCEPTION, then either
       // the query is successful and $success === true, or the prepare or the execute
       // failed, and an exception will be thrown 
       echo 'inserting fails';
   }
} catch(PDOException $e){
    echo 'something else is wrong';
}

僅作記錄。 為了回答這個家伙試圖問的問題。

關於PDO的文章中的代碼(還修復了SQL注入):

try {
    $dbh->prepare("INSERT INTO mytable(token) values(?)")->execute([$token]);
} catch (PDOException $e) {
    if ($e->getCode() == 1062) {
        // insert failed due to duplicate key error
        echo "duplicate token";
    } else {
        // insert failed due to any other error
        throw $e;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM