Samurai
Samurai

Reputation: 55

How to add Data in Array Dynamically, from form In PHP

I have a task to take input from user and push it in array. How can I take input from input field submit it, push it in to array and then do this again?

    <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
        Input Stuff in this Table :
        <input type="text" name="insert">
        <input type="submit" name="submit">
    </form>

    <?php
        $insert = ($_POST["insert"]);
        array_push($data, $insert);
        print_r($data);
    ?>

Upvotes: 1

Views: 312

Answers (1)

behzad m salehi
behzad m salehi

Reputation: 1076

you will miss the content of your variable and will re-initialize it on every page load, the solution is to keep your $data variable in the session and use it on every form submission:

<?php
   session_start();
   $data = isset($_SESSION['data']) ? $_SESSION['data'] : []; 
   array_push($data, $_POST["insert"]);
   $_SESSION['data'] = $data;
?>

Upvotes: 2

Related Questions