简体   繁体   English

每次发送表单时,如何将$ _POST变量附加到$ _SESSION数组?

[英]How can i append a $_POST variable to a $_SESSION array each time the form is sent?

For about 2 hours i'm struggling with this problem. 我花了大约2个小时来解决这个问题。 I want to insert my $_POST variables in a $_SESSION array,and append each new data sent from the form to the session variable. 我想将$ _POST变量插入$ _SESSION数组中,并将从表单发送的每个新数据附加到会话变量中。 Now,when i define my session variable as a array,do i say like this? 现在,当我将会话变量定义为数组时,我会这样说吗?
$_SESSION['name']; $ _SESSION ['name'];
or like this 或像这样
$_SESSION['name'] = array(); $ _SESSION ['name'] = array();

I have two POST variables,and i want to insert each one in a session array. 我有两个POST变量,我想将每个变量都插入会话数组中。

Here is the form: 形式如下:

<form action="action.php" method="POST" >
<label>Moovie name: <input type="text" name="name" /></label><br />
<label>Price: <input type="text" name="price" /></label><br />
<input type="submit" value="Send" />
</form>

And here is action.php 这是action.php

<?php

session_start();

$_SESSION['name'] = array();
$_SESSION['price'] = array();

$name = $_POST['name'];
$price = $_POST['price'];

array_push($_SESSION['name'], $name);
array_push($_SESSION['price'], $price);

print_r($_SESSION['name']);
echo "<br>";
print_r($_SESSION['price']);

?>

Note: If i say 注意:如果我说

$_SESSION['name']; instead of $_SESSION['name'] = array();

i get Warning: array_push() expects parameter 1 to be array, null given in action.php 我得到警告:array_push()期望参数1为数组,在action.php中给出null
Again, is $_SESSION['name'] an array from the beginning? 同样,$ _SESSION ['name']是从头开始的数组吗?

You are emptying the session arrays every time this script runs. 每次运行此脚本时,您都将清空会话数组。

To avoid this, check if the arrays are already present in the session: 为避免这种情况,请检查会话中是否已存在阵列:

<?php

session_start();


if (!isset($_SESSION['name'])) {
    $_SESSION['name'] = array();
}
if (!isset($_SESSION['price'])) {
    $_SESSION['price'] = array();
}    


$name = $_POST['name'];
$price = $_POST['price'];

array_push($_SESSION['name'], $name);
array_push($_SESSION['price'], $price);

print_r($_SESSION['name']);
echo "<br>";
print_r($_SESSION['price']);

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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