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);
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 = ?");
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);
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!