Difficulties with PHP and Mysql Dynamic Insert

Asked

Viewed 175 times

-2

I am developing a system where the user inserts lines as needed (this part is already ready). I’m having trouble generating PHP and the database to save the records, this is the first time I had to generate a input dynamic. I attach the HTML code and the scripts used

<div class="box-content">

<script src="<?php echo INCLUDE_PATH_PAINEL ?>js/jquery.js"></script>
<!--script src="<?php echo INCLUDE_PATH_PAINEL ?>js/jquery.mask.js"></script>
<script src="<?php echo INCLUDE_PATH_PAINEL ?>js/jquery.mask.min.js"></script-->

<link href="<?php echo INCLUDE_PATH_PAINEL ?>css/css/select2.min.css" rel="stylesheet" />
<script src="<?php echo INCLUDE_PATH_PAINEL ?>js/js/select2.min.js"></script>

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.12.0/css/all.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.12.0/css/v4-shims.css">

<script>
    jQuery(function($){
       $('.CPF').mask('999.999.999-99');
       $('.CNPJ').mask('99.999.999/9999-99');
       $('#CPFconjuge').mask('999.999.999-99');
       $('.RG').mask('AA-99.999.999'); 
       //$('#ClienteDtNasc').mask('99/99/9999'); 
       //$('#DataExp').mask('99/99/9999'); 
       //$('#dt_exp_cart').mask('99/99/9999'); 
       $('.Celular').mask('(99)99999-9999');
       $('.Telefone').mask('(99)9999-9999');
       $('#whatsapp').mask('(99)99999-9999'); 
       $('#placa').mask('AAA-9999');
       $('#CEP').mask('99999-999');
       $('.moeda').mask('#.##0,00', {reverse: true});

    });
</script>



<h2><i class="fas fa-bacon"></i> Cardápio  <i class="fas fa-bacon"></i></h2>

<form method="post" enctype="multipart/form-data">

    <fieldset>
        <legend>Dados Produtos:</legend>

        <label>Categoria:</label>
        <select name="grupo" class="prod">
            <option disabled="" selected="">Selecione</option>
            <option value="Alimento">Alimento</option>
            <option value="Bebida">Bebida</option>
        </select>

        <label>Item:</label>
        <input type="text" name="nome_item">

        <label>Preço Unitário:</label>
        <input type="text" name="preco_compra" class="moeda">

        <label>Descrição:</label>
        <textarea name="desc"> </textarea>
    </fieldset>

    <fieldset>
        <legend>Ingredientes:</legend>


        <table id="products-table">
            <tr>
                <th>Produto</th>
                <th>Quantidade Utilizada</th>
                <th>Remover</th>
            <tr>
            <tr class="row">

            </tr>

        </table>

        <div class="botoes" style="text-align: center">
            <button onclick="AddTableRow()" type="button"><i class="fas fa-utensil-spoon"></i>   Adicionar ingrediente</button>

            <!--button onclick="RemoveTableRow()" type="button"><i class="fas fa-trash-alt"></i>    Remover</button-->
        </div>
    </fieldset>


    <div class="botoes">
        <div class="clear"></div>
        <div><button type="submit" name="acao">Enviar</button></div>
        <div><button type="reset" style="margin:15px;" class="bt">Limpar</button></div> 
    </div>
        <div class="clear"></div>

</form>
<script> 
    $('.prod').select2({    
    });
</script>

<script>

    RemoveTableRow = function(handler) {
        var tr = $(handler).closest('tr');
        tr.fadeOut(400, function() {
            tr.remove();
        });
        return false;
    };

    let num = 1; //num criado aqui

    AddTableRow = function() {

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

            var cols = "";

            cols += '<td class="col-md-3"><select class="form-control prod produto" name="produto'+ num + '"> <option selected="" disabled="">Selecione </option> <?php 
                            $result = MySql::conectar()->prepare("SELECT * FROM `produto`");
                            $result->execute(); 
                            foreach($result as $valor){     
                        ?> <option value="<?php echo $valor['ID']?>"><?php echo $valor['nome_produto'] ?></option><?php
                            }
                        ?></select></td>';
            cols += '<td class="col-md-3"><input type="text" class="form-control qtd_usada" name="qtd_usada' + num + '"></td>';
            cols += '<td class="col-md-3">'+'<a class="btn delete" onclick="RemoveTableRow(this)" type="button"><i class="fas fa-trash-alt"></i></a>'+ '</td>';

            num++; //numero aumenta aqui

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

            return false;
    };
