-1
I am trying to create a list of products in php and when clicking send wanted it to be stored N products in the array, however what happens is that each time I click send it adds a new value and does not keep the old.
php form.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Formulario</title>
</head>
<body>
<h1>Produto</h1>
<form action="#" method="POST">
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<label for="description">Description:</label>
<textarea name="description" id="description" cols="30" rows="10"></textarea>
<label for="price">Price:</label>
<input type="number" name="price" id="price">
<button type="submit">Send</button>
</form>
<?php
include "Product.class.php";
if($_POST){
$product = new Product;
$name = $_POST['name'];
$description = $_POST['description'];
$price = $_POST['price'];
$product->addProduct($name, $description, $price);
$product->showProducts();
}
?>
</body>
</html>
Product.class.php
<?php
class Product
{
public $products;
public function addProduct($name, $description, $price){
return $this->products[] = [$name, $description, $price];
}
public function showProducts(){
echo "<pre>";
var_dump($this->products);
echo "</pre>";
}
}
What happens is that as you have a single
<form>
with only 3 fields that send 3 information:name
,description
andprice
, When you make the shipment, you are only informing data of a single product. The next time the page reload and you try to send another product, the object$product
will not hold the attribute that was set inPOST
previous, ie it will be zeroed. It is also recommended to set the attribute$products
of the class asprivate
, this guarantees the principle of encapsulation.– user98628
what I need to do then to keep the information ?
– deft1
Remember that http is a stateless protocol. Each time you invoke a php page your code runs all over again. If you create a list of products on a page, it will always be created on that page.
– Isac