Pivot Tables with JQuery, JavaScript and Mysql

3

Good afternoon, friends, I'm having a problem, I can not register all the users in the database, just register the last one, how can I solve this problem?

Index

<formmethod="post" action="salvar.php">

            Name       CPF       Position - Function       Email       Kinship      Actions                             

  <select name="cargo">
         <option value="gerente" name="gerente">Gerente</option>
         <option value="Professor" name="Professor">Professor</option>
         <option value="Programador" name="Programador">Programador</option>
  </select>

  </td>


<td><input type="text" name="email"></td>


          To remove                                                Add Dependents                              Register

save.php

$nome = $_POST['nome'];
$cpf = $_POST['cpf'];
$cargo = $_POST['cargo'];
$email = $_POST['email'];
$parentesco = $_POST['parentesco'];




// faz consulta no banco para inserir os dados do usuario
$sql = "insert into cad_dependentes (nome, cpf, cargo, email, parentesco) values ('$nome', '$cpf', '$cargo', '$email', '$parentesco')";

function.js

    (function($) {

  RemoveTableRow = function(handler) {
    var tr = $(handler).closest('tr');

    tr.fadeOut(400, function(){ 
      tr.remove(); 
    }); 

    return false;
  };

  AddTableRow = function() {

      var newRow = $("<tr>");
      var cols = "";

      cols += '<td><input type="text" name="nome"></td>';

      cols += '<td><input type="text" name="cpf"></td>'; 

      cols += '<td><select name="cargo">'; 
      cols += '<option value="gerente" name="gerente">Gerente</option>';
      cols += '<option value="Professor" name="Professor">Professor</option>';
      cols += '<option value="Programador" name="Programador">Programador</option>';
      cols += '</select></td>';

      cols += '<td><input type="text" name="email"></td>'; 

      cols += '<td><input type="text" name="parentesco"></td>'; 

      cols += '<td class="actions">';
      cols += '<button class="btn btn-large btn-danger" onclick="RemoveTableRow(this)" type="button">Remover</button>';
      cols += '</td>';

      newRow.append(cols);

      $("#products-table").append(newRow);

      return false;
  };


})(jQuery);
    
asked by anonymous 14.12.2016 / 20:29

2 answers

5

First, to insert multiple values via form in PHP, you need to define a particular format for this action. The way you did, it will always always insert only one file.

For example, if I have these three inputs, always the last value will be sent:

<form method="post">
    <input type="text" name="nome">
    <input type="text" name="nome">
    <input type="text" name="nome">
    <input type="submit" value="Submete Aí!">
</form>

<?php

    if ($_SERVER['REQUEST_METHOD'] === "POST") {

        var_dump($_POST['nome']);
    }
?>

The result would be:

Sowhatwouldbethewaytosendarrayperform?

Youneedtousebracketswiththedesiredindex,ortheemptybrackets,forindexingtobeautomated.

See:

<formmethod="post">
    <input type="text" name="nome[]">
    <input type="text" name="nome[]">
    <input type="text" name="nome[]">
    <input type="submit" value="Submete Aí!">
</form>

<?php

    if ($_SERVER['REQUEST_METHOD'] === "POST") {

        var_dump($_POST['nome']);
    }
?>

In this case the result was different:

Youcouldstillnumbertheindexesofarrayontheform,likethis:

<formmethod="post">
    <input type="text" name="nome[3]">
    <input type="text" name="nome[4]">
    <input type="text" name="nome[5]">
    <input type="submit" value="Submete Aí!">
</form>

<?php

    if ($_SERVER['REQUEST_METHOD'] === "POST") {

        var_dump($_POST['nome']);
    }
?>

The result would be:

Notethatinthelastexample,theindexes3,4,and5appearasdefinedintheform.

Inyourexample,IwouldnameeachindexviajQuery,leavingareservednamein$_POST,tomakeiteasiertocapturethedata.

Simplyput,wecouldhave:

<formmethod="post">

    <input type="text" name="usuarios[0][nome]">
    <input type="text" name="usuarios[0][idade]">
    <input type="text" name="usuarios[0][email]">
    <input type="submit" value="Submete Aí!">
