Assuming you know what it is SQL Injection
First you need to understand one thing, Prepared Statement has two features:
- Escaping values (if well used)
- Optimize Repeated Searches
So you should use it whenever possible, not necessarily for the first but for the second. Now if you will pass the values by bindParam
depends on whether you know what that value is, and not whether or not the value is a constant
For example imagine that you have a class that does some pagination queries:
class Paginacao {
private $itensPorPagina;
public function __construct($itensPorPagina) {
$this->itensPorPagina = $itensPorPagina;
}
public function buscarPorNome($nome) {
$stmtPG = $conn->prepare("SELECT * FROM usuarios WHERE nome = :nome LIMIT $this->itensPorPagina");
$stmtPG->bindParam(':nome', $name, PDO::PARAM_STR);
//...
}
public function buscarPorTelefone($telefone) {
$stmtPG = $conn->prepare("SELECT * FROM usuarios WHERE telefone = :telefone LIMIT $this->itensPorPagina");
$stmtPG->bindParam(':telefone', $telefone, PDO::PARAM_STR);
//...
}
}
Then you’d use it that way
$paginacao = new Paginacao(25);
$paginacao->buscarPorNome($_GET["nome"]);
Note that itensPorPagina
is not a constant, but who defines its value is the programmer at the time of instantiating the class Paginacao
You don’t need to pass the itensPorPagina
for bindValue
because you know that its value is only an integer of value 25, the fact that it is a constant has nothing to do with
Now if it was a variable that came from the user, like the name and phone, then yes, you need to go through bindParam
to avoid SQL Injection
Completion
You do not need to pass variables as a parameter in SQL statements if you know what their value is. Only pass what is doubtful (user entries)
Basically a constant is a value that does not change, if you know what is the initial value of it does not have why to escape it, now if its value is dynamic (comes from the user input) is necessary as well as all other inputs. Remember, never trust your customer’s data
– Costamilam