37

Here is a snippet from my code:

$stmt = $mysqli->prepare("SELECT DISTINCT model FROM vehicle_types 
    WHERE year = ? AND make = '?' ORDER by model");

$stmt->bind_param('is', $year, $make);

$stmt->execute();

When I echo out the values for $year and $make, I am seeing values, but when I run this script, I get a null value, and the following warning appears in my log file:

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

In this case, year is in the database in type int(10), and I have tried passing a copy that had been cast as an int, and make is a varchar(20) with the utf8_unicode_ci encoding. Am I missing something?

Dharman
  • 30,962
  • 25
  • 85
  • 135
TMorgan
  • 655
  • 1
  • 7
  • 13
  • Earlier question: [Enclosing prepared statement placeholders in single quotes](https://stackoverflow.com/q/12884911/2943403) – mickmackusa Feb 07 '23 at 03:33

1 Answers1

61

Your prepared statement is wrong, it should be:

$stmt = $mysqli->prepare("
    SELECT DISTINCT model FROM vehicle_types WHERE year = ? AND make = ? ORDER by model
");
$stmt->bind_param('is', $year, $make);
$stmt->execute();

When you prepare a statement, you have to substitute every variable with a question mark without quotes. A question mark within quotes will not be recognized as a placeholder.

The number of question marks must be equal to the number of variables in the bind_param()

Dharman
  • 30,962
  • 25
  • 85
  • 135
runspired
  • 2,642
  • 1
  • 19
  • 24