Reputation: 337
I want to create a survey using HTML, PHP, Javascript. So I have my question and answers in a csv file(eventually will be in a SQL server). What I need help is with how can i make my answers radio button(type) so the user can select one of them and I can process it later. The reason i am not hardcoding the questions is because i want to be able to edit them from a file(eventually server).
I have csv file that looks like this:
Question 1,Answer1 A,Answer1 B,Answer1 C,Answer1 D
Question 2,Answer2 A,Answer2 B,Answer2 C,Answer2 D
Now processing it with php the output looks like this:
1. Question 1
Answer1 A
Answer1 B
Answer1 C
Answer1 D
2. Question 2
Answer2 A
Answer2 B
Answer2 C
Answer2 D
The code i used for php is:
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$file = fopen('test.csv','r');
while(($line = fgetcsv($file)) !== FALSE)
{
list($questions[], $optionA[], $optionB[], $optionC[], $optionD[]) = $line;
// print_r($line);
}
fclose($file);
$lengthquestion = count($questions);
$lengthoptionA = count($optionA);
$lengthoptionB = count($optionB);
$lengthoptionC = count($optionC);
$lengthoptionD = count($optionD);
echo '<ol>';
for($i=0; $i<$lengthquestion; $i++)
{
echo '<li><div>';
echo $questions[$i] . '<br />';
echo $optionA[$i] . '<br />';
echo $optionB[$i] . '<br />';
echo $optionC[$i] . '<br />';
echo $optionD[$i] . '<br />';
echo '</div></li>';
}
echo '</ol>';
?>
</body>
</html>
The output i want is, of course radio button on the left
A) Answer1 A
B) Answer1 B
C) Answer1 C
D) Answer1 D
Update to main question:
Addition to the main question which is answered by @maytham:
On my top block of code i added this after php.
<form name="next" action="submit.php" method="post" id='1'>
<input type="submit" value="Submit"/>
</form>
My real question is what should be in brackets ([]). Also can I call length question like that. Here is what i think code will look like:
Here is sumbit.php
<?php
session_start();
$file="FILE.csv";
$fp = fopen($file, "a") or die("could not open");
for($i=0; $i<$lenghtquestion; $i++)
{ $_SESSION["answer' . $i'"] = $_POST["answer' . $i'"];
$data.=$_SESSION["answer' . $i'"].",";
fwrite($fp,$data) or die("could not write"); }
fclose($fp);
This doesn't work though
Upvotes: 1
Views: 359
Reputation: 33397
You can do Radio buttons as group in your for loop
:
for ($i = 0; $i < $lengthquestion; $i ++)
{
echo '<li><div>';
echo $questions[$i] . '<br />';
echo '<input type="radio" name="group' . $i . '" value="' . $optionA[$i] . '">' . $optionA[$i] . '<br />';
echo '<input type="radio" name="group' . $i . '" value="' . $optionB[$i] . '">' . $optionB[$i] . '<br />';
echo '<input type="radio" name="group' . $i . '" value="' . $optionC[$i] . '">' . $optionC[$i] . '<br />';
echo '<input type="radio" name="group' . $i . '" value="' . $optionD[$i] . '">' . $optionD[$i] . '<br />';
echo '</div></li>';
}
Here how it looks like:
Upvotes: 1