首页 > 解决方案 > 如何使用 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>";
}    
?>

标签: phphtml

解决方案


在以下代码行之后:

header("Location: posts.php?source=edit_posts&p_id=$post_id");

用户将被重定向到新页面,并且不会看到在 header 指令之后执行的代码。要显示消息,您必须将消息作为 GET 或 POST 参数提交。而第一个选项将更容易。

正如@Dharman 提到的,您的代码对SQL 注入非常开放,应该使用参数化的准备好的语句。您可以使用PDOMySQLi。我用 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>";
}

?>



推荐阅读