PDO Bind Params depending on whether they exists in the query

笑着哭i 提交于 2019-12-08 05:35:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!