简体   繁体   中英

Echo Success Message Once PHP

I am trying to create a "flash" success message which pops up when the user successfully changes their password. But, It doesn't work how I would like it to.

The basic idea is, when people enter their new password (and it passes to the database), it will echo to the page "Successfully updated password". But it will only echo once (when the user refreshes, the echoed message will disappear and not display again until they submit a new password).

I have tried searching around, but I can't seem to find any scripts that will actually work how I would like them to.

This is my PHP function, currently:

function updatePassword($conn, $newpwd, $username){
    $newpwd = hash('md5', $newpwd);
    mysqli_query($conn, "UPDATE users SET password = '$newpwd' WHERE username = '$username'");
}

Cheers.

I created something myself recently, the code could probably be better though, but it works.

function flash_message($message, $type = 'success') {
  switch($type) {
    case 'success':
      $class = "success";
      break;
    case 'info':
      $class = "info";
      break;
    case 'error':
      $class = "error";
      break;
  }

  $_SESSION['flash_message'] = "<p class='flash_message ".$class."'>".$message."</p>";
}

function show_flash_message() {
  if (isset($_SESSION['flash_message'])) {
    $message = $_SESSION['flash_message'];
    unset($_SESSION['flash_message']);
    return $message;
  }
  return NULL;
}

You use show_flash_message() on the page where you want to display it. If there is no message, it wont display anything.

You'd call it by doing this:

function updatePassword($conn, $newpwd, $username){
  $newpwd = hash('md5', $newpwd);
  mysqli_query($conn, "UPDATE users SET password = '$newpwd' WHERE username = '$username'");
 flash_message('Successfully changed your password');
}

The different classes are for if you want to change the display of the message. (Wrong username/password is an error, e-mail been sent can be info/success etc.)

Let me explain you pseudo logic.

Steps:

1) When your password change is done successfully, assign success message to a session variable.

$_SESSION['message'] = 'Password changed successfully.';

2) On the redirected success page, echo this.

if (isset($_SESSION['message'])) {
 echo $_SESSION['message'];
 unset($_SESSION['message']);
}

Also, unset() it, so that, it will not be shown other time again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM