-2

I have a login system which I have been using with mysql functions like real_escape_strings and more . but now I am trying to convert it to PDO since its more modern than mysql functions . the problem is now it does not work with PDO .below is my code please tell me what i mght be doing wrong .

<?php
try {
$con = new PDO('mysql:host=localhost;dbname=tish_database;charset=utf8','root','');

} catch(PDOException $e){
echo 'Connection failed'.$e->getMessage();
}

?>
<?php 
$is_ajax = $_POST['is_ajax'];
    if(isset($is_ajax) && $is_ajax)

    {
$username =(isset($_POST['username']))? trim($_POST['username']): '';
$Password=(isset($_POST['Password']))? $_POST['Password'] : '';
$redirect=(isset($_REQUEST['redirect']))? $_REQUEST['redirect'] :
'view.php';
$query ='SELECT username FROM tish_user WHERE '.
'username="'.($username,$con).'" AND ' .
   'Password = md5("'.($Password,$con).'")';
  $result = $con->prepare($query); 
   $result->execute();
        if(count($result)>0)
        {
        $_SESSION['username']=$username;
$_SESSION['logged'] = 1;
            echo "success"; 
        }
        else {
//set these explicitly just to make sure 

}
    }

?>
Humphrey
  • 2,659
  • 3
  • 28
  • 38

2 Answers2

2

after removing all useless code

<?php
$con = new PDO('mysql:host=localhost;dbname=tish_database;charset=utf8','root','');

if(!empty($_POST['is_ajax']))
{
    $sql = 'SELECT id FROM tish_user WHERE username=? AND Password = md5(?)';
    $stm = $con->prepare($sql); 
    $stm->execute(array($_POST['username'],$_POST['Password']));
    if($row = $stm->fetch())
    {
        $_SESSION['id'] = $row['id'];
    }
}
?>

you need to check letter case too. capital 'Password' looks suspicious. Better choose one standard (all lowercase) and follow it everywhere

Here is my answer on the How prepared statements can protect from SQL injection attacks? question explaining how it works

Community
  • 1
  • 1
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
0
$query ='SELECT username FROM tish_user WHERE username=? AND Password = md5(?) )';
$result = $con->prepare($query); 
$result->execute(array($username, $password));

This will automatically escape strings for you.

hjpotter92
  • 78,589
  • 36
  • 144
  • 183