user9277108
user9277108

Reputation:

Insert rows into database table from pairs of html form elements

I have a dynamic form with repeatable input fields. When the form is submitted, the receiving PHP script is designed to insert pairs of values as new rows in the database. The trouble is that the $_POST['submit'] element is executing an extra/unwanted INSERT query.

This is the foreach loop, (sql secure not included)

if (isset($_POST['submit'])) {
    $nearest = $db->prepare('insert into nearest set place=?, distance=?');
    $i = 0;
    foreach ($_POST as $val) {
        $place = $_POST['place'][$i];
        $distance = $_POST['distance'][$i];
        $nearest->execute([$place, $distance]);
        $i++;
    }
}

This loop inserted '$_POST' values and inserted empty row.

Upvotes: 0

Views: 645

Answers (2)

Andreas
Andreas

Reputation: 23958

If you want to keep the loop you can use array_slice to not include the last item in the loop.
Array_slice will take items from 0 (not literal, but the first item) to second to last (-1).
http://php.net/manual/en/function.array-slice.php

EDIT; I think you need a for loop to loop the count of "place".

if (isset($_POST['submit'])) {
  $nearest= $db -> prepare('insert into nearest set place=?, distance=?');
  for($i=0; $i< count($_POST['place']; $i++){
      $place = $_POST['place'][$i];
      $distance= $_POST['distance'][$i];
      $nearest-> execute([$place , $distance]);
      $i++;
  }
}

example: https://3v4l.org/F47ui

Upvotes: 1

Marcin Orlowski
Marcin Orlowski

Reputation: 75645

You can simply remove your submit key from $_POST prior doing your loop with just regular unset(). But this is bad approach. What I'd rather recommend doing instead is to "isolate" your data, and instead of this:

<input name="distance" ... >

make all your imputs like this:

<input name="data[distance]" ... >

then you just need to loop over "data" (name as you like) array:

foreach($_POST['data'] as val)

Also, resist from removing last element in blind, because it's based on false assumption that this is always your "submit" element. What if you add more submit buttons to the form? or the order will change?

Upvotes: 0

Related Questions