-1

Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined on line 73.

What is this error ?

$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');
    }
}
tereško
  • 58,060
  • 25
  • 98
  • 150
chan
  • 15
  • 1
  • 6

1 Answers1

0

There are some syntax errors. Like no space after SET and before WHERE keyword. I have added and updated your code.

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');
    }
}
Lovepreet Singh
  • 4,792
  • 1
  • 18
  • 36
  • You never reset `$sql`, not that this will be much of an issue in this function as it;s one use, but overall, it's best practice to reset the variable for use. I.e.; `$sql .= "UPDATE ...`, this is always appending, and to a variable that technically doesn't exist in the scope as you don't declare it – Can O' Spam Jul 05 '18 at 08:43
  • You are right. I missed that. – Lovepreet Singh Jul 05 '18 at 08:45
  • I also have a large issue with "*Try this*" type answers, they don't really help as the OP may not see what you've changed - please add explanation so this is clear for the OP and future readers as to what you changed / why – Can O' Spam Jul 05 '18 at 08:45