使用表单内容将值添加到 $_SESSION 数组
我正在尝试创建一个页面,该页面接受表单提交并将内容作为新值添加到 $_SESSION() 数组中,但似乎正在发生的情况是该值被覆盖。
该表单有 3 个名为 a、b 和 c 的文本输入,并在提交时刷新页面。告诉我它被替换的是 $_SESSION[0] 将显示 1 2 和 3,如下定义,然后 $_POST 定义的下一行将是相同的,但数组值被最后提交的值替换,而不是添加最后一个作为另一行提交。
<form action="test2.php" method="post">
<input type="text" name="a">
<input type="text" name="b">
<input type="text" name="c">
<input type="submit" value="Submit">
</form>
<?php
if (isset($_POST['a']))
{
$a = $_POST['a'];
$b = $_POST['b'];
$c = $_POST['c'];
$order = array('a' => $a, 'b' => $b, 'c' => $c);
$_SESSION[0] = array('a' => 1, 'b' => 2, 'c' => 3);
$_SESSION[] = $order;
$count = count($_SESSION);
for ($i = 0; $i < $count; $i++) {
echo "w: " . $_SESSION[$i]['a'] . "\n";
echo "h: " . $_SESSION[$i]['b'] . "\n";
echo "p: " . $_SESSION[$i]['c'] . "\n";
echo "<br />";
}
}
?>
将非常感谢任何帮助, 谢谢
I'm trying to make a page that takes a form submission and adds the contents as a new value in the $_SESSION() array, what seems to be happening though is the value is being overridden.
The form has 3 text inputs named a, b and c and refreshes the page on submission. What tells me it's being replaced is $_SESSION[0] will display 1 2 and 3 as defined below, then the next row defined by $_POST will be the same but with the array values replaced by the last submitted values rather than adding the last submitted as another row.
<form action="test2.php" method="post">
<input type="text" name="a">
<input type="text" name="b">
<input type="text" name="c">
<input type="submit" value="Submit">
</form>
<?php
if (isset($_POST['a']))
{
$a = $_POST['a'];
$b = $_POST['b'];
$c = $_POST['c'];
$order = array('a' => $a, 'b' => $b, 'c' => $c);
$_SESSION[0] = array('a' => 1, 'b' => 2, 'c' => 3);
$_SESSION[] = $order;
$count = count($_SESSION);
for ($i = 0; $i < $count; $i++) {
echo "w: " . $_SESSION[$i]['a'] . "\n";
echo "h: " . $_SESSION[$i]['b'] . "\n";
echo "p: " . $_SESSION[$i]['c'] . "\n";
echo "<br />";
}
}
?>
Would be extremely grateful for any help,
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在我看来,每次提交表单时,您都试图将新数组添加到新的 $_SESSION var 中。您使用的方法只会将值添加到该页面加载的 $_SESSION 数组中 - 它实际上不会在 $_SESSION 数组中!令人困惑吧?所以这些都不起作用...
但是这会起作用,因为 $_SESSION 键中有文本(并且不要忘记启动会话)。
这将为“print_r($_SESSION)”生成以下内容。
It looks to me like you are trying to add a new array to a new $_SESSION var each time the form is submitted. The method you are using will only add the value to the $_SESSION array for that page load - it won't actually be in the $_SESSION array! Confusing right? So either of these won't work...
But this will, due there being text in the $_SESSION key (and don't forget to start the session).
This will generate the below for "print_r($_SESSION)".
添加表单值的最简单方法是
然后使用以下方式访问值
Most simplest way of adding form values would be
Then access the values using