Lets say I have a mysql query which gets built depending on certain conditions: example
$query = "SELECT * from `usertable` where users_active=:users_active";
if($mode=="archived") {
$query .= " AND archived=:archived";
}
$stmt = $dbpdo->prepare($query);
$stmt->bindParam(':users_active', $users_active);
$stmt->bindParam(':archived', $archived);
$stmt->execute();
Now, if I run the above it will only work if $mode=="archived", as otherwise the named placeholder ":archived" will not be part of the query.
This makes sense to me in one respect but begs the question of how to deal with it elegantly. I have lots of queries in my application which are built conditionally. I could do this, but this seems like duplication to me:
if($mode=="archived") {
$stmt->bindParam(':archived', $archived);
}
This seems long winded, particularly if there are lots of conditions to how the query is built. Does anyone have a neater idea on how to do this without having to add lots of conditional tests.
Any thoughts would be appreciated.
Regards
James