1
I am trying to save the result of this Json in Php but when I enter the answers foreach the data is incorrect in the database.
{"questionario":[{"id_base":"661","id_usuario":"1","id_pesquisa":"29","id_varejo":"265285","respostas":[{"Pergunta":"OS","Resposta":["Windows","Linux","Macintosh OSX"]},{"Pergunta":"Plese select from the list","Resposta":["PHP","C#","Ruby","Shell","Objective-C"]}],"data_inicio":"2018-05-08 09:53:08"}]}
public function saveResult($post) {
$array = $post;
foreach ($array['questionario'] as $value) {
$iduser = $value['id_usuario'];
$idPesquisa = $value['id_pesquisa'];
$idVarejo = $value['id_varejo'];
$idBase = $value['id_base'];
$data_inicio = $value['data_inicio'];
$respostas = $value['respostas'];
foreach($respostas as $val){
$pergunta = $val['Pergunta'];
$resposta = $val['Resposta'];
if(is_array($resposta)){
foreach($resposta as $resp){
$resp;
}
}else{
$resp = $val['Resposta'];
}
try{
$db = Database::conexao();
$qry = "INSERT INTO `resultado`(`id_pesquisa`,`id_varejo`,`id_usuario`,`id_base`,`pergunta`,`resposta`,`data_inicio`)VALUES(
:idPesquisa,
:idVarejo,
:iduser,
:idbase,
:pergunta,
:resposta,
:data_inicio)";
$statement = $db->prepare($qry);
$statement->bindValue(':idPesquisa', $idPesquisa);
$statement->bindValue(':idVarejo', $idVarejo);
$statement->bindValue(':iduser', $iduser);
$statement->bindValue(':idbase', $idBase);
$statement->bindValue(':pergunta', $pergunta);
$statement->bindValue(':resposta', $resp);
$statement->bindValue(':data_inicio', $data_inicio);
$statement->execute();
} catch (PDOException $e){
echo $e->getMessage();
$db->rollBack();
}
}//2 foreach
}//1 foreach
}
Give more details. Which error exactly occurs?
– Wallace Maxters
I added a photo of how it is allocating in the database, occurs that if I have more than one answer to a question my code is saving so and not all answers to all questions.
– Carlos Lopes
Dude, what’s this if checking array with foreach inside?
– Wees Smith
was validating whether the answer was an array but now that I saw that it will always be an array even if it only contains an answer in it
– Carlos Lopes
Yeah, the error should be there, you’re wanting to save the array in the bank
– Wees Smith