-1

I am building a program that makes a user enter three items into a cart, takes them to a page that says the items were added to the cart, and has a link to the cart which lists the items the user entered earlier. Here is my code: Form:

<h3>Add Products To Cart</h3>

<form action="add_to_cart.php" method="post">
    Item 1: <input type="text" name="item1"><br /> 
    Item 2: <input type="text" name="item2"><br />
    Item 3: <input type="text" name="item3"><br />
    <input type="submit">
</form>

page that confirms adding was successful:

<?php

session_start();
$username = "Hubert";
$item1 = "cookies";
$item2 = "cream";
$item3 = "water";

if( ( strcasecmp($_POST["item1"], $item1 ) == 0 && strcasecmp($_POST["item2"], $item2) ) == 0 )
{
    $_SESSION["logged"] = true;
    $_SESSION["ID"] = $username;

    echo "Items added to the cart". "<br />";
    echo "<a href=\"list_items_in_cart.php\">Show items in the cart</a> ";
}
else
{
    echo "<a href=\"login.php\">Try again</a>";
}

?>

Page that lists items in cart:

<?php

session_start();



if( isset($_SESSION["logged"]) && $_SESSION["logged"] ){

  echo "Item 1: ".$_POST["item1"]."<br />";
  echo "Item 2: ".$_POST["item2"]."<br />";
  echo "Item 3: ".$_POST["item3"]."<br />";
}

?>

The first two scripts work fine, however, in the 3rd script I have an error: : "Undefined index: items 1,2,3". Can someone offer a solution?

Hubert
  • 1
  • 1

1 Answers1

0

This happens because your $_POST array is filled with values only after you submit a form. So you get your values on the add_to_card.php page, but not on the next page you link to, it's just impossible.
What you need to do here is either to store your items in the database or (probably you wanted this one) to store them in the session itself. And then, on your third page (i.e., "What's in cart") use $_SESSION, and not $_POST superglobal.

Andre Polykanine
  • 3,291
  • 18
  • 28