2018-05-24 14:12
浏览 175


I have a dynamic multi input. When submit form, inserting array values. But I want to insert without 'submit' value. 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]);

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

图片转代码服务由CSDN问答提供 功能建议

我有一个动态多输入。 提交表单时,插入数组值。 但我想插入没有'submit'值。 这是foreach循环,(不包括sql安全)

  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]); \  n $ i ++; 

此循环插入'$ _POST'值并插入空行。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douxiong0668
    douxiong0668 2018-05-24 14:16

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

    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]);

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

    点赞 评论
  • dongtanxi5676756
    dongtanxi5676756 2018-05-24 14:24

    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?

    点赞 评论