gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:08:46 25 4
gpt4 key购买 nike

我创建了一个 MySQL 数据库,并通过 Flutter 应用程序向其发送 POST 请求,并使用 Prepare Statement 来防止 SQL 注入(inject)。我使用 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");
}?>

有什么问题吗?/出现错误时的当前响应

每当数据库抛出这样的错误时,错误消息都是原始形式。

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
Stack trace:
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

我想做什么?
我想发送一个 MySQL 响应代码或一个格式化的错误消息(我将根据错误代码确定写入)。我怎样才能做到这一点?有没有预构建方法?我是 PHP 新手。我希望有人能建议我更好地解决我的问题。谢谢
预期响应

  • child 已注册(以防主键违规。我正在使用复合主键)
  • Reg # 错误或 Reg # 不存在(如果发生外键违规)

最佳答案

首先,您必须了解不建议立即回显错误消息。通常,您的应用程序不会暴露其内部运作,包括错误消息。

因此,echo $mysqli->error;(这是该操作的正确语法。echo 语句中不使用引号或大括号。)是 Not Acceptable 行为。

但是,检查实际错误消息并创建自定义响应是一个很好的做法。要实现这一点,您可以捕获抛出的异常。并编写代码来处理您的情况。在你的情况下,它会是这样的

<?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 来记录错误以便查看它们。

关于php - 使用准备好的语句 PHP 返回 MySQL 错误代码和自定义响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59852645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com