Login form redirects to welcome page even though password and username are wrong

My login page logs the user in even if the username and password are wrong . im not sure where i am going wrong here

<?php
$host_name = '';
$database = '';
$table = 'userpass';
$user_name = '';
$pass_word = '';
if (mysqli_error($connect)) {
die('<p>Failed to connect to MySQL: '.mysqli_error().'</p>');
}   else{
}
    session_start();
    $user = $_POST["user"];
    $pass = $_POST['pass'];//password
    $SESSION['user'] = $user;
    $SESSION['pass'] = $pass;
    $sqli  = "SELECT * FROM `userpass` where user = '$user' AND pass = '$pass'";
    $ask = $connect -> $sqli;
    $rowu = $ask -> mysqli_fetch_assoc;

        if ($user ==$rowu["user"] and $pass == $rowu["pass"]){
        echo 'Incorrect username or password';
        }else{
            header('location: Buttons.php'); //redirects user to the 
        }
        ?>

2 answers

  • answered 2018-04-14 15:22 angelsix

    Your logical check is back to front. If the username and password match you echo that it is incorrect. When it is incorrect you send them to buttons.php. Flip your logic or move the if/else code around

    if ($user ==$rowu["user"] and $pass == $rowu["pass"]){
        header('location: Buttons.php'); //redirects user to the 
    }else{
        echo 'Incorrect username or password';
    }
    

  • answered 2018-04-14 15:24 Umer Hayat

    From the code it seems like you dont have a database connection and also not execute not query properly. here you should do this:

    $con = mysqli_connect("localhost","root","","database password here or leave empty if dont have") or die("Connecting to MySQL failed")
    
    if (mysqli_error($con)) {
    die('<p>Failed to connect to MySQL: '.mysqli_error().'</p>');
    }   else{
    
        $user = $_POST["user"];
        $pass = $_POST['pass'];//password
    
        $sqli  = "SELECT * FROM `userpass` where user = '$user' AND pass = '$pass'";
        $ask = mysqli_query($con,$sqli); 
        $rowu = mysqli_fetch_assoc($ask );
    
        if ($user == $rowu["user"] and $pass == $rowu["pass"]){
               header('location: Buttons.php'); //redirects user to the 
        }else{
    
                 echo 'Incorrect username or password';
        }
    }