问题
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
回答1:
You can use an array with the values and send that as a parameter to the execute() method.
If the type casting of the variables that bindParam()
offers is not that important (you're not even using it...), that makes building queries a lot easier as you can fill the array when you build the query string.
For your example:
$query = "SELECT * from `usertable` where users_active=:users_active";
$params = array(':users_active' => $users_active);
if($mode=="archived") {
$query .= " AND archived=:archived";
$params[':archived'] = $archived;
}
$stmt = $dbpdo->prepare($query);
$stmt->execute($params);
来源:https://stackoverflow.com/questions/29498155/pdo-bind-params-depending-on-whether-they-exists-in-the-query