Search code examples
phpsecuritypdodatabase-connectionsql-injection

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


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


    ?>

Solution

  • 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.