php - 如何使用 PHP 在重定向页面上获取警报通知?
问题描述
我创建了一个 HTML 表单来更新我的帖子。所以我使用 header() 函数将页面重定向到更新页面,以便我可以看到更改。但我想在重定向页面上回显一条消息。我已经尝试过此代码,但这仅适用于同一页面,而不适用于重定向页面。
<?php
$query_2 = "UPDATE posts SET post_image = '$post_image' WHERE post_id = $post_id ";
$query_2 .= "AND LENGTH('$post_image') > 0 AND post_image <> '$post_image' ";
$editPostImg = mysqli_query($connection, $query_2);
if (!$editPostImg) {
die("Something went wrong.<br>" . mysqli_error($connection));
}
header("Location: posts.php?source=edit_posts&p_id=$post_id");
echo "<p class='alert alert-success'><strong>Post Updated!</strong> <a href='../post.php?p_id=$post_id' class='alert-link' target='blank'>View Post</a><a href='' class='close' data-dismiss='alert'>x</a></p>";
}
?>
解决方案
在以下代码行之后:
header("Location: posts.php?source=edit_posts&p_id=$post_id");
用户将被重定向到新页面,并且不会看到在 header 指令之后执行的代码。要显示消息,您必须将消息作为 GET 或 POST 参数提交。而第一个选项将更容易。
正如@Dharman 提到的,您的代码对SQL 注入非常开放,应该使用参数化的准备好的语句。您可以使用PDO或MySQLi。我用 PDO 构建了一个解决方案,但取决于你。
因此,您可以按如下方式调整脚本:
<?php
try{
//Create new PDO Object
$conn = new PDO("mysql:host=HOST;port=PORT;dbname=DBNAME", USERNAME, PASSWORD);
//Define query
$query = $this->conn->prepare("UPDATE posts SET post_image = :postimage WHERE
post_id = :postid AND LENGTH(post_image) > 0 AND post_image <> :postimage");
$query->bindValue("postimage", $post_image);
$query->bindValue("postid", $post_id);
$query->execute();
//Redirect user and add success message as GET parameter
header("Location: posts.php?source=edit_posts&p_id=$post_id&update=success");
//Make sure script is terminated
exit();
} catch(Exception $ex){
//Log error
error_log($ex->getMessage());
//Show user custom error message
echo "Something went wrong";
//Make sure script is terminated
exit();
}
?>
然后,您可以在目标页面 (posts.php) 上插入如下代码片段:
<?php
if(isset($_GET['update']) && $_GET['update'] == "success"){
echo "<p class='alert alert-success'><strong>Post Updated!</strong> <a href='../post.php?p_id=$post_id' class='alert-link' target='blank'>View Post</a><a href='' class='close' data-dismiss='alert'>x</a></p>";
}
?>
推荐阅读
- python - 文件对比优化
- caching - Mule Cache - 内存中的集群 - 反序列化问题
- git - .nyc_output 是否应该包含在 .gitignore 中?
- python - 我可以将 PIL 图像数组保存到 Qt 中吗?
- android - 为什么 SafetyNet Attestation 停止工作?
- spring - Spring Security 登录 Twitter 返回 403 Forbidden
- r - 根据 ggplot2 标准功能创建 ggplot2 函数并将参数指定为数据中的变量
- vsto - VSTO Outlook 如何在定期会议中的 AppointmentItems 链中获取上一个 AppointmentItem
- python - 带有数据框的列表的交叉连接(笛卡尔积)
- python - 禁用鼠标单击和更改指针图标