Solution 1 :

When you are inserting your HTML, you are giving everything the same name. When this is then submitted, the web server isn’t quite sure which one you want so it only uses 1 of these values – in your case it seems to be the very last one.

If you change the names of your controls to add [] at the end (e.g. <input type="text" name="package[]">), the server then treats this as an array and you are able to obtain all the values.

If you then do var_dump($_POST) from your PHP you should see an array of values for package and price. Then, server-side we can just loop through those.

for($i = 0; $i < count($_POST['package']); $i++){
    $package = $_POST['package'][$i];
    $price = $_POST['price'][$i];
    //do whatever you want with variables here
}

Solution 2 :

in your php code when processing package and price you should use an foreach cycle, look below example (here I suppose the package and price arrays have the same size and it’s not associative arrays). Use foreach to cycle through arrays.

$i = 0;
for($_POST['package'] as $package) {
    $price = $_POST['price'][$i];
    //your sql insert of package&price couple
    $i++
}

Problem :

This is the html/php code

<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST">
    <div id="input">
        <label for="package">Package</label>
        <input type="text" name="package[]">
        <label for="price">Price</label>
        <input type="text" name="price[]">
        <input type="button" value="add" onClick="addInput('input');">
        <input type="submit" name="submit" value="Add Package">
    </div>
</form>

this is JS

function addInput(parentDiv) {
    let newInput = document.createElement('div');
    newInput.innerHTML = '<label for="package">Package</label> <input type="text" name="package"> <label for="price">Price</label> <input type="text" name="price"></input>';
    document.getElementById(parentDiv).appendChild(newInput);
}

The user is allowed to add as many inputs as possible. I would like to capture them in an array, with the package as the key and price as the value and save to an sql table

Comments

Comment posted by AKX

What have you tried on the PHP side? Have you looked at e.g.

Comment posted by Alex Gooner Arteta

no, I used $_POST[‘name’]. This way, I only get the last value provided by the user

Comment posted by AKX

There’s no field called

Comment posted by Alex Gooner Arteta

the name is just a placeholder. I used

Comment posted by AKX

You’re missing the

By