Home >Backend Development >PHP Tutorial >Why Does `mysqli_stmt::bind_result()` Throw a 'Mismatched Bind Variables' Error?

Why Does `mysqli_stmt::bind_result()` Throw a 'Mismatched Bind Variables' Error?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-11 13:09:11634browse

Why Does `mysqli_stmt::bind_result()` Throw a

mysqli_stmt::bind_result(): Mismatched Bind Variables vs. Prepared Statement Fields

Question:

When attempting to execute a prepared statement with mysqli_stmt, I encounter the error: "mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement." Why am I receiving this error?

Code Example:

$mysqli = new mysqli("localhost", "root", "", "security");

$stmt = $mysqli->prepare("SELECT username AND password FROM users WHERE username = ?");
$username = $_POST['name'];
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($password, $username);
$stmt->fetch();

Answer:

The error you are encountering occurs when the number of variables specified in bind_result() does not match the number of columns returned by the prepared statement query. In your example, you are attempting to bind two variables to a query that returns only one column.

To resolve this issue, the query should be written in the correct format for the operation. The proper syntax for selecting multiple fields is to separate them by commas, not AND:

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

Once the query is corrected, the bind_result() method can be used to correctly bind the variables to the result:

$stmt->bind_result($username, $password);

The above is the detailed content of Why Does `mysqli_stmt::bind_result()` Throw a 'Mismatched Bind Variables' Error?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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