Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop in form with foreach and session

I have a form with a loop inside. Here is my code:

<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">    
<?php
for ($i = 1; $i <= 2; $i++) {
    echo "Numero ";
    echo $i;
    echo "<input type='text' name='number2[$i]' id='number2{$i}' />";   
}

   ?>
   <input type="submit" name="submitbutton" value="Confirm!">
   </form>
   <?php
   print_r( $_POST  );
if(!isset($submitbutton)) {
    if (isset($_POST['number2']) != "") {
        echo "<b>{$_POST['number2']}</b>, !\n";
        $nI = $_POST['number2'];
    } 
}
?>

The output I get is:

Array ( [number2] => Array ( [1] => 3 [2] => 4 ) [submitbutton] => Confirm! ) Array, !

I would like to know how can I put the number in a session.

For example Session[1]=3, Session[2]=4

I try with array and foreach but I always get error.

like image 932
usertfwr Avatar asked Oct 04 '22 12:10

usertfwr


1 Answers

Something like this should work for you:

<?php
// Start a PHP Session
session_start();
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">    
    <?php
    for ($i = 1; $i <= 2; $i++) {
        echo "Numero ";
        echo $i;
        echo "<input type='text' name='number2[$i]' id='number2{$i}' />";   
    }
    ?>
    <input type="submit" name="submitbutton" value="Confirm!">
</form>
<?php
// If the form was submitted and number2 is an array
if(isset($_POST['submitbutton']) 
        && isset($_POST['number2']) 
        && is_array($_POST['number2'])) {

    // Loop through each posted value and save it to the session
    foreach ($_POST['number2'] as $key => $value) {
        $_SESSION["number2_{$key}"] = $value;
    } 
}
echo "number2_1 = " . $_SESSION["number2_1"] . "<br />";
echo "number2_2 = " . $_SESSION["number2_2"] . "<br />";
?>
like image 107
Steven Moseley Avatar answered Oct 12 '22 08:10

Steven Moseley