使用一个具有可变数量的输入变量的 bind_param()

2021-12-25 00:00:00 php mysqli

我尝试像这样使用变量绑定:

I try to use variable binding like this:

$stmt = $mysqli->prepare("UPDATE mytable SET myvar1=?, myvar2=... WHERE id = ?")) {
$stmt->bind_param("ss...", $_POST['myvar1'], $_POST['myvar2']...);

但有些 $_POST['...'] 可能是空的,所以我不想在数据库中更新它们.

but some of the $_POST['...'] might be empty so I don't want to update them in the DB.

考虑空 $_POST['...'] 的所有不同组合是不切实际的,虽然我可以根据我的需要构建字符串UPDATE mytable SET...",但 bind_param() 是不同的野兽.

It's not practical to take into account all the different combination of empty $_POST['...'] and although I can build the string " UPDATE mytable SET..." to my needs, bind_param() is a different beast.

我可以尝试将其调用构建为字符串并在其上使用 eval() 但感觉不对:(

I could try building its call as a string and use eval() on it but it doesn't feel right :(

推荐答案

您可以使用 call_user_func_array 函数调用带有可变编号或参数的 bind_param 方法:

$paramNames = array('myvar1', 'myvar2', /* ... */);
$params = array();
foreach ($paramNames as $name) {
    if (isset($_POST[$name]) && $_POST[$name] != '') {
        $params[$name] = $_POST[$name];
    }
}
if (count($params)) {
    $query = 'UPDATE mytable SET ';
    foreach ($params as $name => $val) {
        $query .= $name.'=?,';
    }
    $query = substr($query, 0, -1);
    $query .= 'WHERE id = ?';
    $stmt = $mysqli->prepare($query);
    $params = array_merge(array(str_repeat('s', count($params))), array_values($params));
    call_user_func_array(array(&$stmt, 'bind_param'), $params);
}

相关文章