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 ??

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
hany
  • 49
  • 1
  • 10
  • Sorry I'm not sure I understand the problem. Can you give an example of how an incorrect row is appearing. – Ukuser32 Mar 14 '16 at 10:58
  • 1
    Your code is vulnerable to [SQL Injection](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – RiggsFolly Mar 14 '16 at 11:01
  • Can you explain a little more what you mean when you say _but the other records only contain the value of the field related to the array i loop through and the other fields are empty_ – RiggsFolly Mar 14 '16 at 11:05
  • Did you check that the user has entered _all 3 fields_ for each occurance before running this update? – RiggsFolly Mar 14 '16 at 11:06
  • He is overriding the values of his array in the first three lines of the foreach.. Of course he cannot access the considered keys and gets empty result in later loops – Simon Kraus Mar 14 '16 at 11:07

1 Answers1

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);
}
Simon Kraus
  • 736
  • 4
  • 14
  • 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. – Simon Kraus Mar 14 '16 at 11:09