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.
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