简体   繁体   中英

Is My PDO Prepared Statement Secure If I Bind The Parameters In The Execute Function?

I have some form data that I'm writing to a database with PDO prepared statements.

This form data is santized and validated on the on the way in to the database with filter_var() functions and regular expressions and when any of this data is outputted to the site it escaped with htmlspecialchars() .

To prevent SQL injections I'm using I'm using the code below. When I first learnt PDO this was what I saw in the tutorial and I personally find it very easy to read/understand.

I've noticed on the php.net site and in some other code I've saw recently they used bindparams(), whereas in the code below I've always done this inside an array in the execute() method.

Is my code below secure? Or must I use bindparams in the way that is shown in the second code example?

Here is some sample code using a firstname input from a webform

<?php

$firstname = $_POST['firstname'];

$firstname = filter_var($fname, FILTER_SANITIZE_STRING);

if(empty(trim($fname))){
    $error[] = "First Name cannot be blank";
}

$sql = "INSERT INTO users (firstname) VALUES (:firstname)";
$stmt = $connection->prepare($sql);
$stmt->execute([
    ':firstname' => $firstname,
]);

In the php.net docs it does the above prepared statement using bindParam() , which seems a little verbose if you are updating a number of fields?

<?php
$sql = "INSERT INTO users (firstname) VALUES (:firstname)";

$stmt = $connection->prepare($sql);
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);

$stmt->execute();

If it is more secure then I'll obviously have to do it the second way, but wanted to check if my prepared statements given in the first code block are secure?

It's fine either way. The security benefit is from using placeholders at all. There are some cases (dynamically constructed queries) where it's beneficial to use bindParam separately from the execute call, and there are others where you would prefer to avoid the verbosity. Use what suits you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM