如何使用 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>";

}    

?>


POPMUISE
浏览 88回答 1
1回答

蝴蝶不菲

在以下代码行之后:header("Location: posts.php?source=edit_posts&p_id=$post_id");用户将被重定向到新页面,并且不会看到在 header 指令之后执行的代码。要显示消息,您必须将消息作为 GET 或 POST 参数提交。而第一个选项将更容易。您的代码对SQL 注入是完全开放的,应该使用参数化的准备语句。您可以使用PDO或MySQLi。我使用 PDO 构建解决方案,但取决于您。因此,您可以按如下方式调整脚本:<?phptry{    //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>";}?>
打开App,查看更多内容
随时随地看视频慕课网APP