Emily Bond
Emily Bond

Reputation: 21

How to check if user exists in database php

For some reason when i enter an existing username and password into my form the output is ALWAYS 'user does not exist', how could i change it so that it will take the user to the welcome.php page if the user exists and 'user does not exist' if the user doesn't. The database is called TEST and the table is called USERS.

<?php 
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "test";

// Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $user = $conn->real_escape_string($_POST['username']);
    $pass = $conn->real_escape_string($_POST['password']);

    $query = "SELECT `username` AND `password` FROM `users` WHERE `username` = '$user' AND `password` = '$pass'";

    $result = $conn->query($query);
    if($result->num_rows < 0) {

       header('Location:welcome.php');
       die();
    }
    else $message = 'User does not exist';
?>

    <!DOCTYPE html>
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <title>Test</title>
        </head>

        <body>
            <form method="post" action="testing.php" enctype="multipart/form-data">
                <?php if(isset($message)) : ?>
                    <div class="error"><?php echo $message; ?></div>
                <?php endif; ?>

                Username: <input type="text" value="" name="username" /><br /><br />
                Password: <input type="text" value="" name="password" /><br /><br />
                <input type="submit" name="submit" value="Log In"/><br /><br />
                <a href="register.php">Register</a>
            </form>
        </body>
    </html>

Upvotes: 2

Views: 3605

Answers (1)

Marc B
Marc B

Reputation: 360612

num_rows() will NEVER return less-than-zero. It'll return a boolean false on failure, or 0, or a positive integer. If the user doesn't exist or the wrong password was given, then zero rows would be returned:

if ($result->num_rows == 0) {
     die("Wrong user/pass");
} else if ($result->num_rows > 1) {
     die("Duplicate user accounts!");
} else {
     die("Welcome");
}

Upvotes: 2

Related Questions