I want to Create an ItemList and simply display it. For this, I have created an array and a form with add item "text field" and "submit" button.
The problem is when I add a new value by clicking on the "submit" button, the page gets reloaded and previously added values are lost. I want previously added values to persist, without storing these data into the database.
Please help me I am a beginner in this field.
Code :
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>PHP ItemList</title>
</head>
<body>
<div class="container">
<?php
$itemList = array();
if ( $_SERVER["REQUEST_METHOD"] == "POST") {
array_push( $itemList, $_POST["Item"] );
print_r( $itemList );
}
?>
<h3>Add : </h3>
<form method="POST" action = "index.php">
<p>Item : <input type="text" name="Item"></p>
<input type="submit" name="submit" value="submit">
</form>
</div>
</body>
</html>
My Answer:
The issue you are facing is because every time the form is submitted, the $itemList array is getting reinitialized to an empty array. To solve this problem, you can store the $itemList array in the session so that it persists across page reloads. Here is an updated version of your code:
php
session_start();
if (!isset($_SESSION['itemList'])) {
$_SESSION['itemList'] = array();
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
array_push($_SESSION['itemList'], $_POST["Item"]);
print_r($_SESSION['itemList']);
}
?>
PHP ItemList
Add :
By storing the $itemList array in the $_SESSION superglobal, the values will persist across page reloads. Now, when you add a new item and submit the form, the previously added items will still be displayed.
Rate this post
4 of 5 based on 1849 votesComments