title: Prevent SQL Injection to Login Page in PHP and MySQL
body: <p>Below is my PHP code for login page.</p>
  
  <pre><code>if(!$_POST["username"] || !$_POST["password"])
  {
      echo "Username and Password fields are mandatory.";
  }
  else
  {
      $query="select user_id from users where user_name='".$_POST["username"]."' and password='".md5($_POST["password"])."' ";
      .....
      .....
  }
  </code></pre>
  
  <p>I think, this is vulnerable code for SQL Injection. What should I modify in this code to prevent SQL Injection to my MYSQL database?</p>
  
  <p>I am using following code to connect to my MySQL database:</p>
  
  <pre><code>function connect_database()
  {
      $con = mysqli_connect("servername", "username", "", "dbname");
      if (!$con) 
      {
          $con = "";
          echo("Database connection failed: " . mysqli_connect_error());
      }
      return $con;
  }
  </code></pre>
  
  <p>I am trying to use mysqli_prepare, but getting errors:</p>
  
  <pre><code>$unsafe_username = $_POST["username"];
  $unsafe_password = md5($_POST["password"]);
  $query=mysqli_prepare("select user_id from users where user_name= ? and password= ? ");
  $query-&gt;bindParam("ss", $unsafe_username, $unsafe_password);
  $query-&gt;execute();
  </code></pre>
  
  <p>I got following error:</p>
  
  <pre><code>Warning: mysqli_prepare() expects exactly 2 parameters, 1 given
  
  Fatal error: Call to a member function bindParam() on null
  </code></pre>