-3

I created a login page connected to a database. However, in order to give a message, I used alert. Now, upon loading the page i immediately get an 'Invalid Username' alert. I want the alert to appear only after the Login Button is pressed.

Also, upon pressing the Login Button, the page goes blank and then the alert appears and then on clicking OK, the html page loads. How do I get the alert on the same page.

The file: login.php

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <form id="Form"  method="post">
        <input id="Username" name="Username" type="text" placeholder="Username"><br>
        <input id="Password" name="Password" type="password" placeholder="Password""><br>
        <button id="Button" name="Login" type="submit">Login</button><br>
    </form>
</body>
</html>
<?php
$conn=mysqli_connect ('localhost','root','','test');
$uname=$_POST['Username'];
$passw=$_POST['Password'];
$check=mysqli_query($conn,"select Username from members where Username='$uname' and Password='$passw'");
if(mysqli_num_rows($check)==1)
{
    echo "<script>alert('Login Successful');</script>";
}
else
{
    $check=mysqli_query($conn,"select Username from members where Username='$uname'");
    if(mysqli_num_rows($check)==1)
    {
        echo "<script>alert('Invalid Password');</script>";
    }
    else
    {
        echo "<script>alert('Invalid Username');</script>";
    }
}
?>
Jainam Doshi
  • 47
  • 10

3 Answers3

2

It might be harsh for such a seemingly small thing, but the solution here is to use AJAX. Assuming you dont know AJAX, I'd recommend you to learn it, after using this solution.

You also need jQuery for this.

First off, you need to include put the PHP part in another file, lets say: login.php:

<?php


$conn=mysqli_connect ('localhost','root','','test');
$uname=$_POST['Username'];
$passw=$_POST['Password'];
$check=mysqli_query($conn,"select Username from members where Username='$uname' and Password='$passw'");
if(mysqli_num_rows($check)==1)
{
    echo json_encode(array("msg"=>"Login Successful"));
}
else
{
    $check=mysqli_query($conn,"select Username from members where Username='$uname'");
    if(mysqli_num_rows($check)==1)
    {
        echo json_encode(array("msg"=>"Invalid Password"));
    }
    else
    {
        echo json_encode(array("msg"=>"Invalid Username"));
    }
}
?>

Next you'll make a JS file:

$('#form').submit(function(event) {
   $.ajax({
     method: "POST",
     url: "login.php",
     data: $("#form").serialize()
   })
   .done(function( data ) {
     alert(data['msg']);
   });
}

Sorry if I missed a part but there's a lot to do and learn for you to understand this at all.

Loko
  • 6,539
  • 14
  • 50
  • 78
1

Because the PHP is server side code, you are loading the value mysqli_num_rows($check)==1, before your page has been presented to the user, so therefore, no credentials have been entered. If you want to perform an action on the button click, you need to use client side code, such as javascript. Here is a simple solution I have created for you.

This is your "index.php" page where the login form is:

<html>
    <head>
        <title>Please login</title>
    </head>
    <body>
        <input id="Username" name="Username" type="text" placeholder="Username"><br>
        <input id="Password" name="Password" type="password" placeholder="Password""><br>
        <button id="Button" name="Login" onclick="checkCredentials();">Login</button><br>
        <script type="text/javascript">
            function checkCredentials(){
                var username = document.getElementById('Username').value; //Get the text from username field
                var password = document.getElementById('Password').value; //Get the text from password field

                var request = new XMLHttpRequest();

                request.onreadystatechange = function() {
                    if (this.readyState == 4 && this.status == 200) {
                        //Make your alert
                        var response = JSON.parse(this.responseText);

                        if(response.status == 200){
                            alert(response.alert);
                            /**
                            * Here, put whatever else you want to do when login is successful!
                            * My best guess is that you'd redirect the user to a page where a new
                            * PHP session is started. If you need help with this, please ask :)
                            **/
                        } else {
                            //Login has failed, display the response message
                            alert(response.alert);
                        }
                    }
                };

                //We're sending the password in plaintext over a GET request. I've done this for simplicity.
                //You should NOT send the password in plaintext on the production system. Doing this is insecure. Hash it before you send it.
                request.open("GET", "login.php?username="+ username +"password=" + password, true);
                request.send();
            }
        </script>
    </body>
</html>

Now that you have your login page created, you can make the login.php page, which is a backend script for checking login details.

<?php
    $loginStatus = array("status" => 403, "alert" => "forbidden");

    $conn=mysqli_connect ('localhost','root','','test');
    $uname=$_GET['username'];
    $passw=$_GET['password'];

    //Don't use this line in production, you should use a prepared statement instead
    $check=mysqli_query($conn,"select Username from members where Username='$uname' and Password='$passw'");

    if(mysqli_num_rows($check)==1)
    {
        $loginStatus = array("status" => 200, "alert" => "Login Successful!");
    }
    else
    {
        $check=mysqli_query($conn,"select Username from members where username='$uname'");
        if(mysqli_num_rows($check)==1)
        {
            $loginStatus = array("status" => 403, "alert" => "Invalid Password!");
        }
        else
        {
            $loginStatus = array("status" => 403, "alert" => "Invalid Username!");
        }
    }

    echo json_encode($loginStatus);
?>

The code explained:

On your "index.php" there is a peice of javascript which makes a request (in the background) to your auth page (login.php). Login.php returns a JSON array containing information on the login, if it was successful or not, as well as a message which gets displayed in a javascript alert();

What's a prepared statement?

A prepared statement is a database query that works with parameters rather than the values directly. This is much more secure and will help prevent SQL injection to your database. See this question for more info how to do it (stack overflow link)

Harvey Fletcher
  • 1,167
  • 1
  • 9
  • 22
-4

You only want that PHP to run if the form is submitted. So wrap all your PHP code in an if condition.

if (!empty($_POST)) { .... rest of php code here ... }
dmikester1
  • 1,374
  • 11
  • 55
  • 113
  • Doesn't answer the question – GordonM Oct 04 '18 at 13:26
  • Doesn't work. Gave Warning: Use of undefined constant post - assumed 'post' (this will throw an Error in a future version of PHP) in C:\xampp\htdocs\login.php on line 15. – Jainam Doshi Oct 04 '18 at 13:40
  • I'm not sure how this doesn't answer the question. Here is an example of exactly what Jainam is trying to do: https://stackoverflow.com/a/5826877/571723 – dmikester1 Oct 04 '18 at 14:08
  • Create the same script as him and add this piece of code to it. Will that get the alert on the same page without a refresh first? – Loko Oct 05 '18 at 09:59