簡體   English   中英

使用准備好的語句 PHP 返回 MySQL 錯誤代碼和自定義響應

[英]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 , CONSTRAINT FK_child_reg_number FOREIGN KEY ( child_reg_number ) REFERENCES Student ( 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 的新手。 我希望有人會建議我更好地解決我的問題。 謝謝
預期響應

  • 孩子已經注冊(在主鍵違規的情況下。我使用復合主鍵)
  • 錯誤的 Reg # 或 Reg # 不存在(在外鍵違規的情況下)

首先,您必須了解不建議立即回顯錯誤消息。 通常,您的應用程序不會公開其內部工作,包括錯誤消息。

因此, 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
    }
}

所以你的腳本有三個主要變化

  • 關閉暴露錯誤(必須在實時站點上完成)
  • try catch 添加以捕獲錯誤
  • 添加到錯誤處理程序的 else 語句,因此您將被告知可能發生的所有其他錯誤。 您可能希望配置 PHP 來記錄錯誤以便查看它們。

暫無
暫無

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

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