I am a victim of sql injection, they hacked into my mysql database and they started deleting data and also they changed passwords. I thought using PDO am safe. This is my login page for PHP. I need help where did I go wrong here which led to the attacks. I would like to be advised on how to improve this code to avoid similar attacks to happen again.
<?php session_start(); ?>
<?php
require_once('dbconnect/pdo.inc.php');
$username = (isset($_POST['username'])) ? trim($_POST['username']) : '';
$password = (isset($_POST['password'])) ? trim($_POST['password']) : '';
$pas = md5($password);
$redirect = (isset($_REQUEST['redirect'])) ? $_REQUEST['redirect'] :
'index.php';
$result = array();
$result['error'] = FALSE;
$result['message'] = "";
//if(isset($_POST['submit'])){
if (empty($password)) {
$result['error'] = true;
$result['message'] = "enter password";
//json encode and echo reusult.
$res = json_encode($result);
echo $res;
exit();
}
if (empty($username)) {
$result['error'] = true;
$result['message'] = "enter username";
//json encode and echo reusult.
$res = json_encode($result);
echo $res;
exit();
}
$query = ("SELECT username FROM users WHERE username=:username
AND password =:password");
$query_login = $con->prepare($query);
$query_login->execute(array(
':username' => $username,
':password' => $pas));
$results = $query_login->rowCount();
if ($results > 0){
$_SESSION['username'] = $username;
$_SESSION['logged'] = 1;
$result['error'] = false;
$result['message'] = 'Successfully logedin';
header('Location:index.php');
$res = json_encode($result);
echo $res;
}
else{
//set these explicitly just to make sure
$result['error'] = true;
$result['message'] = 'User name invalid';
header('Location:login.php');
$res = json_encode($result);
echo $res;
exit();
}
// }
?>
//This is the way I connect to the database
<?php
function connected_Db(){
$dsn = 'mysql:host=localhost;dbname=usaDB;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
#echo "Yes we are connected";
return new PDO($dsn,'brrmingham','m#67yhfdelkomngf_()likf4', $opt);
}
$con = connected_Db();
if($con){
//echo "connected ";
}
else {
//echo "Connection faid ";
exit();
}
?>