-1

I am trying to add items to an array each time I submit the form above it.

The first 2 items you see in the screenshots are hardcored for the example.

The third item which is a long code is the item I pull from my database and then push it into the array.

My problem is that every time I submit the form to add a new item into the array the new item simply overwrites the previous one as you can see in the screenshots below.

enter image description here

insertProduct.php

$inserted_product_code =  $_POST["code"];

$sql = "SELECT products.code FROM products WHERE products.code = '$inserted_product_code'";

if($result = mysqli_query($link, $sql)){
    while ($row = mysqli_fetch_assoc($result)){
        array_push($inserted_products, $row['code']) ;

    }
}
echo print_r($inserted_products);

createTable.php

$inserted_products = array("Entry 1","Entry 2");

<form method="POST" action="">
    <input type="text" name="code" placeholder="Your Input" required />
    <button type="submit" name="insertProduct"> Submit </button>
</form>

if (isset($_POST['insertProduct'])) { 
    include 'insertProduct.php';
}
Mishka04
  • 23
  • 5
  • Where is your `$sql` code? – biesior May 12 '21 at 17:53
  • @biesior I forgot to include it. I have just updated the question. Altough from what I understand the problem happens regardless from where I pull the new item. – Mishka04 May 12 '21 at 18:14
  • 1
    Previous data is lost once you submit a form(make a new request). Use sessions (or database) to store data between requests – brombeer May 12 '21 at 18:29
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman May 12 '21 at 20:09

1 Answers1

0

I tried to implement the same using sessions, that works fine for me,

if (isset($_POST['insertProduct'])) {
$inserted_code = $_POST['code'];
$inserted_products = array("Entry 1", "Entry 2");
if (isset($_SESSION['myArray'])) {
    $inserted_products = $_SESSION['myArray'];
    array_push($inserted_products, "Entry $inserted_code");
    $_SESSION['myArray'] = $inserted_products;
} else {
    array_push($inserted_products, "Entry $inserted_code");
    $_SESSION['myArray'] = $inserted_products;
}
}
surzabi
  • 16
  • 1