Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

session - Storing multiple values in a $_SESSION variable with PHP

I'm creating a site which has a shopping cart. I do not need any special functionality so I'm creating the cart on my own rather than integrating any ready one. My products do not have a predefined price in the database. The price is being generated dynamically based on the values entered by a user on the product page. So, the user chooses some specifications, enters the quantity and I get the following values:

Item ID
Quantity
Total price

I need to store those values in the $_SESSION variable and then loop over it when needed to get the results and print them in the shopping cart. The problem is that there are a lot of products and I need to store all those values (Quantity, Total Price) distinctively for the chosen product. That said, how do I store Item ID, Quantity and Total price in the $_SESSION variable and associate those values with each other?

Thanks for helping.

EDIT: My code implementing Michael's suggestions:

$itemid = $db->escape($_POST['productid']);
    $itemquantity = $db->escape($_POST['itemquantity']);
    $totalprice = $db->escape($_POST['totalprice']);

    $_SESSION['items'] = array();

    $_SESSION['items'][$itemid] = array('Quantity' => $itemquantity, 'Total' => $totalprice);

    var_dump($_SESSION);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the item ID as an array key, which holds an array of the other items:

// Initialize the session
session_start();

// Parent array of all items, initialized if not already...
if (!isset($_SESSION['items']) {
  $_SESSION['items'] = array();
}

// Add items based on item ID
$_SESSION['items'][$itemID] = array('Quantity' => $quantity, 'Total' => $total);
// Another item...
$_SESSION['items'][$another_itemID] = array('Quantity' => $another_quantity, 'Total' => $another_total);
// etc...

And access them as:

// For item 12345's quantity
echo $_SESSION['items'][12345]['Quantity'];

// Add 1 to quantity for item 54321
$_SESSION['items'][54321]['Quantity']++;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...