简体   繁体   中英

Getting a result from a query and returning a value? PHP & MySQLi

When I click submit, the input validation works, but even when I type in the username and password correctly that is stored in my database exactly as I'm entering it, with consideration of the hash, but all I get is the error message telling me the combination is incorrect.

This is my login script:

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

if (isset($_POST['submit']) === true) {

$login = login($username, $password);

if (empty($username) === true || empty($password) === true) {
    $errors[] = "Please fill in all fields";
} elseif ($login === false) {
    $errors[] = "That username and password combination is incorrect";
} else {
    $_SESSION['login'] = $login;
    echo 'Logged in';
}
}

And here are the functions:

function login($username, $password) {
    global $conn;
    $query = "SELECT userId FROM users where userName = '$username' AND userPass = '$password'";
    $result = mysqli_query($conn, $query);
    $row_count = mysqli_num_rows($result);
    if ($row_count >= 1) {
        return $query['userId'];
    } else {
        return false;
    }
}

enter image description here

The first thing I would suggest you try is to manually compare the md5 hashed password to what's strutted in the table. If you're absolutely sure they're equal, run a manual query using that value from toad or phpmyadmin and see if you get a result. If not the problem could be in the query. If you get a result check your mysqli_num_rows function and instead of returning the user id echo it in your test environment.

What else have you done to debug?

You can simplify it down to this, however I would not recommend taking user input without XSS scrubbing it. Especially for a table such as login.

function login($username, $password) {
    global $conn;
    $password = md5($password);
    $query = "SELECT userId FROM users where userName = '$username' AND userPass = '$password' LIMIT 1";
    $result = mysqli_query($conn, $query);
    $row_count = mysqli_num_rows($result);
    if ($row_count >= 1) {
        return $query['userId'];
    } else {
        return false;
    }
}

I guess your code needs some fixes since your checking the parameters if they are empty after you query it to the database, getting the userID before checking if his password is correct.. and so on..

But first, after the line

    $query = "SELECT userId FROM users where userName = '$username' AND      userPass = '$password'";

why don't u put

die($query);

run the page, copy the result, paste it into phpMyAdmin query box, and see if the result fits your needs.

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