2012-04-06 121 views
1

因此,我得到了一些使用变量列表的语句,看起来我总是在数据库中添加另一列,所以我想创建一个变量列表并以某种方式包含变量,以便我可以更改它曾经,如果我需要,而不是六次。将多个变量整合到一个

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

你检查,如果bind_result()也可以接受一个数组?如果是这样,请使用包含所有变量的数组 – Kristian 2012-04-06 19:43:11

+0

谢谢克里斯蒂安,但我试图把它放在一个数组中,并且绑定似乎不接受数组。我得到“不匹配的变量数”错误 – 2012-04-06 19:45:25

回答

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

相关问题