mysqli_stmt::bind_result() Error: Matching Bind Variables with Prepared Statement Fields
When attempting to utilize a prepared statement for a login mechanism in PHP, you may encounter the error: "mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement." This indicates a discrepancy between the number of variables you are binding in your results and the number of fields expected by the prepared statement.
Incorrect Code and Analysis:
The provided code demonstrates the issue:
$stmt = $mysqli->prepare("SELECT username AND password FROM users WHERE username = ?"); $stmt->bind_param('s', $username); $stmt->execute(); $stmt->bind_result($password, $username);
The error arises because the "AND" keyword has been used incorrectly in the SELECT clause. Instead of separating the fields with "AND," you should use a comma.
Correct Code and Explanation:
To resolve this error, modify the SELECT clause as follows:
$stmt = $mysqli->prepare("SELECT username, password FROM users WHERE username = ?");
With this modification, the prepared statement now expects two fields to be returned: username and password. You can then safely bind two variables to them using mysqli_stmt::bind_result().
$stmt->bind_result($username, $password);
By ensuring that the number of bind variables matches the number of fields in the prepared statement, you can prevent the "Number of bind variables doesn't match number of fields in prepared statement" error.
The above is the detailed content of Why Does `mysqli_stmt::bind_result()` 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!