PDO无效参数编号

问题描述 投票:0回答:1

我已经创建了将此函数插入​​数据库并将其插入数据库,但是会抛出警告:

无效的参数编号:绑定变量的数量与令牌的数量不匹配

代码:

$first = (rand(1, 100));
$second = (rand(1, 100));
$last = $first + $second;
$stmt = $connection->prepare("
INSERT INTO equations (first_number, second_number, operation, result) 
VALUES (:first_number, :second_number, :operation, :result)
");

$stmt->bindParam(':first_number',$first, PDO::PARAM_INT);
$stmt->bindParam(':second_number',$second, PDO::PARAM_INT);

if ($last <= 100) {

    $stmt->bindParam(':result', $last, PDO::PARAM_INT);
    $stmt->bindValue(':operation', "+", PDO::PARAM_STR);

} else if ($first > $second) {

    $second_result = $first - $second;
    $stmt->bindParam(':result', $second_result, PDO::PARAM_INT);
    $stmt->bindValue(':operation', "-", PDO::PARAM_STR);
}
$stmt->execute();
php pdo
1个回答
0
投票

您的条件并不能保证所有参数都始终绑定。例如:

$second=80; 
$first=70;

在这种情况下,:result:operation不受限制,因为$last大于100而$first小于$second。我建议编辑您的代码以涵盖其余条件:

if ($last <= 100) {
    $stmt->bindParam(':result', $last, PDO::PARAM_INT);
    $stmt->bindValue(':operation', "+", PDO::PARAM_STR);
} else if ($first > $second) {
    $second_result = $first - $second;
    $stmt->bindParam(':result', $second_result, PDO::PARAM_INT);
    $stmt->bindValue(':operation', "-", PDO::PARAM_STR);
} else {
    // this else will cover the rest
    $other_result = ... // do your magic here
    $stmt->bindParam(':result', $other_result, PDO::PARAM_INT);
    $stmt->bindValue(':operation', "other", PDO::PARAM_STR);
}
© www.soinside.com 2019 - 2024. All rights reserved.