首頁  >  文章  >  資料庫  >  為什麼我的 PDO 例外會拋出空值並且不執行?

為什麼我的 PDO 例外會拋出空值並且不執行?

Susan Sarandon
Susan Sarandon原創
2024-10-28 12:06:01373瀏覽

Why Are My PDO Exceptions Throwing Null Values and Not Executing?

如何處理PDO 異常

問題:

使用PHP PDO 類別時,嘗試處理錯誤會導致報告空值且保持不活動的代碼。

代碼:

<code class="php">$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Exception handling is enabled

$id = 33;
$name = "Mario Bros.";
$url = "http://nintendo.com";
$country = "jp";

try {
    $sql = "UPDATE table_users SET name = :name, url = :url, country = :country WHERE user_id = :user_id";
    $statement = $connection->prepare($sql);
    $statement->bindParam(':user_id', trim($id), PDO::PARAM_INT);
    $statement->bindParam(':name', trim($name), PDO::PARAM_STR);
    $statement->bindParam(':url', trim($url), PDO::PARAM_STR);
    $statement->bindParam(':country', trim($country), PDO::PARAM_STR, 2);
    $status = $statement->execute();
} catch (PDOException $e) {
    echo $e->getMessage();
}</code>

解:

PDO 不會拋出異常自動排除異常。若要啟用異常處理,必須在嘗試執行任何查詢之前新增以下行:

<code class="php">$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);</code>

說明:

透過將PDO 錯誤模式設為ERRMODE_EXCEPTION,所有與PDO 相關的錯誤都會被當作異常拋出。然後可以使用 try/catch 區塊來處理這些異常並向使用者或日誌系統提供有意義的錯誤訊息。

以上是為什麼我的 PDO 例外會拋出空值並且不執行?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn