[英]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.