我有一个登录系统,我一直在使用mysql函数,如real_escape_strings等。但现在我正在尝试将其转换为PDO,因为它比mysql函数更现代。问题是现在它无法与PDO一起工作。不管是我的代码请告诉我我的错误。
<?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
}
}
?>
答案 0 :(得分:2)
<?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'];
}
}
?>
你也需要检查信件。资本'密码'看起来很可疑。最好选择一个标准(全部小写)并随处跟随
以下是关于How prepared statements can protect from SQL injection attacks?问题解答如何运作的答案
答案 1 :(得分:0)
$query ='SELECT username FROM tish_user WHERE username=? AND Password = md5(?) )';
$result = $con->prepare($query);
$result->execute(array($username, $password));
这将自动为您转义字符串。