0
I made a function to insert in a list of a JSON, only when it goes to prepare the PDO, replace the values happens an error, I do not see where I am missing.
public function newDeviceList(){
global $app;
$dados = json_decode($app->request->getBody(), true);
$dados = (sizeof($dados)==0)? $_POST : $dados;
$keys = array_keys($dados); //Paga as chaves do array
/*
O uso de prepare e bindValue é importante para se evitar SQL Injection
*/
$keys = array_keys($dados);
for($i = 0; $i < count($dados); $i++) {
$sth = $this->PDO->prepare("INSERT INTO MyTable (".implode(',', $keys).")
VALUES (:".implode(",:", $keys).")");
foreach($dados[$keys[$i]] as $key => $value) {
echo $key . " : " . $value . "<br>";
$sth ->bindValue(':'.$key,$value);
}
$sth->execute();
}
//Retorna o id inserido
$app->render('default.php',["data"=>['MyId'=>$this->PDO->lastInsertId()]],200);
}
Error message:
<strong>Message:</strong> SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
Otherwise put the go-through to go through the array I can normally insert.. when it is just a value without being a list.. it is not global no variable no.
the public keyword is only used in function/variable statements from within a class. Since you are not using a class, you need to remove it from your code.
– ElvisP
And it is bad practice to declare a function variable as global. It is not necessary.
– ElvisP
check your foreach because the error happens when there are more or less parameters compared to bindValue. Or you can disable FOR and FOREACH and do only FOREACH with your INSERT and not use your array_keys from above, perform everything within the same loop.
– ElvisP
Eliseu... thank you. I will try this... I believe it will work..
– Alexandre Amaral
Blaza fera, tamos ae.
– ElvisP