请看下面我的代码.我试图将参数数组绑定到我准备好的语句中.我一直在网上浏览,可以看到我必须使用call_user_func_array,但无法让它工作.我得到的错误是:"第一个参数应该是一个有效的回调,'数组'被给出"我可能是错的,但我假设第一个参数可以是一个数组,也许这个错误信息是误导性的.我认为问题是我的阵列在某种程度上是错误的.谁能看到我做错了什么?谢谢.
$type = array("s", "s");
$param = array("string1","anotherstring");
$stmt = $SQLConnection->prepare("INSERT INTO mytable (comp, addl) VALUES (?,?)");
$params = array_merge($type, $param);
call_user_func_array(array(&$stmt, 'bind_param'), $params);
$SQLConnection->execute();
Run Code Online (Sandbox Code Playgroud)
小智 18
一定是这样的:
//connect
$mysqli = new mysqli($host, $user, $password, $db_name);
//prepare
$stmt = $mysqli->prepare("SELECT * FROM the_table WHERE field1= ? AND Field2= ?");
//Binding parameters. Types: s = string, i = integer, d = double, b = blob
$params= array("ss","string_1","string_2");
//now we need to add references
$tmp = array();
foreach($params as $key => $value) $tmp[$key] = &$params[$key];
// now us the new array
call_user_func_array(array($stmt, 'bind_param'), $tmp);
$stmt->execute();
/* Fetch result to array */
$res = $stmt->get_result();
while($row = $res->fetch_array(MYSQLI_ASSOC)) {
$a_data[]=$row;
}
print_r($a_data);
$stmt->close();
Run Code Online (Sandbox Code Playgroud)
我不知道你为什么要使用call_user_func_array
,但这是另一个故事.
在我眼中唯一可能出错的是你正在使用对象的引用.假设您使用的是PHP 5.*,这不是必需的:
call_user_func_array(array($stmt, 'bind_param'), $params);
Run Code Online (Sandbox Code Playgroud)