tags:

views:

28

answers:

2

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?

+1  A: 

You might want to check for blank values as well

if(isset($type) && $type != '') {
    $qry .= 'AND p.type = :type';
}
Phill Pafford
or simply `if(!empty($type)) {}`
choise
It depends if a blank value if a valid value for the field does it not?
Nev Stokes
@choise I like != '' as empty() sees 0 (int/string) and FALSE as empty but they could be acceptable values.
Phill Pafford
@nev stokes, agreed but I would also agree if your looking for a set value that it wouldn't be blank. 2 cents
Phill Pafford
A: 

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.

mario