0

I cannot seem to understand why I am getting error: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement
I followed this example:
Passing an array to a query using a WHERE clause
if you have any ideas that would be awesome!

$sql="SELECT pid,title,description,location FROM jobs WHERE status='o'";
if(isset($_POST['category'])){
    $category_filter = join(',', array_fill(0, count($_POST['category']), '?'));
    $sql .= " AND category IN ('.$category_filter.')";
}

$sql.="ORDER BY job_date DESC";
$stmt = $conn->prepare($sql);
$stmt->bind_param(str_repeat('s', count($_POST['category'])), ...$_POST['category']);
$stmt->execute();
$stmt->bind_result($pid,$title,$description,$location);
markusman
  • 73
  • 1
  • 7
  • 1
    You should have mismatched quotes in `$sql .= " AND category IN ('.$category_filter.')";` it should be `$sql .= ' AND category IN ('.$category_filter.')';` – Nick Apr 07 '20 at 01:34
  • wow what the heck? can you please explain that to me? how must that statement be with single quotes, while the first statement and the last does not need to be? – markusman Apr 07 '20 at 01:40
  • I suggest you `echo $sql` in both cases to see what you're actually getting. In your existing code, it's a string with a lot of `?` in it, which is *not* a set of placeholders, hence the `bind_param` error – Nick Apr 07 '20 at 01:42
  • Interesting, with single quotes I get `AND category IN (?,?)ORDER BY` while with double quotes i get `AND category IN ('.?,?.')ORDER BY` – markusman Apr 07 '20 at 01:48
  • how does a double quote make a period in this situation? – markusman Apr 07 '20 at 01:49
  • Note it would have been just as valid to write `$sql .= " AND category IN (".$category_filter.")";` the requirement was just to match the quotes. – Nick Apr 07 '20 at 01:50
  • Because in your existing code there is just one string and the `.`'s are characters in it, not concatenation operators. – Nick Apr 07 '20 at 01:51
  • ohhhh i see, that makes sense now, i never thought about that. thanks! also good tip on echoing the SQL statement, never thought to do that. – markusman Apr 07 '20 at 01:54

0 Answers0