skip to Main Content

I am add and remove input fields dynamically when i insert it into database only first input is inserted,i have checked it number of time but am not getting any errors in my code,need to help where is am going wrong.
please provide any solution how to fixed it and inserted successfully into database.

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = 'test';

        // Create connection
        $conn = new mysqli($servername, $username, $password,$dbname);

        // Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        } 
        //echo "Connected successfully";
        ?>
<?php  include('connection.php');

if(isset($_POST['submit'])){

$date = $_POST['field1'];

foreach( $date as $key => $d ) {

  $sql = "INSERT INTO invoice (name) VALUES ('$date[$key]')";

  if ($conn->query($sql) === TRUE) {
    echo "New record created successfully".mysqli_affected_rows($conn);
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

}

}

?>

    <!DOCTYPE html>
    <html>
    <head>
      <title>multiple fields</title>
    <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" id="bootstrap-css">
    <script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
    <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>

  <style>
    * {
  .border-radius(0) !important;
}

#field {
    margin-bottom:20px;
}
  </style>
</head>
<body>
<div class="container">
  <div class="row">
    <input type="hidden" name="count" value="1" />
        <div class="control-group" id="fields">
            <label class="control-label" for="field1">Nice Multiple Form Fields</label>
            <div class="controls" id="profs"> 
                <form class="input-append" method="post">
                    <div id="field">
                      <input  type="text" name="field1[]" class="input" id="field1" data-items="8"/>
                      <button id="b1" class="btn add-more" type="submit">+</button>
                    </div>

                    <button type="submit" name="submit">Submit</button>
                </form>

            </div>
        </div>
  </div>
</div>

<script>
  $(document).ready(function(){
    var next = 1;
    $(".add-more").click(function(e){
        e.preventDefault();
        var addto = "#field" + next;
        var addRemove = "#field" + (next);
        next = next + 1;
        var newIn = '<input autocomplete="off" class="input form-control" id="field' + next + '" name="field' + next + '" type="text">';
        var newInput = $(newIn);
        var removeBtn = '<button id="remove' + (next - 1) + '" class="btn btn-danger remove-me" >-</button></div><div id="field">';
        var removeButton = $(removeBtn);
        $(addto).after(newInput);
        $(addRemove).after(removeButton);
        $("#field" + next).attr('data-source',$(addto).attr('data-source'));
        $("#count").val(next);  

            $('.remove-me').click(function(e){
                e.preventDefault();
                var fieldNum = this.id.charAt(this.id.length-1);
                var fieldID = "#field" + fieldNum;
                $(this).remove();
                $(fieldID).remove();
            });
    });


});

</script>
</body>
</html>

3

Answers


  1. Its a Page refresh problem so please try to redirect same page.

    for example :

    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully".mysqli_affected_rows($conn);
        header("location:index.php");
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
        header("location:index.php");
    }
    

    i have used

    header("location:index.php");
    

    for after opration complete

    Login or Signup to reply.
  2. The dynamic inputs that you generate are not named field1[] but field2, field3 etc…

    var newIn = '<input autocomplete="off" class="input form-control" id="field' + next + '" name="field' + next + '" type="text">'; 
    

    In your PHP you only retrieve $date = $_POST[‘field1’]; which is an array of 1 elements.

    The right solution is to rename your first input name from field1[] to field1, and keep the other inputs named field2, field3

    Add a hidden input like that:

    <input type="hidden" name="nb_elements" value="1" >
    

    Every time you create a new input, add this in your javascript:

    $("[name=nb_elements]").val(next);
    

    And in your PHP do this:

    for($i=$_POST['nb_elements'] ; isset($_POST['field'.$i]) ; $i++ ){
       $sql = "INSERT INTO invoice (name) VALUES ('$_POST['field'.$i]')";
       //...
    }
    

    Note that you have a possible SQL injection by the way, use this function:
    http://php.net/manual/en/mysqli.real-escape-string.php

    Login or Signup to reply.
  3. Your code has several issue regarding coding practice and code styles but hope you will learn overtime on them.

    I will address only the issue that you mentioned.

    to get the html form element as an array in the POST request then you should have same name attribute for all elements.

    in your case your javascript should generate new input fields results something as below

    <input autocomplete="off" class="input form-control" id="field1" name="field1[]" type="text">
    <input autocomplete="off" class="input form-control" id="field2" name="field1[]" type="text">
    <input autocomplete="off" class="input form-control" id="field3" name="field1[]" type="text">
    

    But your current script creating unique name attribute for each new input element.It has to be updated as below

    var newIn = '<input autocomplete="off" class="input form-control" id="field' + next + '" name="field1[]" type="text">';
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search