</script>

<script>
    /*function ajustarNomes(){
        $(".table tr").each(function(indice){
            $(this).find('.produto').attr("name", "produto" + indice);
            $(this).find('.qtd_usada').attr("name", "qtd_usada" + indice);
        });
    }

    $(".amount, .price").unbind('blur keyup');
    $(".amount, .price").on("blur keyup",function(){
            const tr = $(this).parent().parent();

            const quant = parseInt(tr.find('.amount').val());
            const valor = parseInt(tr.find('.price').val());
            var total = quant * valor;

            if (!isNaN(quant) && !isNaN(valor)){
                tr.find('.total').html('<input readonly type="text" class="form-control" name="total" value=" '+total+' ">');
             }
        }


    */
</script>

  • Monique is not clear his difficulty, is having trouble picking up the form values after saving?

1 answer

0


What you need to do is turn the fields into arrays. For example, instead of:

<input type="text" name="nome_item">

Change to

<input type="text" name="nome_item[]">

This way, you can create as many forms as you want. By doing the post, you loop the array elements and save to separate records.

$nome_item =  $_POST['nome_item'];
$quant_linhas = count($nome_item);
// Recupepando os dados
for ($i=0; $i<$quant_linhas; $i++) {
    echo  "nome: ".$nome_item[$i]."<br />";
    $nome = $nome_item[$i];
    //Insert para gravar no banco
}

Here’s an example that shows how this works. I have the dynamic form creation and programming executed after posting the forms data.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Adicionando linhas dinamicamente</title>
<style type="text/css" media="all">
  body{ font-family:Arial, Helvetica, sans-serif }
  #tudo{ border:#CCCCCC 1px solid;width:680px;margin:0 auto }
  .bd_titulo{
    text-align:center;
    background-color:#CCCCCC;
    font-weight:bold
  }
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<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>
</head>
<body>
<form method="post" name="frm_campo_dinamico" action="">
<div id="tudo">
<table border="0" cellpadding="2" cellspacing="4">
  <tr><td colspan="4" class="bd_titulo">Adicionando Linhas Dinamicamente</td></tr>
  <tr><td colspan="4" align="center"><a href="http://www.linhadecomando.com" target="_blank">www.linhadecomando.com</a></td></tr>
 
  <tr><td class="bd_titulo" width="10">Qtde</td><td class="bd_titulo">Descrição</td><td class="bd_titulo">Cor</td><td class="bd_titulo">Valor R$</td></tr>
  <tr class="linhas">
    <td><input type="text" name="qtd[]" style="text-align:center" /></td>
    <td><input type="text" name="descricao[]" /></td>
    <td>
      <select name="cor[]">
        <option value="" selected="selected">Selecione uma cor...</option>
        <option value="Amarelo">Amarelo</option>
        <option value="Branco">Branco</option>
        <option value="Cinza">Cinza</option>
        <option value="Verde">Verde</option>            
      </select>
    </td>
    <td><input type="text" name="valor[]" style="text-align:center" /></td>
    <td><a href="#" class="removerCampo" title="Remover linha"><img src="images/minus.png" border="0" /></a></td>
  </tr>
  <tr><td colspan="4">
        <a href="#" class="adicionarCampo" title="Adicionar item"><img src="images/plus.png" border="0" /></a>
	</td></tr>
  <tr>
        <td align="right" colspan="4"><input type="submit" id="btn-cadastrar" value="Cadastrar" /></td>
  </tr> 
</table>
</form>
</div>
<?php 
 
if ($_POST){
   $qtd 	 = $_POST['qtd'];
   $descr 	 = $_POST['descricao'];
   $cor          = $_POST['cor'];
   $valor	 = $_POST['valor'];
   $quant_linhas = count($qtd);
 
   // exibindo os dados
   for ($i=0; $i<$quant_linhas; $i++) {
	echo  "Quantidade: ".$qtd[$i]."<br />";
	echo  "Descrição: ".$descr[$i]."<br />";
	echo  "Cor: ".$cor[$i]."<br />";
	echo  "Valor: ".$valor[$i]."<br />";
  //Seu insert para gravar no banco pode ser inserido aqui
   }
 
}
?>
</body>
</html>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.