0

I have a program where the user can enter the names of there three favorite colors. When it is received by the PHP script I need them to be stored in one variable. If the user enters one color then one color is displayed and entered into the .txt file... if three colors are entered than all three colors are entered into the file etc. Is there a way to receive user input from three separate text fields into one variable? I want them to be displayed in 3 separate fields in an html table.

HTML

<form method="POST" action="colors.php">

<p>Enter Your favorite colors
    <br /><input type="text" name="color1" size="20">
    <br /><input type="text" name="color2" size="20">
    <br /><input type="text" name="color3" size="20">
    </p>

<input type="submit" value="Submit">

</form>

PHP

<table>
<tr>
 $color= $_POST['color'];
 $fp = fopen($filename, 'a');
  $colors .= "<td>".$color1."</td>";
    $colors .= "<td>".$color2."</td>";
    $colors.= "<td>". $color3 ."</td>";
</tr>
</table>
6
  • You should be getting an undefined index notice. Commented Aug 28, 2018 at 0:01
  • I am getting undefined index 'color' Commented Aug 28, 2018 at 0:08
  • and undefined variables Commented Aug 28, 2018 at 0:09
  • Can you offer solutions ? Commented Aug 28, 2018 at 0:24
  • I don't see anything wrong with John's answer. Commented Aug 28, 2018 at 0:43

1 Answer 1

3

Use array notation for the names of your form inputs:

<form method="POST" action="colors.php">

<p>Enter Your favorite colors
<br /><input type="text" name="color[]" size="20">
<br /><input type="text" name="color[]" size="20">
<br /><input type="text" name="color[]" size="20">
</p>

<input type="submit" value="Submit">

</form>

In PHP you will then receive an array of values. Just loop through it like you would any array:

<table>
<tr>
<?php
 foreach ($_POST['color'] as $color) {
   echo "<td>".$color."</td>";
 }
</tr>
</table>

Keep in mind that you shouldn't trust user data and should sanitize and escape it as necessary.

Sign up to request clarification or add additional context in comments.

3 Comments

this works well but how do I get them to be inserted into separate <td> tags in an html table?
Will modify my question, I apologize.
It's just an array. Loop through them using foreach like you would any array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.