KP Joy KP Joy - 1 year ago 72
SQL Question

Preventing SQL Injection in Login Page in PHP

I have a login page (

) and below is the code I am trying to use to authenticate the user by using

if(!$_POST["username"] || !$_POST["password"])
echo "Username and Password fields are mandatory.";
$unsafe_username = $_POST["username"];
$unsafe_password = md5($_POST["password"]);
$query=mysqli_prepare($con, "select user_id from users where user_name= ? and password= ? ");
$query->bind_param("ss", $unsafe_username, $unsafe_password);
$data = $query->get_result();

echo "Login successful";
echo "Login failed";

Below is the code used for making MYSQL connection:

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

By using
, I am getting following warning and error messages:

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

Fatal error: Call to a member function bindParam() on null

I asked the similar question two days ago, but did not get any complete solution. (Prevent SQL Injection to Login Page in PHP and MySQL).

Please help me in resolving the problem. Is it the best approach to prevent my DB from SQL Injection?

Answer Source

missing connection variable $con

$query=mysqli_prepare($con,"select user_id from users where user_name= ? and 
password= ? ");      

and change this too

$query->bind_Param("ss", $unsafe_username, $unsafe_password);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download