Foreach and Mysql

Asked

Viewed 74 times

2

Dear colleagues.

I am bringing two questions from the Mysql database, of which the user will register the respective questions. See:

....
<input type="hidden" name="Pergunta[]" value="<?php echo $idPergunta; ?>">
Pergunta: <?php echo $jmPerguntas->Perguntas; ?><br>
Resposta: <input type="text" name="Respostas[]" class="formRespostas">
....

To redeem the answer value I am using the foreach, but how do I know which answer refers to which question?

foreach($respostas as $resposta){
      $sqlCadastrar = mysqli_query($conexao, "INSERT INTO respostas VALUES(null,".$pergunta.",".$usuario.",'".$resposta."',NOW())");         
    }
  • 1

    I don’t understand what the problem is.

  • @Jose.Marcos, you can paste the generated HTML instead of PHP into the first block?

  • His doubt is related to the return of the data, when he already has the list of answers, but he wants to know how he knows which answer is of which question :)

  • @Maiconcarraro as you understood it from there?

  • @Jorgeb. By his logic is 1 answer to 1 question, not multiple-choice, so no for of it is very strange he iterate $respostas passing a $pergunta in Insert, so what I said is the only hypothesis.

  • @Maiconcarraro very well seen, but it is better to wait for the AP to be sure...

  • That’s about it. I have two questions that were registered in the database. Ex.: Who discovered Brazil? Who discovered America? The user will answer the questions, but I need to enter the questions and their answers in the database. I’m trying to use foreach(), but I was only able to register the answers correctly, but the questions did not.

  • I managed to solve it. I want to thank the colleagues who tried to help me. How do I post the solution? I can answer my own question?

Show 3 more comments

1 answer

1


I managed to solve it. Follow below:

for($i = 0; $i < count($_POST['Pergunta']); $i++){
     $sqlCadastrar = mysqli_query($conexao, "INSERT INTO respostas VALUES(null,".$_POST['Pergunta'][$i].",".$usuario.",'".$_POST['Respostas'][$i]."',NOW())");     
}

 ....
<input type="hidden" name="Pergunta[]" value="<?php echo $idPergunta; ?>">
Pergunta: <?php echo $jmPerguntas->Perguntas; ?><br>
Resposta: <input type="text" name="Respostas[]" class="formRespostas">
....

Thank you all!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.