You could do a bit of string manipulation and write it fairly cleanly with one function . However , what if you had two three or even more optional search parameters ? The number of dedicated search functions or string manipulations would quickly get out of control . This is where a sql query builder comes in . The Doctrine Database Access Layer is a thin layer over pdo which , among other useful features , includes a query builder . Note that this is not the Doctrine ORM . project . o r g p r o j e c t s d o c t r i n e d b a l e n l a testreferencequerybuilder . htmlYour code would end up something like $ qb $ dbcreateQueryBuilder $ qbselect '' from ' posts ' orderBy ' id ' $ qbandWhere ' dateexpires CURRENTTIMESTAMP ' $ params if $ userId $ params $ userId $ qbaddWhere ' userid ? ' echo $ qbgetSQLBit verbose perhaps but you can build up fairly complicated conditional statements without much trouble . Best of all , you can even pass an array to a WHERE IN ? clause .