Add data from a form to an array

-1

I'm trying to create a list of products in php and when I click send I wanted to store N products in the array, but what happens is that every time I click send it adds a new value and does not keep the old.

form.php

<!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>";
    }
}
    
asked by anonymous 12.03.2018 / 00:29

1 answer

0

Paulo Imon has already explained why not storing a solution would be to store this data in a session :

<?php
    session_start();
    include "Product.class.php";

    if(empty($_SESSION["produtos"]))
        $_SESSION["produtos"] = [];

    if($_POST){
        $product = new Product;

        $name = $_POST['name'];
        $description = $_POST['description'];
        $price = $_POST['price'];

        array_push($_SESSION["produtos"], $product->addProduct($name, $description, $price));
    }

    var_dump($_SESSION["produtos"]);
    ?>
    
12.03.2018 / 01:33