Retrieve dynamic input and insert into bank with procedure

6

I'm having trouble inserting input data from a dynamic input. My procedure only inserts once, it follows my code where I get the data:

   $ddd     = $_POST['ddd'];
   $userid  = $_POST['userid'];
   $idusuario = $_POST['idusuario'];
   $telefone    = $_POST['telefone'];
   $obs         = $_POST['obs'];
   $quant_linhas = count($ddd);

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

        $sql = "Call telefone_i(
        '".$userid[$i]."',
        '".$ddd[$i]."',
        '".$telefone[$i]."',
        '".$obs[$i]."',
        '".$idusuario[$i]."'

         )";

   }

In this section is the jQuery that creates the dynamic inputs:

<script type="text/javascript">
$(function () {
  function removeCampo() {
    $(".removerCampo").unbind("click");
    $(".removerCampo").bind("click", function () {
       if($("tr.linhas").length > 1){
        $(this).parent().parent().remove();
       }
    });
  }

  $(".adicionarCampo").click(function () {
    novoCampo = $("tr.linhas:first").clone();
    novoCampo.find("input").val("");
    novoCampo.insertAfter("tr.linhas:last");
    removeCampo();
  });
});

</script>

Follow the excerpt related to the inputs:

<div class="content" style="min-height: 150px;">
   <!-- CONTEUDO INICIO -->
    <center>
        <h2  style="background-color: #DDEBFF">Cadastrar Telefone</h2>
    </center>
    <div style=" margin-left:5px; padding: 5px; width: 600px; overflow:auto; border:#036 thin; border-style:dotted;">

<form action="telefone_inserir.php?id=<?php echo $usuario_id; ?>" method="post" enctype="multipart/form-data">
    <table class="list">
    <thead>
        <tr class="linhas">

            <td width="25%" class="right">DDD</td>

            <td class="left">

            <input type="text" name="ddd[]" value="" maxlength="2" style="width: 30px" />

            <input name="userid[]" type="hidden" value="<?php echo $id; ?>" />

            <input name="idusuario[]" type="hidden" value="<?php echo $usuario_id; ?>" />

            </td>

            <td width="25%" class="right">Telefone</td>

            <td class="left"><input type="text" name="telefone[]" value="" maxlength="9" style="width: 80px" /></td>

            <td width="25%" class="right">OBS:</td>

            <td class="left"><input type="text" name="obs[]" value="" maxlength="45" style="width: 200px" /></td>
            <td class="left"><a href="#" class="removerCampo" title="Remover linha"><img src="imagens/exc_btn.png" border="0" /></a></td>

        </tr>
          <tr><td colspan="7">
        <a href="#" class="adicionarCampo" title="Adicionar item"><img src="imagens/tel_btn.png" border="0" /></a>
    </td></tr>

         <tr>

            <td colspan="7" align="center" height="50">
                <input name="botao" type="image" value="Alterar" id="btn_salvar" src="imagens/cadastrar_btn.png">

            </td>
          </tr>


          </thead>
        </table>

    </form>

    </div>
<!-- CONTEUDO FIM -->
</div> 

My procedure:

CREATE DEFINER='root'@'localhost' PROCEDURE 'telefone_i'(
p_usuario_id int(11) ,
p_ddd int(3) ,
p_telefone int(9) ,
p_obs varchar(45) ,
p_usuario_lancamento int(11)
)
BEGIN

insert acad.telefone
    set
        usuario_id = p_usuario_id,
        ddd = p_ddd,
        telefone = p_telefone,
        obs = p_obs,
        data_lancamento = current_timestamp,
        usuario_lancamento = p_usuario_lancamento;
END

I tried to do this anyway but it did not work:

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

        $sql = mysqli_query($con, "Call telefone_i(
        '".$userid[$i]."',
        '".$ddd[$i]."',
        '".$telefone[$i]."',
        '".$obs[$i]."',
        '".$idusuario[$i]."'

         )");



   }

But my procedure inserts only 1 record and returns the error "Query was empty". I tried another way, but the same effect happens, just inserts a line and returns error. Here is the code snippet:

$msg =   mysql_query("Call telefone_i(
'".$userid[$i]."',
'".$ddd[$i]."',
'".$telefone[$i]."',
'".$obs[$i]."',
'".$idusuario[$i]."'

 )");

Thanks in advance for your help.

    
asked by anonymous 22.11.2015 / 00:10

4 answers

3

The problem it all seems to be, is in the way that the submission is executing and in the way it is trying to insert data into the database. An important detail I recommend is to remove the id from querystring , either for security or not to break the loop in your IDs.

If you need to pass something that should not be shown on your POST, send it in a "hidden" input.

OBS: I was a bit confused by the nomenclatures because you have two userid and idusuario fields but I understand that one of them is the , I suggest changing to make your code clearer, even for yourself:

$mysqli = new mysqli('localhost','root','senha','acad');
if (mysqli_connect_errno()) {
   printf("Falha na conexão: %s\n", mysqli_connect_error());
   exit();
}

if ($_POST) {
   if (count($_POST['telefone'])) {
      $i=0;
       foreach ($_POST['telefone'] as $telefone) {

           $data = array(
                         $_POST['userid'],
                         $_POST['ddd'][$i],
                         $telefone,
                         $_POST['obs'][$i],
                         $_POST['idusuario']
                   );

           $SQL = "CALL telefone_i('" . implode("','",$data) . "')";
           if ( ($result = $mysqli->query($SQL))===false ) {
                printf("Erro da Query: %s\nQuery enviada: %s\n",
                        $mysqli->error, $SQL);
                exit();
           } 
          $i++;   
       } //endforeach
   } 
}  

