sql错误:mysqli_stmt::bind_param():类型定义字符串中的元素数与绑定变量数不匹配

n1bvdmb6  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(377)

我有以下代码:

$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; 
}

然后我得到一个错误:

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

这就是从报纸上打印出来的 $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
)

有两个,两个变量,我得到的错误是,参数的个数不等于变量的个数。
有什么问题?

fumotvh3

fumotvh31#

在您的例子中,问题是您错误地使用了->bind_param函数。

// 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();

参数可以是以下四种类型之一:
i-整数
d-双
s-字符串
b-水滴
我认为正确的代码应该如下所示:

$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; 
}

相关问题