简体   繁体   中英

Store items in SESSION from array on link click

I currently have a table populated from an array. The issue i'm having is storing the products on "Add to Cart"

    <?php
session_start();
$products = array(
array('SKU'=>'test1', 'name'=>'ProductTest1', 'Price'=>10.00),
array('SKU'=>'test2', 'name'=>'ProductTest2', 'Price'=>11.00),
array('SKU'=>'test3', 'name'=>'ProductTest3', 'Price'=>12.00)
);

if(isset($_GET['action' && $_get['action'] == "addToCart"))
{
$id = $_GET['product']);
if(isset($_SESSION['cart'][$id])){
$_SESSION['cart'][$id]['quantity']++;
}
else
{


?>

Below is also the table php which populates correctly.

<?php foreach ($products as $key => $product) {
echo '<tr>';
echo '<td>' . $product['SKU'] . '</td>';
echo '<td>' . $product['name'] . '</td>';
echo '<td>' . '&pound;'. number_format($product['Price'],2) . '</td>';
echo '<td><a href="?action=addToCart&product='. $key.'">Add To Cart </a></td>';
echo '</tr>';
}
?>

I can't figure out how to store the name and price of the items using the GET function, which should take the value from the URL.

Any help would be great!

Copy the element from $products into the session variable to get the name, SKU, and price.

if(isset($_SESSION['cart'][$id])){
    $_SESSION['cart'][$id]['quantity']++;
} else {
    $_SESSION['cart'][$id] = $products[$id];
    $_SESSION['cart'][$id]['quantity'] = 1;
}

Now other scripts can access $_SESSION['cart'][$id]['name'] and $_SESSION['cart'][$id]['Price'] .

Another option would be to put the $products definition in an include file, which is loaded by the other page to get this information.

Eventually you'll probably want to put your product information in a database, which could be accessed by both pages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM