0

I am currently reading through a piece of code provided by my faculty and I am having troubles understanding how it works. Specifically how the anchor is linked to the php without method="post" or method="get". Kindly appreciate if anyone could explain or link me to relevant materials to do further readings. Much thanks.

if (!isset($_SESSION['cart'])){
    $_SESSION['cart'] = array();
}
if (isset($_GET['buy'])) {
    $_SESSION['cart'][] = $_GET['buy'];
    header('location: ' . $_SERVER['PHP_SELF']. '?' . SID);
    exit();
}

for ($i=0; $i<count($items); $i++){
    echo "<tr>";
    echo "<td>" .$items[$i]. "</td>";
    echo "<td>$" .number_format($prices[$i], 2). "</td>";
    echo "<td><a href='" .$_SERVER['PHP_SELF']. '?buy=' .$i. "'>Buy</a></td>";
    echo "</tr>";
}
1
  • The query string variable in the href - ?buy= - can be picked up with $_GET['buy']. Commented Oct 16, 2019 at 9:16

1 Answer 1

1

Cart for bought items indexes is created in session if it's not there yet.

if (!isset($_SESSION['cart'])){
    $_SESSION['cart'] = array();
}

When link with buy query parameter is opened, buy value is added to session cart. After that page is redirected to location without buy parameter.

if (isset($_GET['buy'])) {
    $_SESSION['cart'][] = $_GET['buy'];
    header('location: ' . $_SERVER['PHP_SELF']. '?' . SID);
    exit();
}

List of items to buy is printed on page (i quess code in question is not full).

for ($i=0; $i<count($items); $i++){
    echo "<tr>";
    echo "<td>" .$items[$i]. "</td>";
    echo "<td>$" .number_format($prices[$i], 2). "</td>";
    echo "<td><a href='" .$_SERVER['PHP_SELF']. '?buy=' .$i. "'>Buy</a></td>";
    echo "</tr>";
}
  1. Links open pages with GET method.

  2. Link query parameters can be accessed by special $_GET variable

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.