Monday, 30 September 2013

Data insertion using array in PHP

Data insertion using array in PHP

I have a php script for conducting online test. while taking test, I am
using post method to get the answers in the action page.The answers are
passed as an array with question id and the selected option value(true or
false/the answers the candidate entered like that).Then I have to insert
the answers marked by the candidate in the database. The code is as shown
below:
$student_id=$_POST['name'];
$survey_id=$_POST['survey_id'];
$store = array();
if (isset($_POST['question_id'])) {
foreach ($_POST['question_id'] as $key => $option) {
$option1 = array_filter($option);
print_r($option1);
if (count($option1) > 1) {
$option2 = implode("^", $option1);
$store[] = $option2;
} else {
$value = $option1;
$i = implode(null, $option1);
$store[] = $i;
}
}
print_r($store);
}
$t = new DateTime();
$t->setTimestamp($time = time());
$t->setTimeZone(new DateTimeZone("Asia/Singapore"));
$date = $t->format(DateTime::RFC850);
$SQL = "INSERT INTO answer_table(student_id ,survey_id, ans_1, ans_2,
ans_3, ans_4, ans_5, ans_6, ans_7, ans_8, ans_9, ans_10, timestamp)
VALUES ('$student_id','$survey_id', '$store[0]', '$store[1]',
'$store[2]', '$store[3]', '$store[4]', '$store[5]', '$store[6]',
'$store[7]', '$store[8]', '$store[9]', '$date')";
$result = mysql_query($SQL);
If the student answers the test in sequential order(from question number 1
to 10) the code works fine. But when the candidate answers in random
manner(first 10 then 5 like that),the table field named,ans_1 will get
inserted with answer of question number 10. I need to insert fields with
corresponding answers ,(ans_1 with answer of question 1 like that) what
ever pattern,the candidate takes test.
Can anyone help me to solve this issue. Thanks in advance.

No comments:

Post a Comment