Hi guys!

How can I create an array that retains values dynamically every time i click the submit button?

The condition should be each time I select a product from a list and click submit, $cart must retain all values into it for use at another page.

i tried this code:

if(isset($_POST['submit']))
{
$cart = array();

$cart[] = $item_code.":".$item_qty;
}

from a <form action="$_SERVER['PHP_SELF']" method="post">

but each time i click "submit" $cart displays a new value and looses the old values previously entered.

thanks.😕

    Hey

    There are a couple of problems with what you're trying to do.

    1st
    $cart = array();

    This line will initialise the array each time its called, so in effect you are emptying the array each time you click submit.

    2nd
    $cart scope

    The variable $cart doesn't "persist" so even if you weren't initialising it every time you clicked submit, it would only ever show the last item you clicked on. The web is stateless so you have to store the data somewhere that will be available the next time you look for it, either in the $SESSION or a database. You could also store it in the $POST variable using a hidden field in your form, but i'm not sure how it would handle the array, you may need to serialise and unserialise the data each time you read from it.

    Provided you have sessions running correctly then this might be useful but I've not tested the code.

    if(!isset($_SESSION['cart']))
    {
            $_SESSION['cart'] = array();
    }
    
    if(isset($_POST['submit']))
    {
            array_push($_SESSION['cart'],$item_code.":".$item_qty);
    }
    

    Hope this helps

    Tim

      Write a Reply...