0

I am following a tutorial which creates a data management system in PHP. I am new to PDO. I am getting an array which says

Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens...in C:\xampp\htdocs\inventory\classes\Employee.php on line 43

This is the function in Employee class which help to insert data to table

// insert data to db
    public function insert($fields){
        // $sql = "INSERT INTO employee (name,city,designation) VALUES (:name, :city, :designation)";


        // array keys return all the keys of an array
        $implodeColumns = implode(',' , array_keys($fields));
        $implodePlaceholder = implode(", :", array_keys($fields));

        $sql = "INSERT INTO employee ($implodeColumns) VALUES (: ".$implodePlaceholder.")";


        $stmt = $this->connect()->prepare($sql);
        foreach ($fields as $key => $value) {
            $stmt->bindValue(":".$key,$value);
        }

        $stmtExec = $stmt->execute();

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

This is my create.php class code which is relevant to take the insert form data from user

<?php
// form data submitted

if (isset($_POST['submit'])) {
 $name = $_POST['name'];
 $city = $_POST['city'];
 $designation = $_POST['designation'];

$fields = [
  'name' => $name,
  'city' => $city,
  'designation' => $designation
  ];


  $employee = new Employee();

  $employee->insert($fields);

}
?>

I am not able to sort out this. But I think the following lines of code may cause the error.

$stmt = $this->connect()->prepare($sql);
            foreach ($fields as $key => $value) {
                $stmt->bindValue(":".$key,$value);
            }
Dharman
  • 30,962
  • 25
  • 85
  • 135
Kash
  • 329
  • 3
  • 15
  • 1
    `VALUES (: "` should be `VALUES (:"` – Nick Feb 16 '20 at 12:19
  • I do not recommend to do it this way. Your code might be vulnerable to SQL injection. If `$fields` array is not constant you might be in trouble. – Dharman Feb 16 '20 at 14:22

0 Answers0