gpt4 book ai didi

php - SQL 错误:mysqli_stmt::bind_param():类型定义字符串中的元素数量与绑定(bind)变量的数量不匹配

转载 作者:行者123 更新时间:2023-11-29 06:42:49 24 4
gpt4 key购买 nike

我有以下代码:

$conn = new mysqli($DB, $username, $password, $dbname); 

if($condition == 'con1'){
$sql = "UPDATE users SET con1=? WHERE name=?";
}elseif($condition == 'con2'){
$sql = "UPDATE users SET con2=? WHERE name=?";
}elseif($condition == 'con3'){
$sql = "UPDATE users SET con3=? WHERE name=?";
}

if($query = $conn->prepare($sql)) {
$query->bind_param($value,$name);
$query->execute();

print_r($query);

} else {
$error = $conn->errno . ' ' . $conn->error;
echo $error;
}

然后我得到了这个错误:

Warning:  mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables on line 32

这就是从 $query 打印的内容:

mysqli_stmt Object
(
[affected_rows] => -1
[insert_id] => 0
[num_rows] => 0
[param_count] => 2
[field_count] => 0
[errno] => 2031
[error] => No data supplied for parameters in prepared statement
[error_list] => Array
(
[0] => Array
(
[errno] => 2031
[sqlstate] => HY000
[error] => No data supplied for parameters in prepared statement
)

)

[sqlstate] => HY000
[id] => 1
)

有 2 个? ,和 2 个变量,我收到错误消息,指出参数数量不等于变量数量。

问题是什么?

最佳答案

在您的案例中,问题是您错误地使用了 ->bind_param 函数。

// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email); // sss means string string string

// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();

参数可以是以下四种类型之一:

  • i - 整数
  • d - 双
  • s - 字符串
  • b - BLOB

我相信正确的代码应该如下所示:

$conn = new mysqli($DB, $username, $password, $dbname); 

// You can avoid this structure, by doing concatenation!!!**
if($condition == 'con1'){
$sql = "UPDATE users SET con1=? WHERE name=?";
}elseif($condition == 'con2'){
$sql = "UPDATE users SET con2=? WHERE name=?";
}elseif($condition == 'con3'){
$sql = "UPDATE users SET con3=? WHERE name=?";
}

if($query = $conn->prepare($sql)) {
$query->bind_param("ss", $con, $name);
$con = 'yourNeededValue';
$name = 'someName?';
$query->execute();

} else {
$error = $conn->errno . ' ' . $conn->error;
echo $error;
}

关于php - SQL 错误:mysqli_stmt::bind_param():类型定义字符串中的元素数量与绑定(bind)变量的数量不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50842237/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com