What are common methods for storing shopping cart data in PHP, such as arrays or sessions?
When developing a shopping cart in PHP, common methods for storing shopping cart data include using arrays or sessions. Arrays can be used to store the items in the cart, while sessions can be used to persist the cart data across multiple pages for a single user.
// Storing shopping cart data using arrays
$cart = array();
// Add item to cart
$item = array(
'id' => 1,
'name' => 'Product 1',
'price' => 10.00,
'quantity' => 1
);
$cart[] = $item;
// Storing shopping cart data using sessions
session_start();
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
// Add item to cart
$item = array(
'id' => 1,
'name' => 'Product 1',
'price' => 10.00,
'quantity' => 1
);
$_SESSION['cart'][] = $item;
Keywords
Related Questions
- Are there potential vulnerabilities in sending passwords in plain text via HTML forms in PHP, and how can they be mitigated?
- Is it possible to show category names instead of "Forums" in each category bar on a PHP forum homepage?
- What are some best practices for handling CSS files for different devices in PHP?