未捕获的PDOException:SQLSTATE [HY093]:无效的参数编号:参数未定义

时间:2018-07-05 08:34:19

标签: php mysql pdo

  

未捕获的PDOException:SQLSTATE [HY093]:无效的参数编号:在第73行上未定义参数。

这是什么错误?

$stmtExec = $stmt->execute(); // the line 73

Employee.php

public function update($fields,$id){
    $st = "";
    $counter = 1;
    $total_fields = count($fields);
    foreach ($fields as $key => $value) {
        if ($counter === $total_fields) {
            $set = "$key = :".$key;
            $st = $st.$set;
        } else{
            $set = "$key = :".$key.",";
            $st = $st.$set;
            $counter++;
        }
    }

    $sql = "";
    $sql.= "UPDATE info SET".$st;
    $sql.= "WHERE id =".$id;

    $stmt = $this->connect()->prepare($sql);

    foreach ($fields as $key => $value) {
        $stmt->bindValue(':'.$key, $value);
    }

    $stmtExec = $stmt->execute(); // here is the line with the error

    if ($stmtExec) {
        header('Location:index.php');
    }
}

1 个答案:

答案 0 :(得分:0)

存在一些语法错误。就像SET之后和WHERE关键字之前没有空格一样。我已经添加并更新了您的代码。

public function update($fields, $id) {
    $st = "";
    $counter = 1;
    $total_fields = count($fields);
    foreach ($fields as $key => $value) {
        if ($counter === $total_fields) {
            $st .= "$key = :" . $key;
        } else {
            $st .= "$key = :" . $key . ",";
            $counter++;
        }
    }
    $sql = "UPDATE info SET " . $st . " WHERE id =" . $id;

    $stmt = $this->connect()->prepare($sql);

    foreach ($fields as $key => $value) {
        $stmt->bindValue(':' . $key, $value);
    }

    $stmtExec = $stmt->execute();

    if ($stmtExec) {
        header('Location:index.php');
    }
}