Should I use bindValue() or execute(array()) to avoid SQL injection?

℡╲_俬逩灬. 提交于 2019-12-12 01:06:28

问题


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())

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

Like for $aenrollmentno should I typecast into

$aenrollmentno = (int)($_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();
    }


    ?>

回答1:


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.

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.



来源:https://stackoverflow.com/questions/20551366/should-i-use-bindvalue-or-executearray-to-avoid-sql-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!