It is correct what he says @ LeonardeCabré in his answer.
If you are using PDO (or MySQLi), all queries that handle external variables must pass them through queries prepared to avoid the injection of malicious code.
I just want to point out that with PDO you can simplify the code, saving the bindParam
and passing the parameters as an array, in execute
.
The PHP Manual talks about that second possibility, which, I think, we exploit very little:
execute
Execute the prepared statement. If it included markers of
parameters, you should:
-
call PDOStatement::bindParam()
and / or PDOStatement::bindValue()
to link variables or values
(respectively) to the parameter markers. Variables
linked pass their value as input and receive the output value,
if any, of their associated parameter markers
-
or pass an array of input-only parameter values
❯ Source: execute
in the PHP Manual
Let's see two examples:
With :nombre
markers
$strSQL='SELECT SQL_CALC_ROWS * FROM articulos LIMIT :inicio, :postPorPaginas';
$articulos= $conexion->prepare($strSQL);
$arrParams=array(':inicio'=>$inicio, ':postPorPaginas'=>$postPorPaginas);
$articulos->execute($arrParams);
With placeholders ?
$strSQL='SELECT SQL_CALC_ROWS * FROM articulos LIMIT ?, ?';
$articulos= $conexion->prepare($strSQL);
$arrParams=array($inicio, $postPorPaginas);
$articulos->execute($arrParams);
Knowing this is particularly useful, when we have to pass many parameters, or when the parameters that intervene in the query are dynamic. It will avoid us constantly invoking bindParam
, it will facilitate the process of building a query that depends on several factors. The query executed thus is equally safe that when we use bindParam
.