Reputation: 127
I am working on a simple survey where users are presented with a website with a number of questions in a form.
The questions are stored in a database and not "hardcoded" because in the future I'd like to be able to present different users with different questions or maybe even randomize which questions are shown.
My database structure for questions looks like this:
table: questions
id q_eng
1 Satisfied?
2 Happy?
3 Sad?
And this is how I would like to store the answers:
table: answers
id timestamp question answer
1 2016-02-17 Satisfied? yes
2 2016-02-17 Happy? yes
3 2016-02-17 Sad? no
4 2016-02-18 Satisfied? no
5 2016-02-18 Happy? no
6 2016-02-18 Sad? yes
I am using my stored questions to populate my form in php, like this:
$sql = "SELECT DISTINCT q_eng FROM questions WHERE id = 1";
$result = $con->query($sql);
$row = mysqli_fetch_array($result);
echo "<div class='header'>". $row['q_eng'] ."</div>";
echo "<div class='questions'>";
echo "<input type='radio' name='". $row['q_eng'] ."' id='satisfied_yes value='yes'>";
echo "<label for='satisfies_yes'><img src='satisfied.png' width='15%'></label>";
echo "<input type='radio' name='". $row['q_eng'] ."' id='satisfied_no' value='no'>";
echo "<label for='satisfied_no'><img src='notsatisfied.png' width='15%'></label>";
echo "</div>";
// code repeating for question 2 and question 3 using id = 2 and id = 3.
The trouble I am now having is constructing the correct while loop for saving the different questions and answers.
// checks if form has been submitted
if (!empty($_POST)) {
// fetches distinct questions from database
$sql = "SELECT DISTINCT q_eng FROM questions";
$result = $con->query($sql);
// starts loop for each distinct value to save distinct values
while ($row = mysqli_fetch_array($result)) {
// tries to save the value for each question (yes or no)
// this is not working, maybe due to some syntax error.
// echoing $answer displays nothing.
$answer = $_POST[$row["q_eng"]];
// saves the values. seems to be working fine
$query = "INSERT INTO answers VALUES ('',now(),'".$row['q_eng']."','$answer')";
mysqli_query($con,$query);
}
}
Now, I am 99% sure my error is in this line, but I have not been able to work out whether there's some simple syntax error or whether I am trying to do something that's not supposed to work?
$answer = $_POST[$row["q_eng"]];
Any help you can offer is much appreciated.
Upvotes: 0
Views: 38
Reputation: 161
you need to change your insert statement:
$query = "INSERT INTO answers VALUES ('',now(),'".$row['q_eng']."','" . $answer . "')";
Sorry, i just saw you don't have a <form>
Tag in your code. Is $_POST
even filled?
Upvotes: 1