Your procedure should look like this:

DELIMITER $$

USE acad$$

DROP PROCEDURE IF EXISTS telefone_i$$

CREATE PROCEDURE telefone_i(
p_usuario_id int(11),
p_ddd int(3),
p_telefone int(9),
p_obs varchar(45),
p_usuario_lancamento int(11)
)
BEGIN

INSERT INTO telefone (
  usuario_id,
  ddd, 
  telefone,
  obs,
  data_lancamento,
  usuario_lancamento
) VALUES (p_usuario_id,
         p_ddd,
         p_telefone,
         p_obs,
         now(),
         p_usuario_lancamento
);

END$$
DELIMITER ;

Your HTML should look like this:

<div class="content" style="min-height: 150px;">
   <!-- CONTEUDO INICIO -->
    <center>
        <h2  style="background-color: #DDEBFF">Cadastrar Telefone</h2>
    </center>
    <div style=" margin-left:5px; padding: 5px; width: 600px; overflow:auto; border:#036 thin; border-style:dotted;">
    <form action="telefone_inserir.php" method="post" id="insercao_tel">
        <table class="list">
           <thead>
                 <tr class="linhas">
                   <td width="25%" class="right">DDD</td>
                   <td class="left">
                      <input type="text" name="ddd[]" maxlength="2" style="width: 30px" />
                   </td>
                   <td width="25%" class="right">Telefone</td>
                   <td class="left">
                      <input type="text" name="telefone[]" maxlength="9" style="width: 80px" />
                   </td>
                   <td width="25%" class="right">OBS:</td>
                   <td class="left">
                      <input type="text" name="obs[]" maxlength="45" style="width: 200px" />
                  </td>
                  <td class="left">
                      <a href="#" class="removerCampo" title="Remover linha"><img src="imagens/exc_btn.png" border="0" /></a>
                  </td>
               </tr>
               <tr>
                  <td colspan="7">
                      <a href="#" class="adicionarCampo" title="Adicionar item"><img src="imagens/tel_btn.png" border="0" /></a>
                  </td>
               </tr>
               <tr>
                  <td colspan="7" align="center" height="50">
                     <input name="userid" type="hidden" value="<?php echo $id; ?>" />
                     <input name="idusuario" type="hidden" value="<?php echo $usuario_id; ?>" />
                     <input name="botao" type="image" value="Alterar" id="btn_salvar" src="imagens/cadastrar_btn.png">
                 </td>
              </tr>
           </thead>
       </table>
    </form>
    </div>
    <!-- CONTEUDO FIM -->
</div>
    
24.11.2015 / 13:11
0

Is your insert in Stored Procedure wrong?

It looks like it's a update .

INSERT looks like this:

INSERT INTO TABELA (CAMPO_1, CAMPO_2) VALUES (VALOR_1, VALOR_2)

So, in your SP it would look like this:

insert into acad.telefone
(
    usuario_id, ddd, telefone, obs, data_lancamento, usuario_lancamento
)
values
(
   p_usuario_id,
   p_ddd,
   p_telefone,
   p_obs,
   current_timestamp,
   p_usuario_lancamento
)
    
24.11.2015 / 12:14
0

No need to create a procedure to do this insert, and in this case you are also losing performace because you are opening several transactions in the database.

The best way to do and do an INSERT as follows.

INSERT INTO table (a,b) VALUES (1,2), (2,3), (3,4);

Then use the following code:

$sql = "insert into acad.telefone (usuario_id, ddd, telefone, obs, data_lancamento, usuario_lancamento) VALUES ";

for ($i=0; $i<$quant_linhas; $i++) {
    $sql .= "(". '".$userid[$i]."' . "," . '".$ddd[$i]."' . "," . '".$telefone[$i]."' . "," . '".$obs[$i]."' . "," . '".$idusuario[$i]."' . ") "
}
    
24.11.2015 / 13:14
0

Your procedure is wrong, to enter values through a procedure, you should do something like this:

CREATE PROCEDURE _nome(...)
BEGIN 
     INSERT | UPDATE | DELETE
     INTO   | SET    | FIELD
     VALUES | WHERE  | WHERE
     ...
END

See the example:

DELIMITER //
CREATE PROCEDURE telefone_i(
                            p_usuario_id INT(11),
                            p_ddd INT(3),
                            p_telefone INT(9),
                            p_obs VARCHAR(45),
                            p_usuario_lancamento INT(11)
                            )
    BEGIN
        INSERT INTO acad.telefone (
            usuario_id,
            ddd,
            telefone,
            obs,
            data_lancamento,
            usuario_lancamento
        )   
        VALUES (
            p_usuario_id,
            p_ddd,
            p_telefone,
            p_obs,
            p_data_lancamento,
            p_usuario_lancamento
        );
    END //  

In the script php you can simply do this:

if(isset($_POST)){
    $i=0;
    foreach($_POST as $nome){
        $procedure = "CALL telefone_i({$_POST['userid'][$i]}, {$_POST['ddd'][$i]}, {$_POST['telefone'][$i]}, '{$_POST['obs'][$i]}', {$_POST['idusuario'][$i]})";
        if(!($query = $con->query($procedure))){
            die($con->error);
        }
        $i++;
    }
}

Within this loop, read with the values sent from the form, you can check, and so on.

    
24.11.2015 / 13:49