0
$count = mysqli_num_rows($result);  
          
if($count == 1){  
    echo "<h1><center> Login successful </center></h1>";  
} else{  
    echo "<script>alert('login failed! invalid username or password');</script>";
    header("Location: index.php")  ;
}     

I want to display the alert message as login failed and if the user press ok then it should again go back to the login page.I tried above code but ,that doesn't work. the browser moves to the login page without showing the alert message. Is there any alternative ways for this?

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • 2
    The response should be a redirect *or* content to render, not both. The redirect header tells the browser to redirect the user, so the response is ignored. Displaying the message on the login page itself is probably the best approach. – David Dec 29 '20 at 15:07
  • [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – RiggsFolly Dec 29 '20 at 15:10

1 Answers1

0

echo is working well, but the code is sync in php right there. That is why header runing with echo, but header redirecting you to index.php and echo was seen for a while.

You can store your message to a SESSION and show it on index.php if the msg is exists in SESSION:

.
.
else{
session_start();
$_SESSION['msg'] = 'Login failed! invalid username or password';
header("Location: index.php");

index.php:

session_start();
if(isset($_SESSION['msg'])){
 echo $_SESSION['msg'];
 unset($_SESSION['msg'];
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Morani
  • 446
  • 5
  • 15
  • 1
    That's my recommendation as well... But don't forget to unset the session message. Otherwise it will be showed everytime you load index.php :) – Gowire Dec 29 '20 at 15:12