Neik0
Neik0

Reputation: 103

PHP How to send multiple values within the same name

So here is my current code. This code has 6 inputs within the form. The names on the last 3 inputs are. firstanswer, secondanswer and thirdanswer.

<form action="addsurvey.php" method="post">
  <input type="text" name="surveyname">
  <input type="text" name="question" placeholder="First Question">
  <br>
  <input type="text" name="firstanswer" value="">
  <input type="text" name="secondanswer" value="">
  <input type="text" name="thirdanswer" value="">
  <br>
  <input type="submit" name="submit">
</form>

When they get submitted the php file I set the variables like this.

$firstanswer = $_POST['firstanswer'];
$secondanswer = $_POST['secondanswer'];
$thirdanswer = $_POST['thirdanswer'];

$answers = array();

array_push($answers, $firstanswer);
array_push($answers, $secondanswer);
array_push($answers, $thirdanswer);

This code would make sense if I knew every single user was going to only enter in three possible answers for their form. But I do not know for sure. Is there a way I can use the same name on the last three inputs and send them into some sort of array for example.

<form action="addsurvey.php" method="post">
  <input type="text" name="surveyname">
  <input type="text" name="question" placeholder="First Question">
  <br>
  <input type="text" name="answer" value="">
  <input type="text" name="answer" value="">
  <input type="text" name="answer" value="">
  <br>
  <input type="submit" name="submit">
</form>

Then in the php it would be pushed onto an array. To recap. I want to be able to use the same name for the inputs to then add into an array.

Upvotes: 0

Views: 2788

Answers (2)

Badrinath
Badrinath

Reputation: 491

There is an array name in html 'name'. You can use the array for the all input with the same name, so as i can understand you need below

    <form action="addsurvey.php" method="post">
        <input type="text" name="surveyname">
        <input type="text" name="question" placeholder="First Question">
        <br>
        <input type="text" name="answer[]" value="">
        <input type="text" name="answer[]" value="">
        <input type="text" name="answer[]" value="">
        <br>
        <input type="submit" name="submit">
    </form>

it will solve the issue you have.

Upvotes: 1

JSowa
JSowa

Reputation: 10572

Send inputs as array answer. Then you will have these values in array variable $_POST['answer'] with corresponding IDs or you can send without IDs and then type name="answer[]".

<form action="addsurvey.php" method="post">
  <input type="text" name="surveyname">
  <input type="text" name="question" placeholder="First Question">
  <br>
  <input type="text" name="answer[1]" value="">
  <input type="text" name="answer[2]" value="">
  <input type="text" name="answer[3]" value="">
  <br>
  <input type="submit" name="submit">
</form>

Upvotes: 4

Related Questions