简体   繁体   中英

“Notice: Trying to access array offset on value of type null” being returned when username is entered wrong

I am trying to create a login page, and everything works as expected, except for when a wrong username is entered, I get the error Notice: Trying to access array offset on value of type null for the line if ($_POST['username'] != $row['username']) { in the below code, and I do not understand enough to fix it, as I am still pretty new to this. Any help or suggestions would be greatly appreciated. Any advice on proper ways to write and/or execute my code is welcome as well, thank you.


session_start();

$DATABASE_HOST = "localhost";
$DATABASE_USER = "root";
$DATABASE_PASSWORD = "";
$DATABASE_NAME = "tasktracker";

$link = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASSWORD, $DATABASE_NAME);

if (mysqli_connect_errno()) {

    exit("Failed to connect to database: " . mysqli_connect_error());

}

//Server side form validation

if ($_POST) {

    if (!$_POST['username']) {

        $error .= "A username is required!<br>";

    }

    if (!$_POST['password']) {

        $error .= "A password is required!<br>";

    }

    if (strlen($_POST['password']) < 8) {

        $error .= "Your password must be greater than 8 characters!<br>";

    }

    if (strlen($_POST['password']) > 30) {

        $error .= "Your password must be less than 30 characters!<br>";

    }

if ($error != "") {

    $error = '<div class=""><p><strong>There were issues(s) in your form:</strong></p>' . $error . '</div>';

    echo $error;

    

} else {

//Log user in

    $query = "SELECT * FROM users WHERE username = '".mysqli_real_escape_string($link, $_POST['username'])."' LIMIT 1";

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

    $row = mysqli_fetch_assoc($result);

    if ($_POST['username'] != $row['username']) {

        $error = "That username is incorrect.";

    } else if (md5(md5($row['id']).$_POST['password']) != $row['password']) {

        $error = "That password is incorrect.";

    } else {

        echo 1;

    }

    if ($error != "") {

        $error = '<div class=""><p><strong>There were issues(s) in your form:</strong></p>' . $error . '</div>';

        echo $error;

    } else {

        exit();

    }

}

}```

change this line

if ($_POST['username'] != $row['username']) {

    $error = "That username is incorrect.";

} 

by

if (!$result) {

    $error = "That username is incorrect.";

} 

because if $result is false or has 0 items then no user was found with this username

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