PHP insert multiple fields to database

0

A question at the time of entering a comments to a worker to the database through his ID only I enter a single comment not the multiple that I can add through the textbox.

<script>  
 $(document).ready(function(){  
      var i=1;  
      $('#add').click(function(){  
           i++;  
           $('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');  
      });  
      $(document).on('click', '.btn_remove', function(){  
           var button_id = $(this).attr("id");   
           $('#row'+button_id+'').remove();  
      });    
 });  
 </script>
<div class="container">  
                <br />  
                <br />  
                <input type="text" name="id" value="01">
                <div class="form-group">  
                     <form name="add_name" id="add_name">  
                          <div class="table-responsive">  
                               <table class="table table-bordered" id="dynamic_field">  
                                    <tr>  

                                         <td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td>  
                                         <td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>  
                                    </tr> 
                               </table>  
                               <input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />  
                          </div>  
                     </form>  
                </div>  
           </div>  

           <?php 

  include 'include/conexion.php';
 if (isset($_POST['submit'])) {
       $number = count($_POST["name"]); 
 if($number > 0)  
 {  

      for($i=0; $i<$number; $i++)  
      {  

           if(trim($_POST["name"][$i] != ''))  
           {  

                $sql = "INSERT INTO observacion (id,motivo) VALUES('".mysqli_real_escape_string($conn, $_POST['id'][$i])."','".mysqli_real_escape_string($conn, $_POST["name"][$i])."')";  
                mysqli_query($conn, $sql);  

           }  
      }  
      ?> 
        <div class="text-center">
          <div class="alert alert-success" role="alert">
            <strong>Observacion Ingresada!</strong> 
          </div>
        </div>
        <?php
 }  
 else  
 {  
      echo "Please Enter Name";  
 } 
 }


  ?>
    
asked by MoteCL 31.08.2017 в 13:44
source

2 answers

2

The problem is found in this line:

$sql = "INSERT INTO observacion (id,motivo)
    VALUES('".mysqli_real_escape_string($conn, $_POST['id'][$i])."','".mysqli_real_escape_string($conn, $_POST["name"][$i])."')"; 

Specifically in $_POST['id'][$i] , the id from the form is not being sent as an array but as a variable.

<input type="text" name="id" value="01">

The way to solve it is simple

Well we call $_POST['id'] as is without the [$i] since it seems to be the same id for all comments.

Or we indicate that it is a Array in the form with the square brackets [ ] .

<input type="text" name="id[]" value="01">

For this specific case, it would be advisable to use prepared sentences since they allow us to execute the same sentence by iterating only the values, quickly. Apart from simplifying the code and facilitating the prevention of SQL injection.

Example of code with prepared sentences, I also corrected some errors that I saw.

form

<div class="container">
    <!-- Este input deberia estar dentro del form -->
    <!-- <input type="text" name="id" value="01"> -->
    <div class="form-group">
        <!-- En el form falta el action y el method -->
        <form name="add_name" id="add_name" action="#" method="POST">
            <input type="text" name="id" value="01">
            <div class="table-responsive">
                <table class="table table-bordered" id="dynamic_field">
                  <tr>
                    <td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td>
                    <td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
                  </tr>
                </table>
                <!-- el type deberia ser submit en el boton de envio -->
                <input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
            </div>
        </form>
    </div>
</div>

PHP

// se asume conexion en $conn interfaz MySQLi
include 'include/conexion.php';
// Comprobamos  si se envio el form
if ( isset($_POST['submit']) AND isset($_POST['id']) )
{
    // comprobamos que haya almenos un elemento name
    if(count($_POST["name"]) > 0)
    {
        // creamos la consulta
        $sql = "INSERT INTO observacion (id,motivo) VALUES( ?, ? );";
        // preparamos la consulta
        $stmt = $conn->prepare($sql);
        // asignamos id
        $id = $_POST['id'];
        // recorremos $_POST['name']
        foreach ($_POST['name'] as $motivo)
        {
          //comprobamos que se escribio algo
            if(trim($motivo) != '')
            {
              // si se escribio ejecutamos la co
              $stmt->bind_param('ss', $id, $motivo);
              $stmt->execute();
            }
        }
        ?> 
        <div class="text-center">
            <div class="alert alert-success" role="alert">
                <strong>Observacion Ingresada!</strong> 
            </div>
        </div>
        <?php
    }
    else
    {
      echo "Please Enter Name";
    }
}

