Question

I have a form with 4 inputs and a + button which, if pressed, through jQuery I add the same fields again so I can make multiple insertion at once. Just for reference this are the fields.

<fieldset class="dyn-product">
    <legend>Dettagli prodotto</legend>

    <div class="form-row rhird p1 left">
       <label for="barcode" class="label">Codice</label>
       <input type="text" class="input incoming-barcode" name="barcode[]" id="barcode" placeholder="Codice">
       <button type="button" class="generate-barcode">Crea codice a barre</button>
       <input type="hidden" name="has-barcode[]" class="has-barcode" value="1">
    </div>

    <div class="form-row third p1 left">
       <label for="name" class="label">Nome</label>
       <input type="text" class="input" name="name[]" id="name" placeholder="Nome">
    </div>

    <div class="form-row third left">
       <label for="quantity" class="label">Quantità</label>
       <input type="text" class="input" name="quantity[]" id="quantity" placeholder="Quantità">
    </div>

    <div class="form-row full left">
       <label for="description" class="label">Descrizione</label>
       <textarea name="description[]" class="input full small-textarea" id="description" cols="30" rows="10" placeholder="Descrizione"></textarea>
    </div>

    <div class="clearfix"></div>

</fieldset>

Once I press the + button, I generate the same <fieldset>. The problem is in php when I want to insert this data. Here is the code

$nr = count(Input::post('barcode'));
for ( $i = 0; $i < $nr; $i++ ) {

    $productData = array(
       'barcode'    => Input::post('barcode', $i),
       'name'       => Input::post('name', $i),
       'quantity'   => Input::post('quantity', $i),
       'descr'      => Input::post('description', $i),
       'has_code'   => Input::post('has-barcode', $i)
   );

   $insertProduct = $dbh->prepare(" INSERT INTO products(name, description, quantity, barcode, has_barcode) VALUES(:name, :descr, :quantity, :barcode, :has_code) ");
   $insertProduct->execute($productData);
}

This works fine, the problem is, if I insert 2 products, only the first inserts. If I insert 3 products, only the first 2 insert and so one. The last one doesn't insert. I get no errors and if I remove the insertion part code and print_r() the $productData array, I have all the products, but when inserting the last one doesn't.

I tried modifying the for loop, but that is not the problem.

I'd really appreciate if someone could help me.

Thank you.

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top