Jump to content

Dynamic Form Fields Submitting Separately rather than in same row


Recommended Posts

Hi guys,

I really hope this will make sense.

I am creating a dynamic field on a button click for Pickup Location. That works fine and submitting the form to the database works fine. However, instead of one entry, each time I submit the form with multiple Pickup Locations, it creates multiple separate database entries.

Here is the PHP for submitting:

if(isset($_POST['new']) && $_POST['new']==1){
$pickups = '';
foreach($_POST['pickups'] as $cnt => $pickups)
    $pickups .= ',' .$pickups;
	$locations = count($_POST["pickups"]);
	
	if ($locations > 0) {
	    for ($i=0; $i < $locations; $i++) { 
		if (trim($_POST['pickups'] != '')) {
			
    $name = mysqli_real_escape_string($con, $_POST['name']);
    $price = mysqli_real_escape_string($con, $_POST['price']);
    //$origin = $_POST['origin'];
    $pickups = $_POST["pickups"][$i];
    $destination = mysqli_real_escape_string($con, $_POST['destination']);
    $dep_date = mysqli_real_escape_string($con, $_POST['dep_date']);
    $ret_date = mysqli_real_escape_string($con, $_POST['ret_date']);
    $fleet_number = mysqli_real_escape_string($con, $_POST['fleet_number']);
    $driver = mysqli_real_escape_string($con, $_POST['driver']);
    $itinerary = mysqli_real_escape_string($con, $_POST['itinerary']);
    $submittedby = mysqli_real_escape_string($con, $_SESSION["username"]);
    $trn_date = mysqli_real_escape_string($con, date("Y-m-d H:i:s"));
    

    $query="insert into tours (`name`, `price`, `pickups`, `destination`, `dep_date`, `ret_date`, `fleet_number`, `driver`, `itinerary`, `submittedby`, `trn_date`)values ('$name', '$price', '$pickups', '$destination', '$dep_date', '$ret_date', '$fleet_number', '$driver', '$itinerary', '$submittedby',  '$trn_date')";
    mysqli_query($con,$query)
    
    or die(mysqli_error($con));
    if(mysqli_affected_rows($con)== 1 ){
    $message = '<i class="fa fa-check"></i> - Record Inserted Successfully';
    }
}
}
}
}

Here is the HTML form:

                          <form role="form" method="post" name="add_tour" id="add_tour" action"">
                                <input type="hidden" name="new" value="1" />
                            <div class="modal-body">
                                
                          <div class="row form-group">
                              <div class="col-6">
                                <div class="form-group"><label for="name" class=" form-control-label">Name</label><input type="text" id="name" name="name" placeholder="Tour Name" class="form-control">
                                </div>
                                </div>
                              <div class="col-6">
                                <div class="form-group"><label for="price" class=" form-control-label">Price</label><input type="text" id="price" name="price" placeholder="0.00" class="form-control">
                                </div>
                                </div>
                                </div>
                                
                                <div class="row form-group">
                                    <div class="col-6">
                        <div class="form-group origin" id="pickupsfield"><label for="pickups" class=" form-control-label">Pickup Location</label><input type="text" id="pickups" name="pickups[]" placeholder="Start Typing..." class="form-control"></div>
    <button type="button" class="btn btn-success add-field" id="add" name="add">Add New Location &nbsp; 
      <span style="font-size:16px; font-weight:bold;">+ </span>
    </button>
                        </div>

                        <div class="col-6">
                        <div class="form-group"><label for="destination" class=" form-control-label">Destination</label><input type="text" id="destination" name="destination" placeholder="Start Typing..." class="form-control"></div>
                        </div>
                        </div>
                          <div class="row form-group">
                              <div class="col-6">
                        <div class="form-group"><label for="dep_date" class=" form-control-label">Departure Date</label><input type="date" id="dep_date" name="dep_date" placeholder="" class="form-control"></div>
                        </div>
                              <div class="col-6">
                           <div class="form-group"><label for="ret_date" class=" form-control-label">Return Date</label><input type="date" id="ret_date" name="ret_date" placeholder="" class="form-control"></div>
                          </div>
                          </div>
                          <div class="row form-group">
                              <div class="col-6">
                        <div class="form-group"><label for="fleet_number" class=" form-control-label">Fleet Number</label>
                           <select class="form-control" id="fleet_number" name="fleet_number">
                               <option value="Select">== Select Fleet Number ==</option>
