When preparing an SQL query using PDO, should/must I do
$query->bindValue('column', $value, is_null($value) ? PDO::PARAM_NULL : PDO::PARAM_STR);
Or I can just use PDO::PARAM_INT
or PDO::PARAM_STR
directly, because PDO figures that one out on its own? (as it really, really should in my opinion)
And as a curiosity follow-up question, if I don’t have to use PDO::PARAM_NULL
, what is it actually for?
Advertisement
Answer
No, you do not need to use PDO::PARAM_NULL
. If you bind NULL with any type, then PDO will use NULL internally. The value will not be converted to a string, number or any other type. NULL will remain NULL.
When you set the type to PDO::PARAM_NULL
it is equivalent to setting the value to NULL. One might argue that PDO::PARAM_NULL
is useless as you can achieve the same results when binding NULL with any other type.
The following statements will both bind literal NULL value.
$str = 'someString'; $stmt->bindParam(1, $str, PDO::PARAM_NULL); $str = null; $stmt->bindParam(1, $str, PDO::PARAM_STR); $stmt->bindValue(1, null);