我有這樣的代碼,故意使查詢錯誤:delete_test.php。<?php.....$id = 1;$sql = "xSELECT * FROM tbl_1 WHERE 1 AND id =?"; // Adding and an x to make this error$stmt = $mysqli->stmt_init();if(!$stmt->prepare($sql)){ // Line 56 echo "There is something wrong #1"; exit();}else{ $stmt->bind_param("i", $id); if(!$stmt->execute()){ echo "There is something wrong #2"; exit(); } .....}.....?>當我運行 delete_test.php 時出現此錯誤:Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'xSELECT * FROM tbl_1 WHERE 1 AND id =?' at line 1 in C:\xampp\htdocs\delete_test.php:56 Stack trace: #0 C:\xampp\htdocs\delete_test.php(56): mysqli_stmt->prepare('xSELECT * FROM ...') #1 {main} thrown in C:\xampp\htdocs\delete_test.php on line 56而不是打印這個:There is something wrong #1為什么 php 忽略echo "There is something wrong #1";了該行的行錯誤?以及如何echo "There is something wrong #1";在該行的行錯誤處打印?
1 回答

呼啦一陣風
TA貢獻1802條經驗 獲得超6個贊
你不能用 if 語句捕獲異常!
絕對沒有理由將每個 mysqli 函數調用包裝在一條if語句中,即使您要關閉 mysqli 錯誤報告。Mysqli 可以觸發異常,就像您收到的異常一樣,它告訴您的不僅僅是“有問題#1”。
你有 3 行代碼,你把它變成了 12 行代碼,但你仍然沒有包裝stmt_init()或bind_param()在if聲明中。只需堅持簡單的三行準備好的語句。
$stmt = $mysqli->prepare("xSELECT * FROM tbl_1 WHERE 1 AND id =?");
$stmt->bind_param('s', $id);
$stmt->execute();
PHP 具有內置的錯誤處理程序,因此如果發生錯誤,它可以將錯誤顯示給最終用戶或將錯誤記錄在服務器上的文件中。后者是優選的。如果您想使用自己的錯誤處理程序,那么您可以將所有 PHP 代碼包裝在一個 try-catch 塊中,并使用自定義記錄器處理所有異常和錯誤。不要在 try-catch 中包裝每個 mysqli 調用!
- 1 回答
- 0 關注
- 116 瀏覽
添加回答
舉報
0/150
提交
取消