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.

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top