-1

Below is my PHP code for login page.

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"])."' ";
    .....
    .....
}

I think, this is vulnerable code for SQL Injection. What should I modify in this code to prevent SQL Injection to my MYSQL database?

I am using following code to connect to my MySQL database:

function connect_database()
{
    $con = mysqli_connect("servername", "username", "", "dbname");
    if (!$con) 
    {
        $con = "";
        echo("Database connection failed: " . mysqli_connect_error());
    }
    return $con;
}

I am trying to use mysqli_prepare, but getting errors:

$unsafe_username = $_POST["username"];
$unsafe_password = md5($_POST["password"]);
$query=mysqli_prepare("select user_id from users where user_name= ? and password= ? ");
$query->bindParam("ss", $unsafe_username, $unsafe_password);
$query->execute();

I got following error:

Warning: mysqli_prepare() expects exactly 2 parameters, 1 given

Fatal error: Call to a member function bindParam() on null
KP Joy
  • 505
  • 1
  • 7
  • 16

2 Answers2

4

use prepared statement,

http://php.net/manual/en/pdo.prepared-statements.php

$stmt = mysqli->prepare("select user_id from users where user_name= ? and password= ?");
$stmt->bindParam("ss",$username,$pass);
$stmt->execute();
Dave
  • 3,050
  • 6
  • 15
  • 28
  • Getting this warning with your solution: Warning: mysqli_prepare() expects exactly 2 parameters, 1 given – KP Joy Jul 09 '16 at 06:00
  • can you show your code? – Dave Jul 09 '16 at 06:02
  • I have updated my question. Also mysqli->prepare is giving syntax error while mysqli_prepare is working. – KP Joy Jul 09 '16 at 06:08
  • try, var_dump($stmt); after your query. http://stackoverflow.com/questions/11374672/mysqli-bind-param-does-not-set-stmt-error-or-stmt-errno – Dave Jul 11 '16 at 10:26
0

You want to escape the strings that can be inputted into your query. Considering you are using the mysqli driver you can do this:

$username = mysqli_real_escape_string($con, $_POST["username"]);
$password = mysqli_real_escape_string($con, $_POST["password"]);

$query="select user_id from users where u.user_name='".$username."' and u.password='".md5($password)."' ";

Official documentation can be found here. You can also use prepared statements.

Countach
  • 527
  • 7
  • 20