phpsql-injectionparameterized-query

"Cant process the request", dealing with basic parameterized queries


I am trying something I found online (Extremely new to this) and none of it works. It's some random science project I decided to learn more about yet I am stuck on part 2 of the "procedures". https://www.sciencebuddies.org/science-fair-projects/project-ideas/Cyber_p008/cybersecurity/sql-injection#procedure

I watched videos but they only consist of just a user_ID and not a username and password. NOTE: Only the code dealing with login.php is causing problems.

<?php
include("global.php");
include("db.php");

session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST") {

  // username and password are sent in the form 

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

  // Check if the username and password exist in the database

  $sql = "SELECT username FROM users WHERE username = '$username' AND password = '$password'";
  $stmt = msqli_stmt_init($db);
  if (!mysqli_stmt_prepare($stmt, $sql)) {
    echo "SQL Statement Failed";
  } else {
      mysqli_stmt_bind_param($stmt, "ss", $username, $password );
  mysqli_stmt_execute($stmt);
   $result = mysqli_stmt_get_result($stmt);
   $row = mysqli_fetch_array($result, MYSQLI_ASSOC);

   $count = mysqli_num_rows($result);}
  // If username and password matched then there is one row in the result

  if ($count != 0) {
     $_SESSION['login_user'] = strtolower($username);

     header("location: search.php");
  }
  else {
     $error = "Your Username or Password is invalid";
  }

} ?>

It should have prevented a basic " 'or''=' " injection attack but it decided not to work entirely.


Solution

  • If you use query parameters — which is definitely a good idea — you must leave placeholders in your query. Use ? as the placeholder.

    Like this:

    $sql = "SELECT username FROM users WHERE username = ? AND password = ?";
    

    You later bind variables to those parameters. You must bind the same number of variables as the number of parameter placeholders.

    You got the error you described because you tried to bind variables to a query that had no parameter placeholders.