【问题标题】:Php multiple variables into onephp多个变量合二为一
【发布时间】:2012-04-06 19:38:16
【问题描述】:

所以我有几个使用变量列表的语句,似乎我总是在数据库中添加另一列,所以我想制作一个变量列表并以某种方式包含它,这样我就可以在需要时更改一次而不是六次。

    $stmt = $mysql->prepare("SELECT * FROM table WHERE id =? LIMIT 1");

$stmt -> bind_param('i', $id);

$stmt->execute();

$stmt->bind_result($a, $b, $c, $d, $e, $f, $g);

$stmt->fetch();

$stmt->close(); 

但我想做这样的事情:

    varList="$a, $b, $c, $d, $e, $f, $g";

    $stmt = $mysql->prepare("SELECT * FROM table WHERE id =? LIMIT 1");

$stmt -> bind_param('i', $id);

$stmt->execute();

$stmt->bind_result($varList);

$stmt->fetch();

$stmt->close(); 

【问题讨论】:

  • 你检查过 bind_result() 是否也可以接受一个数组吗?如果是这样,请使用包含所有变量的数组
  • 感谢克里斯蒂安,但我尝试将其放入数组中并且绑定似乎不接受数组。我收到“与变量数不匹配”错误

标签: php variables mysqli prepared-statement


【解决方案1】:

您可以做一个数组(对变量的引用),然后使用call_user_func_array 调用bind_result

例子:

$varList = array('a', 'b', 'c', 'd', 'e', 'f', 'g'); // variable names.
$params = array(); // list of params

foreach($varList as $v){
    $params[] = &$$v; // store a reference to the vars in $params
}

call_user_func_array(array($stmt, 'bind_result'), $params);

您可能不需要foreach 循环,您也可以这样做:

$varList = array(&$a, &$b, &$c, &$d, &$e, &$f, &$g); // variable references

call_user_func_array(array($stmt, 'bind_result'), $varList);

根据这个答案:https://stackoverflow.com/a/966717/206403

【讨论】:

    猜你喜欢
    • 2019-11-06
    • 1970-01-01
    • 2023-03-20
    • 2022-06-17
    • 2020-12-08
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多