Sending of Product Order

Asked

Viewed 137 times

-1

Guys, I’m putting together a product order shipping system, on the product selection page, we have the selection of them, where each one will have a input, however, undetermined, how do I send all this inputs to the base, regardless of the quantity?

PHP

$produtos = $_POST['produto_solicitado'];      
foreach($_POST['quantidade'] as $indice => $quanti){
    $produtos_selecionado=$produtos[$indice];
}
$usuario_bd = 'root';
$senha_bd   = '';
$host_db    = 'localhost';
$base_dados_pedidos = 'psaude_pedidos_' . $chns_cliente;
$charset_db = 'utf8';
$conexao_pdo = null;
$detalhes_pdo_pedidos  = 'mysql:host=' . $host_db;
$detalhes_pdo_pedidos .= ';dbname='. $base_dados_pedidos;
$detalhes_pdo_pedidos .= ';charset='. $charset_db;
try {
    $conexao_pdo_pedidos = new PDO($detalhes_pdo_pedidos, $usuario_bd, $senha_bd);
} catch (PDOException $e_pedidos) {
    print "Erro: " . $e_pedidos->getMessage() . "<br/>";
    die();
}
$username_table = 'pedido_' . $chns_cliente . '_' . $PedidoID;
$prepara_table = $conexao_pdo_pedidos->prepare("CREATE TABLE $username_table (`id` int(11) NOT NULL, `produto` longtext NOT NULL, `valor_org` longtext NOT NULL, `valor_desc` longtext NOT NULL, `quantidade` longtext NOT NULL, `valor_total_prod` longtext NOT NULL, `obs` longtext NOT NULL, `data_pedido` longtext NOT NULL, `chns` longtext NOT NULL, `para` longtext NOT NULL, `quem` longtext NOT NULL, `pedido` longtext NOT NULL,PRIMARY KEY (id))");
$prepara_table_autoinc = $conexao_pdo_pedidos->prepare("ALTER TABLE $username_table MODIFY `id` int(11) NOT NULL AUTO_INCREMENT");
$prepara = $conexao_pdo_pedidos->prepare("INSERT INTO $username_table (`produto`,`valor_org`,`valor_desc`,`valor_total_prod`,`quantidade`,`obs`,`data_pedido`,`chns`,`para`,`quem`,`pedidoID`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$verifica_table = $prepara_table->execute();
$verifica_table_autoinc = $prepara_table_autoinc->execute();
$verifica = $prepara->execute(  
   array(
          $produtos_selecionado,
          $valor_org,
          $valor_desc,
          $valor_total_prod,
          $quantidade,
          $obs,
          $data_pedido,
          $chns,
          $para,
          $quem,
          $pedidoID
    )
);
if ( $verifica ) {
    echo "Pedido Enviado";
}

HTML

<form action="<?echo$endereco;?>assets/inc/envia/pedido" class="form_planeta" id='form_planeta' method="post">
    <input type="text" id="autocomplete-input" class="autocomplete" name="empresa">
    <input name="produto_solicitado[]" value="787879" class="hide">
    <input name="quantidade[]" value="12" class="">
    <input name="produto_solicitado[]" value="7878798" class="hide">
    <input name="quantidade[]" value="1" class="">
    <button type="submit" class="waves-effect site envia_again">
    <p class="wht">Cadastrar Pedido</p></button>
</form>
  • 1

    Put what you have done. What the problem is and what you want. That way your question will probably be closed.

  • Those inputs are of the type checkbox? You’re trying to do this through a form with submit or with javascript?

  • @Leocaracciolo, I’m having a problem with the array conversion when going to do the insert, the message is "Array to string Conversion". $produtos = $_POST['produto_solicitado']; &#xA;foreach($_POST['produto_solicitado'] as $indice => $valor){&#xA; $produtos_selecionado=$produtos[$indice];&#xA;}

  • I am using PDO with the inclusion in array(); $verifica = $prepara->execute(&#xA; array(&#xA; $produtos_selecionado&#xA; )&#xA;)

  • @Leocaracciolo, I switched to insertion with mysql as in the link you sent, but only one product is being included, the others it ignores. A name of input are with the [], but still ignores.

  • Without code posted it is difficult to analyze the difficulty. You’ll get better answers if you give people code they can use to reproduce the problem

  • @Leocaracciolo, I added the code to the question.

  • I think I got it wrong, how are your inputs?

  • <input type="text" name="produto_solicitado[]" value="7878798">

  • It is not the solution to the problem but your INSERT statement has two fixes to make: the column created in the database is pedido and not pedidoID as it is in the INSERT declaration, Invalid parameter number: the number of linked variables does not match, one is missing ? Furthermore, it remains to know the HTML structure of the form to understand how the data are passed.

  • I made the corrections and it worked, I just made another foreach to the quantidade[] to inhibit conversion that was not being made from array. But only one input is still being added. I updated the question with html code

Show 6 more comments

1 answer

1


I had already developed a system based on the information that was in your question before you edit it, however, I think you can take advantage of my answer - ( mainly in what is commented with // prepare e bind and // definir parâmetros e executar which are the key points) - and adapt your need.

With your connection, with me it didn’t work, so I changed in the example

PHP

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

    $PedidoID= ($_POST['pedido']);
    $array = ($_POST['produto_solicitado']);
    $quant=count($array);
    $chns_cliente="leo";

    // conexão
    $hostname="localhost";  
    $username="USUARIO";  
    $password="SENHA";  
    $db = "NOME_DB"; 

    $conn = new mysqli($hostname, $username, $password, $db);

    // Checa conexão
    if ($conn->connect_error) {
        die("Conexão falhou: " . $conn->connect_error);
    }

    $username_table = 'pedido_' . $chns_cliente . '_' . $PedidoID;
    $prepara_table = $conn->prepare("CREATE TABLE $username_table (`id` int(11) NOT NULL, `produto` longtext NOT NULL, `valor_org` longtext NOT NULL, `valor_desc` longtext NOT NULL, `quantidade` longtext NOT NULL, `valor_total_prod` longtext NOT NULL, `obs` longtext NOT NULL, `data_pedido` longtext NOT NULL, `chns` longtext NOT NULL, `para` longtext NOT NULL, `quem` longtext NOT NULL, `pedido` longtext NOT NULL,PRIMARY KEY (id))");
    $prepara_table_autoinc = $conn->prepare("ALTER TABLE $username_table MODIFY `id` int(11) NOT NULL AUTO_INCREMENT");

    $verifica_table = $prepara_table->execute();
    $verifica_table_autoinc = $prepara_table_autoinc->execute();


    // prepare e bind
    $stmt = $conn->prepare("INSERT INTO $username_table (produto,valor_org,valor_desc,valor_total_prod,quantidade,obs,data_pedido,chns,para,quem,pedido) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("sssssssssss", $produto, $valor_org, $valor_desc, $valor_total_prod, $quantidade, $obs, $data_pedido, $chns, $para, $quem, $pedido);

    // definir parâmetros e executar
    for ( $a=0; $a<$quant; $a++ ) {
        $check = $array[$a]['quantidade'];
        if($check!=""){
            $produto = $array[$a]['produto'];
            $valor_org = $array[$a]['valor_org'];
            $valor_desc = $array[$a]['valor_desc'];
            $valor_total_prod = $array[$a]['valor_total_prod'];
            $quantidade = $array[$a]['quantidade'];
            $obs = $array[$a]['obs'];
            $data_pedido = $array[$a]['data_pedido'];
            $chns = $array[$a]['chns'];
            $para = $array[$a]['para'];
            $quem = $array[$a]['quem'];
            $pedido = $array[$a]['pedido'];
            $stmt->execute();
        }
    }

    $stmt->close();
    $conn->close();

}

$PedidoID=rand(5, 150000);

Library and script (optional)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script language="javascript">
$(document).ready(function () {
   $('.somente-numero').keyup(function (e) {
        var v3 ="";
        var currentVal = $(this).val();
        var replaceD = currentVal.replace(/[^0-9\.]/g, '');
        $(this).val(replaceD);
        var v1 = Number($(this).prev().prev().val());
        var v2 = Number($(this).val());
        v3 = ($(this).prev().val());
        v3 = Number(v3.substring(0, v3.length - 1));
        var calculatedval = parseFloat((v1-(v3*(v1/100))) * v2).toFixed(2);
        $(this).next().val(calculatedval);
   });
});
</script>

HTML

<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">

<!-- numero pedido -->
<input type="hidden" name="pedido" value="<?php echo $PedidoID; ?>" />

<!-- produto 1 -->
<input type="text" name="produto_solicitado[0][produto]" value="7878797" />
<input type="text" name="produto_solicitado[0][valor_org]" value="100.00" readonly />
<input type="text" name="produto_solicitado[0][valor_desc]" value="5%" placeholder="valor_desc" readonly />
<input type="text" class="somente-numero" name="produto_solicitado[0][quantidade]" value="" placeholder="quantidade"/>
<input type="text" name="produto_solicitado[0][valor_total_prod]" value="" placeholder="valor_total_prod" readonly />
<input type="text" name="produto_solicitado[0][obs]" value="" placeholder="obs"/>
<input type="text" name="produto_solicitado[0][data_pedido]" value="" placeholder="data_pedido"/>
<input type="text" name="produto_solicitado[0][chns]" value="" placeholder="chns"/>
<input type="text" name="produto_solicitado[0][para]" value="" placeholder="para"/>
<input type="text" name="produto_solicitado[0][quem]" value="" placeholder="quem"/>
<input type="hidden" name="produto_solicitado[0][pedido]" value="<?php echo $PedidoID; ?>" />

<br>
<!-- produto 2 -->
<input type="text" name="produto_solicitado[1][produto]" value="7878798" />
<input type="text" name="produto_solicitado[1][valor_org]" value="150.00" readonly />
<input type="text" name="produto_solicitado[1][valor_desc]" value="5%" placeholder="valor_desc" readonly />
<input type="text" class="somente-numero" name="produto_solicitado[1][quantidade]" value="" placeholder="quantidade"/>
<input type="text" name="produto_solicitado[1][valor_total_prod]" value="" placeholder="valor_total_prod" readonly />
<input type="text" name="produto_solicitado[1][obs]" value="" placeholder="obs"/>
<input type="text" name="produto_solicitado[1][data_pedido]" value="" placeholder="data_pedido"/>
<input type="text" name="produto_solicitado[1][chns]" value="" placeholder="chns"/>
<input type="text" name="produto_solicitado[1][para]" value="" placeholder="para"/>
<input type="text" name="produto_solicitado[1][quem]" value="" placeholder="quem"/>
<input type="hidden" name="produto_solicitado[1][pedido]" value="<?php echo $PedidoID; ?>" />

<br>
<!-- produto 3 -->
<input type="text" name="produto_solicitado[2][produto]" value="7878799" />
<input type="text" name="produto_solicitado[2][valor_org]" value="200.00" readonly />
<input type="text" name="produto_solicitado[2][valor_desc]" value="5%" placeholder="valor_desc" readonly />
<input type="text" class="somente-numero" name="produto_solicitado[2][quantidade]" value="" placeholder="quantidade"/>
<input type="text" name="produto_solicitado[2][valor_total_prod]" value="" placeholder="valor_total_prod" readonly />
<input type="text" name="produto_solicitado[2][obs]" value="" placeholder="obs"/>
<input type="text" name="produto_solicitado[2][data_pedido]" value="" placeholder="data_pedido"/>
<input type="text" name="produto_solicitado[2][chns]" value="" placeholder="chns"/>
<input type="text" name="produto_solicitado[2][para]" value="" placeholder="para"/>
<input type="text" name="produto_solicitado[2][quem]" value="" placeholder="quem"/>
<input type="hidden" name="produto_solicitado[2][pedido]" value="<?php echo $PedidoID; ?>" />


<button type="submit" class="waves-effect site envia_again">
    <p class="wht">Cadastrar Pedido</p></button>
</form>

If the user gives refresh the request will be inserted again in the same table. To avoid this make a select and if there is no return, ie - if(empty($result)), proceed with the next steps to insert into the database:

...............
...............

$username_table = 'pedido_' . $chns_cliente . '_' . $PedidoID;

$query = "SELECT pedido FROM $username_table";

$result = mysqli_query($conn, $query);

if(empty($result)) {

$prepara_table = $conn->prepare("CREATE TABLE $username_table (`id` int(11) NOT NULL, `produto` longtext NOT NULL, `valor_org` longtext NOT NULL, `valor_desc` longtext NOT NULL, `quantidade` longtext NOT NULL, `valor_total_prod` longtext NOT NULL, `obs` longtext NOT NULL, `data_pedido` longtext NOT NULL, `chns` longtext NOT NULL, `para` longtext NOT NULL, `quem` longtext NOT NULL, `pedido` longtext NOT NULL,PRIMARY KEY (id))");
$prepara_table_autoinc = $conn->prepare("ALTER TABLE $username_table MODIFY `id` int(11) NOT NULL AUTO_INCREMENT");

$verifica_table = $prepara_table->execute();
$verifica_table_autoinc = $prepara_table_autoinc->execute();

// prepare e bind
$stmt = $conn->prepare("INSERT INTO $username_table (produto,valor_org,valor_desc,valor_total_prod,quantidade,obs,data_pedido,chns,para,quem,pedido) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssssssss", $produto, $valor_org, $valor_desc, $valor_total_prod, $quantidade, $obs, $data_pedido, $chns, $para, $quem, $pedido);

// definir parâmetros e executar
for ( $a=0; $a<$quant; $a++ ) {
    $check = $array[$a]['quantidade'];
    if($check!=""){
        $produto = $array[$a]['produto'];
        $valor_org = $array[$a]['valor_org'];
        $valor_desc = $array[$a]['valor_desc'];
        $valor_total_prod = $array[$a]['valor_total_prod'];
        $quantidade = $array[$a]['quantidade'];
        $obs = $array[$a]['obs'];
        $data_pedido = $array[$a]['data_pedido'];
        $chns = $array[$a]['chns'];
        $para = $array[$a]['para'];
        $quem = $array[$a]['quem'];
        $pedido = $array[$a]['pedido'];
        $stmt->execute();
    }
}

$stmt->close();

}else{
    echo "tabela já existe";
}
..............
..............

If you choose not to use jquery, remove inputs readonly

  • Dude, you saved me. But just one more question, the customer will select the desired products, and this is playing kind of in the cart with ajax, as the inputs are already pre-defined by [1], [2]... has how when it selects, that numbering be generated automatically, in order of addition? I tried to do to get by id of the product in DB but did not work by the order of offset.

  • @Thomasfranklin, just setting the stage and doing tests.

Browser other questions tagged

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