Why Am I Getting \'Number of Bind Variables Mismatch\' Error in MySQLi Prepared Statements?

Patricia Arquette
Release: 2024-10-27 19:31:30
Original
644 people have browsed it

Why Am I Getting

Number of Bind Variables Mismatch in Prepared Statement Insertion

When executing an INSERT statement using MySQLi prepared statements, users may encounter the error: "Number of bind variables doesn't match number of fields in prepared statement."

This issue arises when the number of bind variables provided in the bind_param() method does not align with the number of placeholders in the INSERT query. For example, consider the code snippet below:

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;
}
Copy after login

In this code, the INSERT statement has two placeholders (?): one for the user and one for the pass. However, the bind_param() method is binding two variables ($user, $pw) to the placeholders. This results in the mismatch error.

The solution is to remove the bind_result() method call since the INSERT statement does not return any results. The updated code below correctly inserts data into the table:

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;
}
Copy after login

The above is the detailed content of Why Am I Getting \'Number of Bind Variables Mismatch\' Error in MySQLi Prepared Statements?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!