简体   繁体   中英

PDO Login System With Username and Email

I'm trying to figure out how to use PDO to login to my site give the user the option of either their email address or username once they are logged in, I checked some of the other answers but it doesn't seem to work for me.

Here is the code

<?php

if(isset($_POST['username']) || isset($_POST['password'])){
    if(!$_POST['username'] || !$_POST['password']){
        $error = "Please Enter your Username and Password";
    }

So the issue stems from below, I tried adding an OR on the $query as I saw it from one of the other posts on here but doing that allows the user to login through email but not with username, if I remove "OR user_email" they can login through username but not E-Mail.

if(!$error){
            //No errors - lets get the users account
            $query = "SELECT * FROM users WHERE user_name OR user_email = :username";

            $result = $DBH->prepare($query);
            $result->bindParam(':username', $_POST['username']);
            $result->execute();

            $row = $result->fetch(PDO::FETCH_ASSOC);

            if($row){
                //User found - let’s check the password
                if(password_verify($_POST['password'], $row['user_password'])){
                    $_SESSION['loggedin'] = true;
                    $_SESSION['userData'] = $row;

                echo "<script> window.location.assign('index.php?p=viewprofile'); </script>";
            }else{
                $error = "Username/Password Incorrect";
            }

        }else{
            $error = "Username/Password Incorrect";
        }

    }
}

?>

You SQL query is wrong:

$query = "SELECT * FROM users WHERE user_name = :username OR user_email = :username";

You forgot to compare the column user_name with the user input

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