Search code examples
phpmysqlibindparam

bind_param(): Number of variables doesn't match number of parameters in prepared statement


Basically the problem is I have a column of dates in my database table and I want to count the number of each particular date and have it stored in an array.I've busted my head around this problem for a week and so far I've come up with this.

<?php

function vref($arr) {
 if (strnatcmp(phpversion(),'5.3') >= 0) {
  $refs = array();
  foreach($arr as $key => $value) $refs[$key] = &$arr[$key];
  return $refs;
 }
 return $arr;
}

$mysqli = new mysqli("localhost", "root","" , "ti_project");

$bind = 'sssss';
$feedbackdate = array($bind);

$query = "SELECT dateTime FROM feedback";
$result = $mysqli->prepare($query);
$result->execute();
$result->bind_result($Date);
while ($result->fetch()){
    $feedbackdate[] = array($Date);
}

$rawQuery = 'SELECT COUNT(*) FROM feedback WHERE dateTime IN (';
$rawQuery .= implode(',',array_fill(0,count($feedbackdate),'?'));
$rawQuery .= ')';

$stmt = $mysqli->prepare($rawQuery);
call_user_func_array(array($stmt,'bind_param'),vref($feedbackdate));
$stmt->execute();
$stmt->bind_result($count);

while ($stmt->fetch()) {
    printf ("%s\n", $count);
}

?>

But here I get the error

mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement.

So how to do this?


Solution

  • I am not sure why you need to do two queries to get the result set you are looking for. This query will group the results by date and count them:

    SELECT dateTime, COUNT(*) FROM feedback GROUP BY dateTime;
    

    This will output something like:

    +-----------------------+-------+
    | dateTime              | count |
    +-----------------------+-------+
    |2016-01-25 00:00:00    | 1     |
    |2016-01-24 00:00:00    | 2     |
    +-----------------------+-------+
    

    Is that the type of data you are after?