Inserting session array into mysql database

I am still learning bits of PHP and have been stuck on this issue regarding the POST data from radio buttons within a form being inserted into a mysql database from a session array. Currently, I have 2 questions within my survey and they consist of radio button options for a user to select from. The relevant answers can be selected and they are stored in a session array:

array(1) { ["choice"]=> array(2) { [0]=> string(11) "56-65 years" [1]=> string(17) "Prefer not to say" } }

However I was not too sure if the array should be as such. The two answers chosen from the radio options in the above example are "56-65 years" and "Prefer not to say".

Following on from the session array, I am trying to insert each of those answers in to a mysql database. I have a column created to insert each answer (i.e. there are two columns (question 1 and question 2) to store the two answers from the example above).

I am aware that my code is open to SQL injection and plan on fixing that after overcoming the inserting of data.

Question.php

     <form method="POST" action="process.php">
      <ul class="choices">
  &lt;?php while($row = $answers-&gt;fetch_assoc()):?&gt;
    &lt;li&gt;&lt;input type="radio" name="choice" value="&lt;?php echo $row['answerText']; ?&gt;"&gt;

    &lt;?php echo $row['answerText'] ?&gt;&lt;/li&gt;
    &lt;?php endWhile; ?&gt;

  &lt;/ul&gt; 
  &lt;input type="submit" name="submit" value="Next Question"&gt;
  &lt;input type="hidden" name="number" value="&lt;?php echo $number; ?&gt;"&gt;

</form>

Process.php

<?php

    if(isset($_POST['submit'])){

$number = $_POST['number'];
$next = $number+1;

$selected_choice = $_POST['choice'];
$_SESSION['choice'][] = $selected_choice;

foreach ($_SESSION[‘choice’] as $key) {

$user_responses = $key;

}

$insertdata = “INSERT INTO userAnswersTable(‘question1’, ‘question2’) VALUES ($_SESSION[‘choice’])”;
$resulting = $mysqli->query($insertdata) or die($mysqli->error.LINE);

}
?>

I would expect each of the user responses to be in an array from which each individual selected choice within the session array can be stored in each corresponding column within the mySql table. Any suggestions would be very helpful.

#php #mysql #database

2 Likes49.85 GEEK