简体   繁体   中英

SQL error :mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables

I have the following code:

$conn = new mysqli($DB, $username, $password, $dbname); 

if($condition == 'con1'){
    $sql = "UPDATE users SET con1=? WHERE name=?";  
}elseif($condition == 'con2'){
    $sql = "UPDATE users SET con2=? WHERE name=?";  
}elseif($condition == 'con3'){
    $sql = "UPDATE users SET con3=? WHERE name=?";  
}

if($query = $conn->prepare($sql)) { 
    $query->bind_param($value,$name);
    $query->execute();

    print_r($query);

} else {
    $error = $conn->errno . ' ' . $conn->error;
    echo $error; 
}

Then I get that error:

Warning:  mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables on line 32

That's what get printed from the $query :

mysqli_stmt Object
(
[affected_rows] => -1
[insert_id] => 0
[num_rows] => 0
[param_count] => 2
[field_count] => 0
[errno] => 2031
[error] => No data supplied for parameters in prepared statement
[error_list] => Array
    (
        [0] => Array
            (
                [errno] => 2031
                [sqlstate] => HY000
                [error] => No data supplied for parameters in prepared statement
            )

    )

[sqlstate] => HY000
[id] => 1
)

There are 2 ? , and 2 variables and I get that error saying that number of params not equal to number of variables.

What is the problem?

In your case problem, is that you use ->bind_param function incorrectly.

// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email); // sss means string string string

// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();

The argument may be one of four types:

  • i - integer
  • d - double
  • s - string
  • b - BLOB

I believe the right code should be like following:

$conn = new mysqli($DB, $username, $password, $dbname); 

// You can avoid this structure, by doing concatenation!!!**
if($condition == 'con1'){
    $sql = "UPDATE users SET con1=? WHERE name=?";  
}elseif($condition == 'con2'){
    $sql = "UPDATE users SET con2=? WHERE name=?";  
}elseif($condition == 'con3'){
    $sql = "UPDATE users SET con3=? WHERE name=?";  
}

if($query = $conn->prepare($sql)) { 
    $query->bind_param("ss", $con, $name);
    $con = 'yourNeededValue';
    $name = 'someName?';
    $query->execute();

} else {
    $error = $conn->errno . ' ' . $conn->error;
    echo $error; 
}

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