Based on the principle that you know what SQL Injection is SQL Injection
First you need to understand something, the Prepared Statement has two functionalities:
- Escape values (if well used)
- Optimize repeat 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
it depends if you know what value this is, and not whether or not the value is a constant
For example, imagine that you have a class that does some paging 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);
//...
}
}
So you would 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 when instantiating the class Paginacao
You do not need to pass itensPorPagina
to bindValue
because you know its value is just an integer of value 25, being a constant has nothing to do
Now if it was a variable that came from the user, such as the name and phone, then yes, you need to pass bindParam
to avoid SQL Injection
Conclusion
You do not need to pass variables as a parameter in SQL statements if you know what their value is. Just pass on what is doubtful (user input)