Is there a way to make a param optional in PHP PDO?
Say I have this query:
$qry = 'SELECT p.id FROM products p
WHERE p.type = :type AND p.parent = :parent';
If I wanted to make "type" optional then the only way I know how to do it would be to do something like this:
$qry = 'SELECT p.id FROM products p
WHERE p.parent = :parent';
if(isset($type))
{
$qry .= 'AND p.type = :type';
}
Is this the best way? I am wondering if there is a way I can keep it like the original, and use some sort of parameter to indicate that it is optional... For example if $type = "*" then pull all types.
开发者_运维技巧Whats the best way to do this?
You might want to check for blank values as well
if(isset($type) && $type != '') {
$qry .= 'AND p.type = :type';
}
Theoretically this might work:
AND :type IN (NULL, p.type)
Not sure about the speediness. But it puts your query logic completely into the database.
精彩评论