我正在尝试使用call_user_func_array和mysqli_stmt :: bind_param,如下所示:
# A. prepare an insert query statement
$this->_stmt = $db_link->prepare('INSERT INTO foo (col1, col2) VALUES (?,?)');
# B. bind a placeholder array to the statement
$bound = array('col1' => null, 'col2' => null);
call_user_func_array(array($this->_stmt, 'bind_param'),
array($types_string, &$bound));
# C. while there are records, retrieve, munge, and insert
while ($row = $res->fetch_assoc()) {
$bound = transform($row); # $bound remains an array indexed as 'col1', 'col2'
$this->_stmt->execute(); # PHP Notice: Array to string conversion
}
我对PHP引用感到困惑,导致数组转换为字符串。我在步骤B中没有正确绑定占位符数组,或者我没有在步骤C中正确分配占位符。
(以前曾问过类似的问题,但我没有找到答案。)
答案 0 :(得分:2)
你正在传递
array(
types,
&array(
a, b, c
)
)
到call_user_func_array(),但必须是
array(
types, &a, &b, &c
)
实现这一目标的一种方法是使用另一个(临时)数组,其中“原始”数组的所有元素都作为引用。 http://docs.php.net/call_user_func_array:
注意:param_arr中的引用变量通过引用传递给函数,其他变量通过值传递。 [...]
E.g。
$mysql = new mysqli('localhost', 'localonly', 'localonly', 'test');
// test table
$mysql->query('CREATE TEMPORARY TABLE foo (a int, b int, c int)') or die($mysql->error);
$params = array('a'=>null, 'b'=>null, 'c'=>null);
$types = 'iii';
$stmt = $mysql->prepare('INSERT INTO foo (a,b,c) VALUES (?,?,?)');
// make an array of references to the original array
$tmp = array($types);
foreach( $params as &$p ) {
$tmp[] = &$p;
}
call_user_func_array( array($stmt, 'bind_param'), $tmp);
// test insert
for($i=0; $i<10; $i++) {
$params['a'] = $i;
$params['b'] = $i+100;
$params['c'] = $i+1000;
$stmt->execute();
}
unset($stmt);
// test select
$result = $mysql->query('SELECT * FROM foo');
while( null!==($row=$result->fetch_row()) ) {
echo join(',', $row), "\n";
}