I have a an array I want, whenenever i submit my form the post value get inserted into that array, every time with new incremented index.. How can I do that? And yes submited page is redirected to its开发者_运维问答elf...
In PHP:
$arr[] = value;
$arr[] = other value;
In HTML:
<input type="text" name="arr[]" />
<input type="text" name="arr[]" />
You could solve this using the session-variables. This way the data won't be overridden. Here's an example:
$_SESSION['formdata'][] = $_POST['value1'];
$_SESSION['formdata'][] = $_POST['value2'];
After you reload the script the data will still be available an pushing other values into the array won't override the old ones. You just do it again:
$_SESSION['formdata'][] = $_POST['value3'];
$_SESSION['formdata'][] = $_POST['value4'];
Calling the $_SESSION['formdata']-Array you now have all 4 values stored in there.
** EDIT ** I am finally home, and as promised I'm offering another solution using cookies, since sessions don't work for you, as we've already discussed. So here we go...
First of all we need to think of the way we want to name the cookie. I would suggest we would do this by ip-address and any suffix, to ensure, that it is really the user who has already filled, the former forms.
So we could go like this:
$dataArray[] = $_POST['value1'];
$dataArray[] = $_POST['value2'];
Then we need to store the data into an cookie. We do this by serializing the array, since we don't want to save hundreds of cookies. This would work like this:
$cookievalue = serialize($dataArray);
// Here we actually generate a cookiename in the format of "IP_formdata"
setcookie($_SERVER['REMOTE_ADDR'] . '_formdata', $cookievalue);
So far so good. Within the next form we retrieve the cookie-data and unserialize the data, so we can extend this array:
$dataArray = unserialize($_COOKIE[$_SERVER['REMOTE_ADDR'] . '_formdata');
Now we can add other values to the array from the second form:
$dataArray[] = $_POST['value3'];
$dataArray[] = $_POST['value4'];
After all additional values have been put into this array we serialize it again and store it into the again again:
$cookievalue = serialize($dataArray);
setcookie($_SERVER['REMOTE_ADDR'] . '_formdata', $cookievalue);
Now we can repeat this steps for all further forms. Just remember that if you want to work with the data you first have to unserialize the data and store it into an array.
And don't forget as I have already stated in the comments: The user can turn off cookies, then the whole thing won't work. You could also add some additional checks to verify that this is the correct user or something. I haven't tested the code, but I think it should work in a way like this and I hope I could help you or at least give you a hint :)
精彩评论