我应该使用bindValue()还是execute(array())来避免SQL注入? [英] Should I use bindValue() or execute(array()) to avoid SQL injection?

查看:785
本文介绍了我应该使用bindValue()还是execute(array())来避免SQL注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了防止SQL注入,我使用PDO。我已经看到人们使用两种方法ie:bindValue()和then()或只是执行(array())

As a prevention against SQL injections, I'm using PDO. I have seen people using both the methods ie: bindValue() and then execute() or just execute(array())

这两种方法是否会阻止攻击?因为mysql_real_escape_string()已被弃用有什么其他我应该考虑使用这里?

Do both the methods prevent the attack? Since mysql_real_escape_string() is deprecated is there anything else I should consider using here?

像$ aenrollmentno应该类型转换为

Like for $aenrollmentno should I typecast into

$ aenrollmentno = ($ _POST ['aenrollmentno']);

如果我不在准备语句中使用它,我缺少的任何其他安全措施?

Will this be safe enough if I'm not using it in a prepared statement? Any other security measure that I'm missing?

   <?php  


     if(isset($_POST['aenrollmentno']))
     {
    $aenrollmentno = mysql_real_escape_string($_POST['aenrollmentno']); 
     }



 if(isset($_POST['afirstname']))
        {
            $afirst_name  = mysql_real_escape_string($_POST['afirstname']);
            $afirstname = ucfirst(strtolower($afirst_name));

    }




    //PDO connection     
    try {


        $conn = new PDO('mysql:host=localhost;dbname=practice','root','');
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

        $stmt = $conn->prepare('INSERT INTO  modaltable(afirstname, alastname,aenrollmentno) VALUES (:afirstname,:alastname,:aenrollmentno)');

        $stmt->execute(array(

        'afirstname' => $afirstname,
        'alastname' => $alastname,
        'aenrollmentno' => $aenrollmentno,

        ));



    echo "Success!";


    }
    catch (PDOException $e) {
        echo 'ERROR: '. $e->getMessage();
    }


    ?>


推荐答案

execute(array)在每个数组元素上调用bindValue。使用任何适合您的程序流最好。两者都阻止SQL注入。

execute(array) is just a shortcut for a loop that calls bindValue on each of the array elements. Use whatever suits your program flow best. Both prevent SQL injection.

经验法则:无论你传递给哪个准备,都不应以任何方式依赖于用户输入。你可以传递任何你想要执行() - 你可能会得到运行时错误,例如。如果您尝试将非数字字符串放入数字列 - 但您不允许SQL注入。

Rule of thumb: Whatever you pass to prepare should NOT, in any way, depend on user input. You can pass anything you want to execute() - you might get runtime errors, e.g. if you try to put a non-numeric string into a number column - but you won't allow SQL injections.

这篇关于我应该使用bindValue()还是execute(array())来避免SQL注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