Prinston J
Prinston J

Reputation: 105

Adding new value to PHP Session array

What my scenario is I have items in session when loading to this page.php,

now in this page.php on a form submit it posts some values to same page.php, And am trying to add post values to existing session values by the following code,

    if (isset($_POST['special'])) {
    for ($i = count($_SESSION['item']); $i <= count($_SESSION['item']); $i++) {
        $index = ++$i;
        $_SESSION['price'][$index] = $_POST['price'];
        $_SESSION['item'][$index] = $_POST['name'];

    }
}

Am doing the following for re-arranging the items(as I do have deleting particular items)..

$k=0;
for ($j = 1; $j <= count($_SESSION['item']); $j++) {
if ($_SESSION['item'][$j] != '') {
    ++$k;
    $itemName[$k] = $_SESSION['item'][$j];
    $itemPrice[$k] = $_SESSION['price'][$j];
    }
$_SESSION['item'] = $itemName;

$_SESSION['price'] = $itemPrice;

On echo of the content of $_SESSION['item'] am finding the newly added available in page.php, but when I move to next page the newly added session is alone missing.

Upvotes: 1

Views: 1992

Answers (1)

41eight
41eight

Reputation: 191

You need to use session_start() inside your script. If not then the session won't continue when moving between pages.

<?php

session_start();

// Your code

?>

Upvotes: 1

Related Questions