动态绑定参数Php / Mysqli

时间:2015-04-11 04:13:58

标签: php mysqli prepared-statement

您好我合并我的数组并绑定我的参数有一些问题。

  

错误消息=警告:mysqli_stmt :: bind_param():元素数量   在类型定义字符串中与绑定变量的数量不匹配   在.......

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

2 个答案:

答案 0 :(得分:1)

你需要改变这个:

$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

答案 1 :(得分:1)

这是一个迟到的答案,但我遇到动态添加值的问题。 如果您有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();