How can PHP sessions be implemented in a shopping list program?
To implement PHP sessions in a shopping list program, you can start a session when the user logs in or visits the shopping list page. You can store the shopping list items in the session variable and update it as the user adds or removes items from the list. This way, the shopping list will persist across different pages or visits until the user logs out or the session expires.
<?php
session_start();
// Check if shopping list array exists in session, if not create a new empty array
if (!isset($_SESSION['shopping_list'])) {
$_SESSION['shopping_list'] = [];
}
// Add item to shopping list
if (isset($_POST['add_item'])) {
$item = $_POST['item'];
array_push($_SESSION['shopping_list'], $item);
}
// Remove item from shopping list
if (isset($_POST['remove_item'])) {
$index = $_POST['index'];
unset($_SESSION['shopping_list'][$index]);
}
// Display shopping list
echo '<ul>';
foreach ($_SESSION['shopping_list'] as $index => $item) {
echo '<li>' . $item . ' <form method="post"><input type="hidden" name="index" value="' . $index . '"><input type="submit" name="remove_item" value="Remove"></form></li>';
}
echo '</ul>';
?>
Related Questions
- What are the common mistakes to avoid when modifying existing PHP scripts found online for specific functionalities like dropdown menus?
- How can PHP beginners improve their understanding of Apache and server configurations?
- Where can one find the correct parameter order for the implode() function in PHP?