Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top