5

我有一个里面有一个循环的表格。这是我的代码:

<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'];
    } 
}
?>

我得到的输出是:

数组 ( [number2] => 数组 ( [1] => 3 [2] => 4 ) [提交按钮] => 确认!) 数组,!

我想知道如何将号码放入会话中。

例如Session[1]=3, Session[2]=4

我尝试使用数组和 foreach,但总是出错。

4

2 回答 2

2

像这样的东西应该适合你:

<?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 />";
?>
于 2013-07-18T02:01:10.107 回答
2

你遇到了什么错误?请注意,isset()仅返回TRUEor FALSE,因此isset($_POST['number2'])永远不会等于空字符串。

于 2013-07-18T01:58:26.467 回答