0

i have three fields

<textarea rows="2" name="answer[]" ></textarea>
<select name="fraction[]">...
<textarea rows="2" name="feedback[]"></textarea>

the user should fill this fields more than one time at least four times then i use php to loop through this fields to insert it in database

$answer = isset($_POST['answer']) ? $_POST['answer'] : "" ;
$fraction = isset($_POST['fraction']) ? $_POST['fraction'] : "" ;
$feedback = isset($_POST['feedback']) ? $_POST['feedback'] : "" ;

foreach($answer as $key=>$value){
    $answer = $value;
    $fraction = $fraction[$key];
    $feedback = $feedback[$key];
    $query = "insert into `question_answer` ( answer, fraction, feedback) values ('$answer', '$fraction','$feedback')";
    $questions->insertData($query,$con);
}

this insert number of records , the first record contain all values as i want but the other records only contain the value of the field related to the array i loop through and the other fields are empty..any help ??

5

1 Answer 1

2

You overwrite your variables in the first loop... Take this:

$answer = isset($_POST['answer']) ? $_POST['answer'] : "" ;
$fraction = isset($_POST['fraction']) ? $_POST['fraction'] : "" ;
$feedback = isset($_POST['feedback']) ? $_POST['feedback'] : "" ;

foreach($answer as $key=>$value){
    $query = "insert into `question_answer` ( answer, fraction, feedback) values ('$value', '$fraction[$key]','$feedback[$key]')";
    $questions->insertData($query,$con);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Of course the OP should prevnet SQL Injections too and make sure the user entered all data so that there is no answer without feedback or so.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.