简体   繁体   English

使用准备好的语句 PHP 返回 MySQL 错误代码和自定义响应

[英]Return MySQL Error Code and Custom Response using Prepared Statement PHP

I have created a MySQL database and sending POST requests to it through my Flutter application and using Prepare Statement to prevent SQL Injection .我创建了一个 MySQL 数据库并通过我的 Flutter 应用程序向它发送POST请求,并使用Prepare Statement来防止SQL Injection I am returning the error messages in a raw form using mysqli->error .我使用mysqli->error以原始形式返回错误消息。 Here is my code.这是我的代码。

<?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");
}?>

What's the problem?有什么问题? / Current Response in case of error / 出错时的当前响应

The error message is in the raw form whenever the database throws an error like this.每当数据库抛出这样的错误时,错误消息都是原始形式。

Fatal error : Uncaught mysqli_sql_exception: Cannot add or update a child row: a foreign key constraint fails ( parent_child_table , CONSTRAINT FK_child_reg_number FOREIGN KEY ( child_reg_number ) REFERENCES Student ( reg_number )) in /storage/ssd1/900/12273900/public_html/add_new_child.php:11致命错误:未捕获的 mysqli_sql_exception:无法添加或更新子行:外键约束失败( parent_child_table , CONSTRAINT FK_child_reg_number FOREIGN KEY ( child_reg_number ) REFERENCES Student ( reg_number ))在 / reg_number :11
Stack trace:堆栈跟踪:
0 /storage/ssd1/900/12273900/public_html/add_new_child.php(11): mysqli_stmt->execute() 0 /storage/ssd1/900/12273900/public_html/add_new_child.php(11): mysqli_stmt->execute()
1 {main}thrown in /storage/ssd1/900/12273900/public_html/add_new_child.php on line 11 1 {main}在第11行的/storage/ssd1/900/12273900/public_html/add_new_child.php 中抛出

What I want to do?我想做的事?
I want to send a MySQL response code or a formatted error message (which I'll be writing for sure based on the error code).我想发送一个 MySQL 响应代码或一个格式化的错误消息(我将根据错误代码确定写入)。 How can I achieve that?我怎样才能做到这一点? Is there any pre-build method?有没有预构建方法? I am a newbie to PHP.我是 PHP 的新手。 I hope someone would suggest me a better solution to my problem.我希望有人会建议我更好地解决我的问题。 Thanks谢谢
Expected Response预期响应

  • Child Already Registered (in case of Primary key violation. I am using composite Primary Key)孩子已经注册(在主键违规的情况下。我使用复合主键)
  • Wrong Reg # or the Reg # doesn't exist (in case of Foreign Key Violation)错误的 Reg # 或 Reg # 不存在(在外键违规的情况下)

First of all you have to understand that echoing error messages right away is not recommended .首先,您必须了解不建议立即回显错误消息。 As a rule, your application do not expose its internal workings, error messages included.通常,您的应用程序不会公开其内部工作,包括错误消息。

Therefore, echo $mysqli->error;因此, echo $mysqli->error; (which is the correct syntax for the operation. Neither quotes nor braces are used with echo statements.) is not acceptable behavior. (这是该操作的正确语法echo语句中既不使用引号也不使用大括号。)是不可接受的行为。

However, checking the actual error message and creating a custom response is a good practice.但是,检查实际错误消息并创建自定义响应是一种很好的做法。 To achieve that you can catch the exception thrown.为此,您可以catch抛出的异常。 And write a code to handle your situation.并编写代码来处理您的情况。 In your case it would be like this在你的情况下,它会是这样的

<?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
    }
}

So there are three main changes to your script所以你的脚本有三个主要变化

  • exposing errors turned off (has to be done on a live site)关闭暴露错误(必须在实时站点上完成)
  • try catch added in order to catch the error try catch 添加以捕获错误
  • an else statement added to the error handler so you will be informed of all other errors that may occur.添加到错误处理程序的 else 语句,因此您将被告知可能发生的所有其他错误。 You may want to configure PHP to log errors in order to see them.您可能希望配置 PHP 来记录错误以便查看它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM