doukui4836 2014-04-26 22:13
浏览 45
已采纳

动态预准备语句(绑定参数错误)

I'm trying to be able to add parameters to to my prepared statement, query and arrays look right. But the "Number of elements in type definition string doesn't match number of bind variables" error is triggered.

$sql = 'SELECT * FROM `feed` ';
$types = array();
$params = array();

if( isset($_GET['p']) ) {
  $page = $_GET['p'];
}
else {
  $page = 0;
}

if( isset($_GET['q']) ) {
  $sql .= 'WHERE `title` LIKE ? ';
  $search = $_GET['q'];
  array_push($types, 's');
  array_push($params, $search);
}

$sql .= 'ORDER BY `time` DESC LIMIT ?, 6';

array_push($types, 'i');
array_push($params, $page);

$stmt = $mysqli->prepare($sql);
$params = array_merge($types, $params);

$refs = array();
foreach($params as $key => $value)
  $refs[$key] = &$params[$key];

call_user_func_array(array($stmt, 'bind_param'), $refs);

(Printed from the server)

Query: SELECT * FROM feed WHERE title LIKE ? ORDER BY time DESC LIMIT ?, 6

Array merge:

Array
(
    [0] => s
    [1] => i
    [2] => word
    [3] => 0
)

Thanks.

  • 写回答

1条回答 默认 最新

  • duanaiguang1960 2014-04-26 22:28
    关注

    My understanding is that the first parameter 'types' is a string of the types of the parameters, not an array. so the the parameter list for the example should look like:

    Array
    (
        [0] => si
        [1] => word
        [2] => 0
    )
    

    This is untested code: but implode should do what we want from the '$types' array

    $strTypes = implode('', $types);
    

    i will check it later.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?