使用一个具有可变数量的输入变量的 bind_param() [英] Use one bind_param() with variable number of input vars

查看:23
本文介绍了使用一个具有可变数量的输入变量的 bind_param()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);
}

这篇关于使用一个具有可变数量的输入变量的 bind_param()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