skip to Main Content

Im having a trouble with a PHP Login form.

When Username + Password is Correct everything works fine , but when its incorrect it gives an error :

Notice: Trying to access array offset on value of type null in
/opt/lampp/htdocs/login/process.php on line 20 Login Failed!

I know is something related with the mysqli_fetch_array but i dont know what.

PHP is last version 7.4.8

<?php
// Get values from form in login.php

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

// To prevent SQL injection
$username = stripcslashes($username);
$password = stripcslashes($password);
// $username = mysql_real_escape_string($username);
// $password = mysql_real_escape_string($password);

// Database Connection
$con = mysqli_connect("localhost","root","1234", "login");

// Query the Db for username
$result = mysqli_query($con, "SELECT * FROM users WHERE username = '$username' AND password = '$password'")
        or die("Fail to connect to database".mysql_error());
$row = mysqli_fetch_array($result);
if ($row['username'] == $username && $row['password'] == $password){
    echo "Login succesfull!";
} else {
    echo "Login Failed!";
}

2

Answers


  1. The problem is because the $row variable initialised as:

    $row = mysqli_fetch_array($result);
    

    is equal to null, when no user matches the provided password and username. The quick fix is to extend the condition for successful login to include a null check:

    if ($row !== null && $row['username'] == $username && $row['password'] == $password) {
        echo "Login succesfull!";
    }
    

    On a side note, know that escaping values using mysql_real_escape_string may still not be enough to prevent SQL Injection. Instead, a prepared statement with typed parameters should be used.

    Also, storing passwords in a plain text is really not a good idea. It’d be recommended to implement a mechanism using e.g. the password_hash and password_verify functions.

    Login or Signup to reply.
  2. $result = mysqli_query($con, "SELECT * FROM users WHERE username = '$username' AND password = '$password'")
            or die("Fail to connect to database".mysql_error());
    if(mysqli_num_rows($result) > 0) {
        echo "Login succesfull!";
    } else {
        echo "Login Failed!";
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search