首页  >  文章  >  后端开发  >  为什么我在 MySQLi 准备好的语句中收到“绑定变量数量不匹配”错误?

为什么我在 MySQLi 准备好的语句中收到“绑定变量数量不匹配”错误?

Patricia Arquette
Patricia Arquette原创
2024-10-27 19:31:30645浏览

Why Am I Getting

准备语句插入中绑定变量的数量不匹配

使用MySQLi准备语句执行INSERT语句时,用户可能会遇到错误:“绑定变量的数量与准备好的语句中的字段数量不匹配。”

当bind_param()方法中提供的绑定变量的数量与INSERT查询中的占位符的数量不一致时,就会出现此问题。例如,考虑下面的代码片段:

if($stmt = $conn->prepare("INSERT INTO login(user, pass) VALUES(?, ?)")) {

  /* Bind parameters s - string, b - blob, i - int, etc */
  $stmt->bind_param("ss", $user, $pw);

  /* Execute it */
  $stmt->execute();

  /* Bind results */
  $stmt->bind_result($user, $pw);

  /* Close statement */
  $stmt->close();
  $userId = $conn->insert_id;
}

在此代码中,INSERT 语句有两个占位符 (?):一个用于用户,一个用于通行证。但是,bind_param() 方法将两个变量($user、$pw)绑定到占位符。这会导致不匹配错误。

解决方案是删除 bind_result() 方法调用,因为 INSERT 语句不返回任何结果。下面更新的代码正确地将数据插入表中:

if($stmt = $conn->prepare("INSERT INTO login(user, pass) VALUES(?, ?)")) {

  /* Bind parameters s - string, b - blob, i - int, etc */
  $stmt->bind_param("ss", $user, $pw);

  /* Execute it */
  $stmt->execute();

  /* Close statement */
  $stmt->close();
  $userId = $conn->insert_id;
}

以上是为什么我在 MySQLi 准备好的语句中收到“绑定变量数量不匹配”错误?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn