duandai0373 2013-02-17 08:07
浏览 60
已采纳

如何将mysql函数转换为现代PDO

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 

}
    }

?>
  • 写回答

2条回答 默认 最新

  • douhua1890 2013-02-17 08:24
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?