I am trying to execute a dynamic array of values with PDO, here is my PHP code:
protected function insertData($data, $table) {
$db = $this->getDB();
$columns = '';
$params = '';
$values = '';
// Retrieves columns, their respective value and params.
$i = 0;
foreach($data as $col => $val) {
$i++;
$columns .= $i != count($data) ? "`$col`, " : "`$col`";
$params .= $i != count($data) ? "?, " : "?";
$values .= $i != count($data) ? "'$val', " : "'$val'";
}
$query = "INSERT INTO $table ($columns) VALUES ($params)";
$prepQuery = $db->prepare($query);
return $prepQuery->execute([$values]);
}
When I execute this code, I get this error : "Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in".
I know the issue is that $prepQuery->execute([$values])
actually does $prepQuery->execute(["'val1', 'val2', 'val3'..."])
instead of what I wanna do which is $prepQuery->execute(['val1', 'val2', 'val3'...])
but I don't know how to fix it...
How can I execute a dynamic array of values with PDO? The method is generic.
Thanks in advance, I hope I was clear enough. :/