I want to know if the use of bindParam is mandatory to prevent SQL injection using PDO and MYSQL.

Example:

$username=$_POST['username'];
$password=$_POST['password'];
$cryptpass=hashFunction($password);
$sth=$dbh->prepare("INSERT INTO users(username,password) VALUES(?,?)");
$sth->execute(array($username,$cryptpass));

Is it a safe and proper way to write this code? Omitting bindParam makes shorter code.

有帮助吗?

解决方案

This is still binding the values to a prepared statement. You are doing the same thing as if you were using the bindParam function. So the answer is yes it is just as safe. bindParam just allows for more functionality than simply binding with the execute function for example:

$sth=$dbh->prepare("Select * from users where status=:v1");
$sth->bindParam(':v1',1,PDO::PARAM_INT);
$sth->execute();

This allows you to specify the data_type by default with execute everything is sent as a string. Also you can look at the answer to this similar question: PDO bindParam vs. execute

其他提示

All that matters is that you use parameters rather than substituting directly into the query string. It doesn't matter whether you bind the parameters with bindParam or with an array argument to execute, they're equivalent.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top