Home > Backend Development > PHP Tutorial > Why Does My MySQLi Prepared Statement Throw a 'Number of bind variables doesn't match number of fields' Error?

Why Does My MySQLi Prepared Statement Throw a 'Number of bind variables doesn't match number of fields' Error?

Patricia Arquette
Release: 2024-12-15 21:30:26
Original
241 people have browsed it

Why Does My MySQLi Prepared Statement Throw a

Mismatched Bind Variables in MySQLi Prepared Statement

When attempting to implement a login form using a prepared statement in PHP, some developers encounter the frustrating error: "mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement."

This error arises when the SQL query and the bind_result() function contain a mismatch in the number of fields being selected and assigned to variables. Let's examine how to address this issue based on the provided code.

In the provided code:

$stmt = $mysqli->prepare("SELECT username AND password FROM users WHERE username = ?");
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($password, $username);
Copy after login

The issue lies in the SQL query. The "AND" keyword is used instead of a comma when selecting multiple fields. The correct syntax for selecting multiple fields is to separate them with a comma:

$stmt = $mysqli->prepare("SELECT username, password FROM users WHERE username = ?");
Copy after login

Additionally, the bind_result() function should match the number of selected fields. In this case, two fields are selected, so the bind_result() function should have two variables:

$stmt->bind_result($username, $password);
Copy after login

By correcting the select syntax and aligning the bind_result() function with the number of selected fields, the issue of mismatched bind variables will be resolved, allowing the login form to function correctly.

The above is the detailed content of Why Does My MySQLi Prepared Statement Throw a 'Number of bind variables doesn't match number of fields' Error?. 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