</form>

<?php

    if ($_SERVER['REQUEST_METHOD'] === "POST") {

        var_dump($_POST['usuarios']);
    }
?>

So,wecouldchangetheJavascriptcodethatcreatestheinputstothefollowingform:

See:

varcurrentRow=0;AddTableRow=function(){varnewRow=$("<tr>");
    var cols = "";

    cols += '<td><input type="text" name="usuarios['+ currentRow + '][nome]"></td>';

    cols += '<td><input type="text" name="cpf"></td>';

    cols += '<td><select name="usuarios['+currentRow +'][cargo]">';
    cols += '<option value="gerente" name="usuarios['+currentRow +'][gerente]">Gerente</option>';
    cols += '<option value="Professor" name="usuarios['+currentRow +'][Professor]">Professor</option>';
    cols += '<option value="Programador" name="usuarios['+currentRow +'][Programador]">Programador</option>';
    cols += '</select></td>';

    cols += '<td><input type="text" name="usuarios['+currentRow +'][email]"></td>';

    cols += '<td><input type="text" name="usuarios['+currentRow +'][parentesco]"></td>';

    cols += '<td class="actions">';
    cols += '<button class="btn btn-large btn-danger" onclick="RemoveTableRow(this)" type="button">Remover</button>';
    cols += '</td>';

    newRow.append(cols);

    $("#products-table").append(newRow);

    ++currentRow;

    return false;
};

And your PHP script that inserts the data, could look like this:

$pdo = Database::conexao(); 

$stmt = $pdo->prepare('INSERT INTO cad_dependentes (nome, cpf, cargo, email, parentesco) VALUES (:nome, :cpf, :cargo, :email, :parentesco)'); 

foreach ($_POST['usuarios'] as $usuario) { 

    $stmt->bindParam(':nome', $usuario['nome'], PDO::PARAM_STR); 
    $stmt->bindParam(':cpf', $usuario['cpf'], PDO::PARAM_STR); 
    $stmt->bindParam(':cargo', $usuario['cargo'], PDO::PARAM_STR); 
    $stmt->bindParam(':email', $usuario['email'], PDO::PARAM_STR); 
    $stmt->bindParam(':parentesco', $usuario['parentesco'], PDO::PARAM_STR); 

    $stmt->execute(); 

}

Note that I only used foreach in $_POST['usuarios'] . I did this to make it easier and readable what is being done on each line inserted.

Each line inserts by its jQuery, would be equivalent to this:

<form method="post">

        <input type="text" name="usuarios[0][nome]">
        <input type="text" name="usuarios[0][idade]">
        <input type="text" name="usuarios[0][email]">
        <hr/>
        <input type="text" name="usuarios[1][nome]">
        <input type="text" name="usuarios[1][idade]">
        <input type="text" name="usuarios[1][email]">

    <input type="submit" value="Submete Aí!">
</form>

<?php

    if ($_SERVER['REQUEST_METHOD'] === "POST") {

        print_r($_POST['usuarios']);
    }
?>

So, see the result:

    
15.12.2016 / 17:36
5

Well, you need a loop to do this insertion, so try:

for($i=0; $i < count($_POST['nome']); $i++)
{
  $nome = mysql_real_escape_string($_POST['nome'][$i]);
  $cpf = mysql_real_escape_string($_POST['cpf'][$i]);
  $cargo = mysql_real_escape_string($_POST['cargo'][$i]);
  $email = mysql_real_escape_string($_POST['email'][$i]);
  $parentesco = mysql_real_escape_string($_POST['parentesco'][$i]);

  mysql_query("INSERT INTO cad_dependentes (nome, cpf, cargo, email, parentesco) VALUES ('$nome', '$cpf', '$cargo', '$email', '$parentesco')") or die(mysql_error());
  echo "OK";
}

Change the name="cargo" to name="cargo[]" , following the @Wallace Maxters hint

Take a few minutes with this question: Why should not we use mysql_ * functions? *

    
14.12.2016 / 22:18