簡體   English   中英

重定向到另一個頁面並在php中顯示消息

[英]Redirect to another page and show message in php

我正在嘗試提交表單后,從registration.php重定向到index.php並在其中顯示消息。 結構是這樣的:

registration.php

class Registration 
{ 

...

public $messages = array();

...

if ($stmt->execute([$uid_new, $email_new, $pwd_1_hash])) {  
    $this->messages[] = 'success';
    header('Location index.php');
}

messages.php

if ($registration->messages) {
    foreach($registration->messages as $message) {
        echo "$message <br>";
    }

index.php

<?php include 'messages.php'; ?>

但是,重定向后,消息未顯示。 這里哪里有問題? 謝謝。

您正在使用可在index.php頁面上重定向的標頭,因此如果要使用相同的消息,則必須完成類對象范圍,必須在會話中存儲消息並在打印后銷毀會話。

if ($stmt->execute([$uid_new, $email_new, $pwd_1_hash])) {  
    $this->messages[] = 'success';
     session_start();
     $_SESSION['errors'] = $this->messages;
    header('Location: index.php');
}

And on index page use 
$registration = $_SESSION['errors'];
if ($registration->messages) {
    foreach($registration->messages as $message) {
        echo "$message <br>";
    }

未設置($ _SESSION ['errors'])

由於要在Registration類中進行重定向,因此會丟失所有未保存在持久性存儲(例如會話)中的數據,包括$ messages數組。 我認為您的代碼結構不正確,無法按需要處理重定向。 我建議在重定向之前設置一個會話變量來保存您的消息。 另外,我不知道您的errors.php文件中包含什么,但是不應該是messages.php嗎?

<?php

// Registration.php
class Registration
{
    public function save()
    {
        if ($stmt->execute()) {
            $_SESSION['messages'][] = 'success';
        }
    }
}

// messages.php
if (!empty($_SESSION['messages'])) {
    foreach($_SESSION['messages'] as $message) {
        echo "$message <br>";
    }
}

// index.php
include 'messages.php';

另外,我並不真正認可這種代碼風格,在當今的PHP生態系統中,它有點hacker。 如果您是我,我將考慮使用框架。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM