如何将动态参数传递给查询?

时间:2018-03-07 15:44:11

标签: php mysql sql dynamic

这是我的代码:

$param2 = $val2 = "";
if ($myCondition){
    $parm2 = ", param2 = ?";
    $val2 = "something";
}

$stmt = $dbh_conn->prepare("UPDATE myTable SET param1 = ? $param2 WHERE param3 = ?");
$stmt->execute([$val1, $val2, $val3]);

当条件为true时,我的代码有效。如果那是false

,我该如何处理?

3 个答案:

答案 0 :(得分:3)

$param2 = $val2 = "";
if ($myCondition){
    $parm2 = ", param2 = ?";
    $val2 = "something"; 
    $stmt = $dbh_conn->prepare("UPDATE myTable SET param1 = ? $param2 WHERE param3 = ?");
    $stmt->execute([$val1, $val2, $val3]);
} else {
    $stmt = $dbh_conn->prepare("UPDATE myTable SET param1 = ? WHERE param3 = ?");
    $stmt->execute([$val1, $val3]);
}

答案 1 :(得分:1)

这是一个开始的代码:

$params = ['param1 = ?'];
$values = [$param1];
if ($myCondition){
    $params[] = 'param2 = ?'
    $values = [$param2];
}
$values[] = $param3;

$stmt = $dbh_conn->prepare("UPDATE myTable SET " . implode(', ', $params)  . " WHERE param3 = ?");
$stmt->execute($values);

您可以根据需要对其进行修改,但主要思想是收集将在数组中更新的所有值,然后将此数组内爆为字符串。

答案 2 :(得分:0)

更简单的方法是:

if ($myCondition){
$stmt = $dbh_conn->prepare("UPDATE myTable SET param1 = ?, param2 = ? WHERE param3 = ?");
$stmt->execute([$val1, "something", $val3]);
} else {
    $stmt = $dbh_conn->prepare("UPDATE myTable SET param1 = ? WHERE param3 = ?");
$stmt->execute([$val1, $val3]);
}