Yes, your code follows good practices for SQL injection prevention. Using parameters is the right way to do it.
The only suggestion would be optional, for the sake of code style, not secure code. Yours is just as secure.
$a=preg_replace('/[%_]/', '\\\\$0', $_GET["a"]);
$b=preg_replace('/[%_]/', '\\\\$0', $_GET["b"]);
$sql="
SELECT * FROM table
WHERE ColA LIKE :txtA AND ColB LIKE :txtB";
$query = $db->prepare($sql);
$query->execute(['txtA'=>"%{$a}%", 'txtB'=>"%{$b}%"]);
PDO allows you to pass query parameters as an array argument to execute()
, so you don't have to use bindValue()
.
Also, you don't need PDO::PARAM_STR
arguments to bindValue()
at least not for MySQL. The PDO driver for MySQL always passes parameters as strings. Maybe it's required for some other brands of database.
You can write your SQL query in one multi-line string (unlike some languages like Java). You don't need to use .=
.
You can embed PHP variables inside double-quoted strings. You don't need to use '%'.$a.'%'
, you can use "%{$a}%"
. I find the latter a little more more readable, especially when you have multiple variables to include.