CodeConnoisseur
CodeConnoisseur

Reputation: 1869

How to retrieve multiple input names into one variable in PHP

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>

Upvotes: 0

Views: 64

Answers (1)

John Conde
John Conde

Reputation: 219804

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.

Upvotes: 3

Related Questions