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