嗨,我在合并数组和绑定参数时遇到了一些问题。
错误消息 = 警告:mysqli_stmt::bind_param():元素数 IN 类型定义字符串与绑定变量的数量不匹配 在。。。。。。。
$headline = $_GET['hl'];
$county = $_GET['ca'];
$categories = $_GET['co'];
$query = 'SELECT COUNT(id) FROM main_table';
$queryCond = array();
$stringtype = array();
$variable = array();
if (!empty($headline)) {
$queryCond[] = "headline LIKE CONCAT ('%', ? , '%')";
array_push($stringtype, 's');
array_push($variable, $headline);
}
if (!empty($county)) {
$queryCond[] = "county_id = ?";
array_push($stringtype, 'i');
array_push($variable, $county);
}
if (!empty($categories)) {
$queryCond[] = "categories_id = ?";
array_push($stringtype, 'i');
array_push($variable, $categories);
}
if (count($queryCond)) {
$query .= ' WHERE ' . implode(' AND ', $queryCond);
}
//var_dump($query);
$stmt = $mysqli->prepare($query);
$variable = array_merge($stringtype, $variable);
print_r($variable);
//var_dump($refs);
$refs = array();
foreach($variable as $key => $value)
$refs[$key] = &$variable[$key];
call_user_func_array(array($stmt, 'bind_param'), $refs);
你需要改变这个:
$variable = array_merge($stringtype, $variable);
$refs = array();
foreach($variable as $key => $value)
$refs[$key] = &$variable[$key];
对此:
$variable = array_combine($stringtype, $variable);
因为array_combine()
通过使用一个数组作为键,另一个数组作为其值来创建数组。
阅读更多:
http://php.net/manual/en/function.array-combine.php
回答有点
晚了,但我在动态添加值时遇到了问题。如果你有 php v +5.6,你可以省略这部分
$variable = array_merge($stringtype, $variable);
// and $refs
call_user_func_array(array($stmt, 'bind_param'), $refs);
并使用...在 +5.6V 中引入的令牌。这是我的情况的完整工作示例:
// establish mysqli connection
$conn = new mysqli(.....);
$tableName = 'users';
// Types to bind
$type = 'isss';
$fields = ['id','name', 'email', 'created'];
$values = [1, 'name', 'email@test.com', '2018-1-12'];
$sql = "INSERT INTO " . $tableName . " (" . join(',', $fields) . ") VALUES (?,?,?,?)";
$stmt = $conn->prepare($sql);
// Using ...token introduced in php v.5.6 instead of call_user_func_array
// This way references can be omitted, like for each value in array
$stmt->bind_param($type, ...$values);
$stmt->execute();
$stmt->close();