Php mysqi bind_param 变量数与准备好的语句中的参数数不匹配

2021-12-25 00:00:00 php mysqli prepared-statement

这一定是新手的错误,但我没有看到.这是我的代码片段:

This has to be a newbie mistake, but I'm not seeing it. Here is a snippet from my code:

$mysqli = mysqli_connect($dbCredentials['hostname'], 
    $dbCredentials['username'], $dbCredentials['password'], 
    $dbCredentials['database']);

if ($mysqli->connect_error) {
    throw new exception( 'Connect Error (' . $mysqli->connect_errno . ') '
    . $mysqli->connect_error);
}

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

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

$stmt->execute();

当我回显 $year 和 $make 的值时,我看到的是值,但是当我运行这个脚本时,我得到一个空值,并且我的日志文件中出现以下警告:

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

在这种情况下,year 在数据库中的类型为 int(10),我尝试传递一个已转换为 int 的副本,而 make 是使用 utf8_unicode_ci 编码的 varchar(20).我错过了什么吗?

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?

推荐答案

你准备好的语句有误,应该是:

Your prepared statement is wrong, it should be:

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

单引号使?是价值而不是标记.它已经是一个字符串,因为您正在使用 bind_param('is'

The single quotes made that ? be the value not a marker. It will already be a string because you are casting as such with bind_param('is'

相关文章