问题描述:

I'm currently working on an HTML page that requires users to login before they can access its content. The user must input a username and password into a form on an HTML page and when they hit the submit button, the information is to be checked by PHP with an SQL database of usernames and passwords. If the info the user inputted is corrected, then they will be allowed to access the rest of the "website", otherwise they get an error. However, with my current code, even if the user enters in the correct credentials, they are not granted access to the page.

Here is my current code:

if($_POST['submit']) {

$sql = "SELECT * FROM log WHERE user='username' AND pass='password'"; //'user' and 'pass' being the SQL table values, and 'username' and 'password' being the HTML form ids

$result = $conn->query($sql);

if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {

header("Location: home.html");

exit();

}

}

else {

echo "Login information is incorrect.";

}

}

If anyone could offer me any tips or help on how to fix my problem, it would be greatly appreciated.

网友答案:

You are not passing in the inputs to the SQL query, but instead are passing in the actual strings username and password (so unless the valid credentials are username and password - the test will fail). Instead, you should join it with the . operator like so:

if($_POST['submit']) {
    $sql = "SELECT * FROM log WHERE user='" . $_POST['username'] . "' AND pass='" . $_POST['password'] . "'"; //'user' and 'pass' being the SQL table values, and 'username' and 'password' being the HTML form ids
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            header("Location: home.html");
            exit();
        }
    }

    else {
        echo "Login information is incorrect.";
    }
}

P.S. Also please note that your code is vulnerable to an attack called "SQL Injection", and you should also be hashing your passwords with salt.

相关阅读:
Top