phpsession-variableshttp-post-vars

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. I want to insert my $_POST variables in a $_SESSION array,and append each new data sent from the form to the session variable. Now,when i define my session variable as a array,do i say like this?
$_SESSION['name'];
or like this
$_SESSION['name'] = array();

I have two POST variables,and i want to insert each one in a session array.

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

<?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
Again, is $_SESSION['name'] an array from the beginning?


Solution

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