简体   繁体   中英

Binding parameter to mysqli database query

I'm getting this:

Warning: mysqli_stmt_bind_result() [function.mysqli-stmt-bind-result]: Number of bind variables doesn't match number of fields in prepared statement

I've defined $id and $link above this in my code, and have no trouble connecting to the database.

$query = "select * from tablename where id = ?";

if ($stmt = mysqli_prepare($link, $query)) {
    mysqli_stmt_bind_param($stmt, 'i', $id);
    //execute statement
    mysqli_stmt_execute($stmt);
    // bind result variables
    mysqli_stmt_bind_result($stmt, $first, $last);
    // fetch values
    mysqli_stmt_fetch($stmt);
    echo "$first $last<br>";
    // close statement
    mysqli_stmt_close($stmt);
}

It seems to me that the query only has one '?', so it should only need one (integer typed) value to fill in, which I think I'm supplying with $id. Help?

You have to put each column name in your SELECT rather than use the * wildcard, Documentation .

Example

SELECT `FirstName`,`LastName` FROM `tablename` WHERE `id` = ?

The error said Number of bind variables doesn't match number of fields in prepared statement .

In line mysqli_stmt_bind_result($stmt, $first, $last); you're trying to bind two variables ( $first and $last ) to $stmt . But the amount of selected variables from the database has to be equal to the amount of variables you're trying to assing to $stmt . You can do that as stated above.

Side Note: I recommend quoted `tables` and `columns` names with backticks ` .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM