0

Okay, so here's my code

<?php
$cn = new mysqli ("localhost", "root", "root", "dbsam");
$username = isset ($_POST['username']) ? $_POST['username']:"";
$password = isset ($_POST['password']) ? $_POST['password']:"";
$sql = "SELECT * FROM tbluser WHERE username=? AND password=?";
$upass = hash("SHA256", $password);
$qry = $cn->prepare($sql);
$qry->bind_param("ss", $username, $upass);
$qry->execute();
$qry->fetch();
if ($qry->num_rows()==1) {
    echo "Logged in!";
}
else {
    echo "<script>alert('Account did not match the database records!')</script>>";
    header ("location: login.php");
}
?>

If the username and password did not match, an alert box will appear. So the problem is that it doesn't appear anymore it only executes the header that I put under it but if I remove the header, the alert dialog box will appear. I want the alert box to appear then the user will be redirected to the log-in page after that. How can I do that? Great Thanks!

3
  • You'll need to use Javascript to do the redirect if you want the alert to appear, see something like this: stackoverflow.com/a/506004/7956549 Commented Jul 6, 2017 at 14:40
  • Might be better to show a content block (div) for a few seconds, such as a flash message, then after a few seconds redirect the user. Commented Jul 6, 2017 at 14:40
  • 1
    It may be best to set this script as a separate ajax call and return a well-structured JSON response. Then handle the response in JS. Commented Jul 6, 2017 at 14:41

2 Answers 2

2

You can set document.location, inside a script tag. Something like

<script> document.location = 'login.php'; </script>

Beside the answer to the direct question, I feel like you will need a timeout, or something more complex to handle the time spent reading the alert.

Sign up to request clarification or add additional context in comments.

Comments

1

It is impossible in such way, PHP will redirect and never let the browwer executing the JS.

You can add a variable in the url then make your test in login.php then show the alert

    .....
    else {
        header ("location: login.php?mode=login_failed");
    }

    //login.php
    $mode = filter_input(INPUT_GET, 'mode');
    if ($mode === 'login_failed') {
         echo '<script>.......';
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.