I have to create a shopping list using PHP. To be more precise: I have to enter things in an input field. And echo all the input on the webpage, without reseting the list. And it's forbidden to use a database.
But that's my problem, if i enter something, it apears on the page. But if i enter another item it will overwrite the current item.
this is my code for so far:
<?php
if (isset($_POST['gros'])) {
$gros = $_POST['gros'];
}
$data = [$gros];
setcookie("grocery", $gros, 100);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>shopping list</title>
</head>
<body>
<h1>shopping list</h1>
<form action="index.php" method="POST">
<input type="text" placeholder="article" name="gros"><br>
<input type="submit" name="submit" value="submit">
</form>
<h3>Your shopping list</h3>
<?php
if (empty($gros)) {
echo "Field is empty";
} else {
foreach($data as $value) {
echo $value;
}
}
?>
</body>
</html>
I thought cookies are the solution, unfortunately i don't know exactly how to use them. someone who can help me?
thanks in advance!
CodePudding user response:
I think your solution should be to handle the lists correctly, if you notice, the cookie is only storing the element you are sending, thus overwriting the existing cookie, for this you should rescue the cookie, add the element to the list and then save another turn the entire list into the cookie.
<?php
if (isset($_POST['gros'])) {
$gros = $_POST['gros'];
if (isset($_COOKIE['grocery']){
$data = json_decode($_COOKIE['your_cookie_name'], true);
array_push($data, $gros);
setcookie("grocery", json_encode($data), 100);
}else{
$data = []
array_push($data, $gros);
setcookie("grocery", json_encode($data), 100);
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>shopping list</title>
</head>
<body>
<h1>shopping list</h1>
<form action="index.php" method="POST">
<input type="text" placeholder="article" name="gros"><br>
<input type="submit" name="submit" value="submit">
</form>
<h3>Your shopping list</h3>
<?php
if (empty($gros)) {
echo "Field is empty";
} else {
foreach($data as $value) {
echo $value;
}
}
?>
</body>
</html>
The solution to handle JSON for cookies was obtained in the following publication: