ncirl.eva ncirl.eva - 3 years ago 226
PHP Question

Any unregistered user can login (PHP)

I'm working on a login for my website, when I login it doesn't check to see if the user already exists in the database. It allows anyone to sign in even if you haven't registered.

This is the code for the login.


//database details
$servername = "localhost";
$username = "myname";
$password = "******";
$dbname = "mydb";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);


$email = $_POST ['email'];
$password =$_POST ['password'];

$query = "SELECT * FROM Users WHERE Email='$email' AND Password='$password'";

$result = mysqli_query($conn, $query);


header('Location: profile.php');


header('Location: failedlogin.html');



Answer Source

Your code never checks if the user account exists in the database. It only checks if the query was executed without error. This should work(untested):

$query = "SELECT * FROM Users WHERE Email='$email' AND Password='$password' LIMIT 1";
if($result = mysqli_query($conn, $query)){

    if(mysqli_num_rows($result) > 0){

        //user account exists
        $member = mysqli_fetch_array($result, MYSQLI_ASSOC);
        $email = $member["Email"];

    } else {

        //user account does not exist


} else {

    echo "Error executing database query.";

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download