<?php
$sql = "SELECT fleet_number FROM fleet";
$result = $con->query($sql);
        while(list($fleet_number) = mysqli_fetch_row($result)){
          $option = '<option value="'.$fleet_number.'">'.$fleet_number.'</option>';
          echo ($option);
        }
          ?>
                           </select>
                        </div>
                        </div>
                              <div class="col-6">
<?php

    ?>
                           <div class="form-group"><label for="driver" class=" form-control-label">Driver</label>
                           <select class="form-control" id="driver" name="driver">
                               <option value="Select">== Select Driver ==</option>
<?php
$sql = "SELECT name FROM drivers";
$result = $con->query($sql);
        while(list($driver) = mysqli_fetch_row($result)){
          $option = '<option value="'.$driver.'">'.$driver.'</option>';
          echo ($option);
        }
          ?>
                           </select>
                           </div>
                          </div>
                          </div>
                            <div class="form-group"><label for="itinerary" class=" form-control-label">Itinerary</label>
                            <textarea class="form-control" id="itinerary" name="itinerary"></textarea>
                            </div>

                            <div class="modal-footer">
                                <button type="reset" class="btn btn-warning">Clear Form</button>
                                <button type="submit" name="submit" id="submit" class="btn btn-primary">Confirm</button>
                            </div>
                            </form>

And the Javascript for adding the new fields:

<script>
  $(document).ready(function(){

    var i = 1;

    $("#add").click(function(){
      i++;
      $('#pickupsfield').append('<div id="row'+i+'"><input type="text" name="pickups[]" placeholder="Enter pickup" class="form-control"/></div><div><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></div>');  
    });

    $(document).on('click', '.btn_remove', function(){  
      var button_id = $(this).attr("id");   
      $('#row'+button_id+'').remove();  
   });

    $("#submit").on('click',function(){
      var formdata = $("#add_tour").serialize();
      $.ajax({
        url   :"",
        type  :"POST",
        data  :formdata,
        cache :false,
        success:function(result){
          alert(result);
          $("#add_tour")[0].reset();
        }
      });
    });
  });
</script>

Anyone have any idea where I am going wrong?

Before you say it, Yes, I know, Use Prepared statementsĀ šŸ˜·

Edited by DanEthical
Added tags
Link to post
Share on other sites
36 minutes ago, DanEthical said:

I am creating a dynamic field on a button click for Pickup Location. That works fine and submitting the form to the database works fine. However, instead of one entry, each time I submit the form with multiple Pickup Locations, it creates multiple separate database entries.

Well yeah: you put the code to insert inside the for loop that goes over each location.

Link to post
Share on other sites
13 minutes ago, requinix said:

Well yeah: you put the code to insert inside the for loop that goes over each location.

Hi requinix,

Is that not how it is meant to go? Sorry, it is a new learning curve for me.

Link to post
Share on other sites

Learning? That's fine. But there's one really important thing about programming that lots of newbies don't always get around to learning, and it's really, really important that they understand it sooner rather than later.

Indentation.

This

if(isset($_POST['new']) && $_POST['new']==1){
$pickups = '';
foreach($_POST['pickups'] as $cnt => $pickups)
    $pickups .= ',' .$pickups;
	$locations = count($_POST["pickups"]);

makes it look like (1) the if statement isn't doing anything and (2) the $locations line is inside the same foreach loop that the $pickups line is.

Every { means the next line indents further in by one, every } means the next line indents back out by one. Plus a couple other rules, like how when you don't use braces { } with control structure (like foreach) then the single line after it gets indented - or better yet, alwaysĀ use braces { }.
The above code should look more like

if(isset($_POST['new']) && $_POST['new']==1){
    $pickups = '';
    foreach($_POST['pickups'] as $cnt => $pickups)
        $pickups .= ',' .$pickups;
    $locations = count($_POST["pickups"]);

That properly shows where each line is relative to the if (all of them are included and thus only run when new=1) and to the foreach (it only affects the $pickups line and not the $locations line).

Take a moment to learn some more about indentation, then go back to the code you first posted - definitely the PHP but the HTML could benefit from proper indentation as well (<tag> indents in, </tag> indents out) - and then post the revised version. It still won't work correctly, because PHP is a reasonable language and doesn't do stupid things like care about how many spaces or tabs you used to indent your code, but it will be much easier to scan through. Plus it will help to point out exactly what other code is part of that one problematic for loop that is now the subject of conversation.

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.