简体   繁体   中英

Form: make a loop to save different value of a same field name

I do a form, inside I would like to do a loop for to show the same field. Each field will have different value and I would like to use sessions to take all the value.

Here is my code:

for ($i = 1; $i <= 5; $i++) { //normally not 5 but a random number, choose by user
     echo "Numero ";
     echo $i;
?>      
<input type="text" name="number2" id="number2"/>    
<?php
}
?>
</form>
<?php
echo $_POST['number2'];
$my_array=array($_POST['number2']);
    $_SESSION['countnumb']=$my_array;

in another page:

foreach($_SESSION['countnumb'] as $key=>$value)
{
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
}

I can't register any number. How can I do this? thanks

Basics First - ids should be unique in a webpage.

Declaring <input type="text" name="number2" id="number2"/> in a loop is wrong .

For creating multiple input using loop try like this-

echo "<input type='text' name='number[$i]' id='number{$i}' />";
<input type="text" name="number[2]" id="number2"/>  

would make $_POST['number'] an array which you can loop though server side, This is described here http://www.php.net/manual/en/faq.html.php#faq.html.arrays

foreach ($_POST['number'] as $number){
echo $number;
}

for example

this would make your code

for ($i = 1; $i <= 5; $i++) { //normally not 5 but a random number, choose by user
     echo "<input type="text" name="number[$i]" id="number{$i}"/>  ";
?>      

<?php
}
?>
</form>
<?php
print_r( $_POST['number']  );

$_SESSION['countnumb']= $_POST['number'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM