【问题标题】:Dynamically binding params Php/Mysqli动态绑定参数 Php/Mysqli
【发布时间】:2015-04-11 04:13:58
【问题描述】:

您好,我在合并数组和绑定参数时遇到了一些问题。

错误消息 = 警告: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);

【问题讨论】:

  • print_r($variable); 的输出是什么
  • 数组 ( [0] => s [1] => i [2] => 搜索 [3] => 2000 )
  • $variable = array_merge($stringtype, ... 中的 $stringtype 应该是一个字符串连接在一起的类型。即 implode('', $stringtype)
  • 是的,我试图以某种方式实现这一目标。像这个数组( [0] => si [1] => search [2] => 2000 )

标签: php mysqli prepared-statement


【解决方案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

【讨论】:

    【解决方案2】:

    答案有点晚了,但我在动态添加值时遇到了问题。 如果你有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();
    

    【讨论】:

      猜你喜欢
      • 2012-08-04
      • 2022-01-14
      • 2015-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多