I'm trying to implement some code that keeps adding to an array every time my page is submitted. I want to do this using serialize/unserialize method. For some reason my array simply adds one item and just changes that item every time I submit the form.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
$array_var=array("Name"=>"Doe","Karma"=>"45","Date"=>"2012-08-30");
?>
<form action="testtestmain.php" method="post">
<input type="hidden" id="str_var" name="str_var" value="<?php print base64_encode(serialize($array_var)) ?>">
<input type="text" name="name" value="Name">
<input type="submit" name="submit" value="Submit">
</form>
<?php
if (isset($_POST['str_var'])) {
$str_var=$_POST['str_var'];
$str_var=unserialize(base64_decode($_POST['str_var']));
$str_var[]=$_POST['name'];
foreach ($str_var as $cur) {
echo $cur."<br>";
}
}
?>
</body>
</html>
PHP values aren't saved between requests, remember HTTP is a stateless protocol. Thus each time you submit and refresh the page the array will be empty.
If you want to keep the data you'll need to save it in either: a cookie, a file, the session or a database.
Alternatively you can resend the full array via the hidden field, by moving the PHP up so to correctly populating the form.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
$str_var = isset($_POST['str_var']) ? unserialize(base64_decode($_POST['str_var'])) : [];
if(isset($_POST['str_var']))
{
$str_var[] = $_POST['name'];
}
?>
<form action="testtestmain.php" method="post">
<input type="hidden" id="str_var" name="str_var" value="<?php print base64_encode(serialize($str_var)) ?>">
<input type="text" name="name" value="Name">
<input type="submit" name="submit" value="Submit">
</form>
<?php
foreach($str_var as $cur)
{
echo $cur."<br>";
}
?>
</body>
</html>