0

Is the following code vulnerable to Sql injections and how to validate it ?

$query=("select * from table2 where username = '$username'and password='$password'");
$result=  mysqli_query($connect, $query);
       $row=  mysqli_fetch_assoc($result);
    if  ($username==$row['username']&&$password==$row['password'])
    {
        header('location:header.php');//to go header
        }
else
{
    header('location:insert_p.php');}
rollstuhlfahrer
  • 3,988
  • 9
  • 25
  • 38
A.Al
  • 1
  • 1

1 Answers1

1

Yes, your code seems vulnerable to SQL injections. Look at this line:

$query=("select * from table2 where username = '$username' and password='$password'");

Here you are passing the variables $username and $password directly to the database. If $username contains a string like admin'; -- then there will be no check for the password.

How to validate?

Just make sure, that every variable you directly put into an SQL statement is safe.

Other solutions?

  • You can use mysqli_real_escape_string() (docs) to escape special characters like '.
  • You can use prepared statements. They seperate code and values. This is a good start.
Community
  • 1
  • 1
rollstuhlfahrer
  • 3,988
  • 9
  • 25
  • 38