I leave the code in a file.php to test it, just configure the data of the database, it assumes a table called 'observation' with at least the columns'id' and'motivo':

Full_example.php

<!DOCTYPE html>
<html>
<head>
  <title>Form</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <script>
     $(document).ready(function(){
          var i=1;
          $('#add').click(function(){
               i++;
               $('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
          });
          $(document).on('click', '.btn_remove', function(){
               var button_id = $(this).attr("id"); 
               $('#row'+button_id+'').remove();
          });  
     });
     </script>
</head>
<body>

<div class="container">
    <!-- Este input deberia estar dentro del form -->
    <!-- <input type="text" name="id" value="01"> -->
    <div class="form-group">
        <!-- En el form falta el action y el method -->
        <form name="add_name" id="add_name" action="#" method="POST">
            <input type="text" name="id" value="01">
            <div class="table-responsive">
                <table class="table table-bordered" id="dynamic_field">
                  <tr>
                    <td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td>
                    <td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
                  </tr>
                </table>
                <!-- el type deberia ser submit en el boton de envio -->
                <input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
            </div>
        </form>
    </div>
</div>

<?php
$conn = new mysqli('localhost', 'usuario', 'contraseña', 'base_datos') or die("Error con la base de datos.");
/* Comprueba la conexión */
if ($conn->connect_errno) {
    printf("Connect failed: %s\n", $conn->connect_error);
    exit;
}

// se asume conexion en $conn interfaz MySQLi
//include 'include/conexion.php';
// Comprobamos  si se envio el form
if ( isset($_POST['submit']) AND isset($_POST['id']) )
{
    // comprobamos que haya almenos un elemento name
    if(count($_POST["name"]) > 0)
    {
        // creamos la consulta
        $sql = "INSERT INTO observacion (id, motivo) VALUES( ?, ? );";
        // preparamos la consulta
        $stmt = $conn->prepare($sql);
        // asignamos id
        $id = $_POST['id'];
        // recorremos $_POST['name']
        foreach ($_POST['name'] as $motivo)
        {
          //comprobamos que se escribio algo
            if(trim($motivo) != '')
            {
              // si se escribio ejecutamos la co
              $stmt->bind_param('ss', $id, $motivo);
              $stmt->execute();
            }
        }
        ?> 
        <div class="text-center">
            <div class="alert alert-success" role="alert">
                <strong>Observacion Ingresada!</strong> 
            </div>
        </div>
        <?php
    }
    else
    {
      echo "Please Enter Name";
    }
}

?>
</body>
</html>
    
answered by 31.08.2017 / 15:38
source
0

First of all I iterated through each index of $_POST["name"] instead of doing a loop for , but I think the most important thing is that I changed the following line:

/* Mal */
if(trim($_POST["name"][$i] != ''))
/* Bien (nótese el cierre de paréntesis) */
if(trim($_POST["name"][$i]) != '')

I have also controlled any error that the query may generate, since in case you have problems with duplicate key, syntax error, etc, you would not know in any way.

Result:

<?php
include 'include/conexion.php';
if (isset($_POST['submit'])) {
    /* Iteramos por cada índice */
    foreach ($_POST["name"] as $i => $nombre) {
        /* Cuidado con los paréntesis de aquí */
        if (trim($nombre) !== '') {
            $sql = "
                INSERT INTO observacion (
                    id,
                    motivo
                ) VALUES(
                    '" . mysqli_real_escape_string($conn, $_POST['id'][$i]) . "',
                    '" . mysqli_real_escape_string($conn, $nombre) . "'
                )
            ";
            /* Comprobamos si la consulta se ejecuta correctamente */
            if (mysqli_query($conn, $sql) === false) {
                die(mysqli_error($conn));
            }
        }
    }
?>        <div class="text-center">
            <div class="alert alert-success" role="alert">
                <strong>Observacion Ingresada!</strong>
            </div>
        </div>
<?php
    } else {
        echo "Please Enter Name";
    }
}
    
answered by 31.08.2017 в 14:34