将多个变量Php合二为一

时间:2012-04-06 19:38:16

标签: php variables mysqli prepared-statement

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

    $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(); 

1 个答案:

答案 0 :(得分: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

相关问题