![](/img/trans.png)
[英]Insert into table using PHP and prepared statement getting response code 500
[英]Return MySQL Error Code and Custom Response using Prepared Statement PHP
我創建了一個 MySQL 數據庫並通過我的 Flutter 應用程序向它發送POST
請求,並使用Prepare Statement
來防止SQL Injection
。 我使用mysqli->error
以原始形式返回錯誤消息。 這是我的代碼。
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
include("connection.php");
$query=$connection->prepare("insert into parent_child_table(`parent_id`, `child_reg_number`) values(?,?)");
$query->bind_param("is",$parent_id,$reg_number);
$parent_id=$_POST["parent_id"];
$reg_number=$_POST["reg_number"];
if ($query->execute()) {
echo "1";
} else {
echo("$mysqli -> error");
}?>
有什么問題? / 出錯時的當前響應
每當數據庫拋出這樣的錯誤時,錯誤消息都是原始形式。
致命錯誤:未捕獲的 mysqli_sql_exception:無法添加或更新子行:外鍵約束失敗(
parent_child_table
, CONSTRAINTFK_child_reg_number
FOREIGN KEY (child_reg_number
) REFERENCESStudent
(reg_number
))在 /reg_number
:11
堆棧跟蹤:
0 /storage/ssd1/900/12273900/public_html/add_new_child.php(11): mysqli_stmt->execute()
1 {main}在第11行的/storage/ssd1/900/12273900/public_html/add_new_child.php 中拋出
我想做的事?
我想發送一個 MySQL 響應代碼或一個格式化的錯誤消息(我將根據錯誤代碼確定寫入)。 我怎樣才能做到這一點? 有沒有預構建方法? 我是 PHP 的新手。 我希望有人會建議我更好地解決我的問題。 謝謝
預期響應
首先,您必須了解不建議立即回顯錯誤消息。 通常,您的應用程序不會公開其內部工作,包括錯誤消息。
因此, echo $mysqli->error;
(這是該操作的正確語法echo
語句中既不使用引號也不使用大括號。)是不可接受的行為。
但是,檢查實際錯誤消息並創建自定義響應是一種很好的做法。 為此,您可以catch
拋出的異常。 並編寫代碼來處理您的情況。 在你的情況下,它會是這樣的
<?php
ini_set('display_errors', 0); // this will prevent PHP from displaying errors
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT ); // has to be moved in connection.php
include("connection.php");
$sql = "insert into parent_child_table(`parent_id`, `child_reg_number`) values(?,?)";
$query = $connection->prepare($sql);
$query->bind_param("is",$parent_id,$reg_number);
$parent_id=$_POST["parent_id"];
$reg_number=$_POST["reg_number"];
try {
$query->execute();
} catch (mysqli_sql_exception $e) {
if ($e->getCode() == /* the code for Foreign Key Violation */ ) {
echo "Wrong Reg # or the Reg # doesn't exist";
} elseif ($e->getCode() == /* the code for Primary key Violation */ ) {
echo "Child Already Registered";
} else {
throw $e; // the most important part - ALL OTHER errors won't go unnoticed
}
}
所以你的腳本有三個主要變化
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.