I often see code using bindParam
or bindValue
with PDO. Is simply passing arguments to execute
frowned upon for any reason?
I understand that bindParam
actually binds to the variables and that you can set the type of parameter being bound with both bind
methods, but what if you are only inserting strings?
$query = "SELECT col1 FROM t1 WHERE col2 = :col2 AND col3 = :col3 AND col4 = :col4";
$pdo->bindValue(':col2', 'col2');
$pdo->bindValue(':col3', 'col3');
$pdo->bindValue(':col4', 'col4');
I often see the above, but personally I prefer:
$pdo->execute(array(':col2' => 'col2', ':col3' => 'col3', ':col4' => 'col4'));
It is not as verbose and visually it makes more sense to me to have the inputs "going in" to the query together. However, I hardly ever see it used.
Is there a reason to prefer the bind
methods over passing parameters to execute
when you don't have to take advantage of the special behaviors of the former?
You might find bindParam
used when you just want to bind a variable reference to a parameter in the query, but perhaps still need to do some manipulations on it and only want the value of the variable calculated at time of query execution. It also allows you to do more complex things like bind a parameter to a stored procedure call and have the returned value updated into the bound variable.
For more, see the bindParam documentation, bindValue documentation and execute documentation.
For example
$col1 = 'some_value';
$pdo->bindParam(':col1', $col1);
$col1 = 'some_other_value';
$pdo->execute(); // would use 'some_other_value' for ':col1' parameter
bindValue
and passing an array to execute
behave in much the same way as the parameter value is fixed at that point and SQL executed accordingly.
Following the same example above, but using bindValue
$col1 = 'some_value';
$pdo->bindValue(':col1', $col1);
$col1 = 'some_other_value';
$pdo->execute(); // would use 'some_value' for ':col1' parameter
When passing values directly in execute
all values are treated as strings (even if integer value is provided). So if you need to enforce data types, you should always use bindValue
or bindParam
.
I think you might see bind*
used more than execute(array)
as many consider it to be better coding practice to explicitly define data types in parameter declarations.