<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Oblig 8 Felles</title>
</head>
<body>
<form method="GET" action="">
<p><label for="itemName">Add Name:</label>
<input type="text" name="itemName" /></p>
<p><label for="itemPrice">Add Price:</label>
<input type="text" name="itemPrice" /></p>
<input type="submit" name="sendPrice" value="Send" />
</form>
[php]
function addItem($name, $price) {
global $inventory;
$inventory[$name] = $price;
}
$inventory = array();
$name = $_GET['itemName'];
$price = $_GET['itemPrice'];
addItem($name, $price);
/* I try to build an array from the name and price input.
When I enter new values, they replace the last entries. */
[/php]
</body>
</html>
It’s not that you are replacing the old one it’s that you are starting a new array every time the form submits and reloads the page. The best way to do what you want is to use a session variable.
For example, at the very top of your script put this:
[php]
[/php]
Then you can modify your array to use the session variable:
[php]
// $_SESSION[‘inventory’] is passed by reference so there is no need for global
function addItem($name, $price, &$inventory) {
$inventory[$name] = $price;
}
$name = $_GET[‘itemName’];
$price = $_GET[‘itemPrice’];
addItem($name, $price, $_SESSION[‘inventory’]);
[/php]
Thank you M@tt, for a quick and great answer
It worked, but I’m probably to unexperienced for this kind of PHP.
When I tested it with som random inputs, I filled the inventory array with gibberish.
To remove the unwanted items, I used unset- and destroy session. Then it stopped working.
I tried to make a new php-file, but it still doesn’t work. It seems like what I did resides in memory somewhere, I don’t know.
I will go and learn some more PHP… It is obvious that I need to :
You treat the $_SESSION just like an array. So if you wanted to clear the session you could simply do
[php]$_SESSION = array();[/php]
The session values will remain until you either manually clear your browsers cache (including sessions) or close all browser windows. Just keep posting your code and I’ll try to explain what you are doing wrong