Difficulty in saving 3 input with different name with foreach

0

Hello, I'm creating a shopping cart and I need to record the products selected by the customer via form. This is almost all working, just missing the products in the item sale table.

I made this foreach below to list the products with your data:

    <?php
    require("conexao.php");
    foreach($_SESSION['carrinho'] as $carrinho){

    echo '<tr style="font-size:11px; font-weight:bold; color:#000;">       
          <input size="1" type="hidden" name="codproduto" value="'.$codigo.'" />
          <input size="1" type="hidden" name="quant" value="'.$qtd.'" />
          <input size="5" type="hidden" name="preco" value="'.$preco.'" />
          </tr>';

    ?>
    <?php } ?>

But I can not record more than 1 product, if I buy 2, 3 or more products, it only writes the last one from the list.

I am publishing below the INSERT used to write the data to the table.

    <?php
    include '../conexao.php';

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

    $codvenda = mysql_insert_id();
    $codproduto = $_POST['codproduto'];
    $quant = $_POST['quant'];
    $preco = $_POST['preco'];

    mysql_query("INSERT INTO itemvenda (codvenda, codproduto, quant, preco) values ('$codvenda', '$codproduto', '$quant', '$preco')");
    }
    ?>

If friends can give me a light on how I should proceed so I can record all the products listed by foreach, I'll be grateful.

Hugs to all.

    
asked by anonymous 19.12.2015 / 04:20

1 answer

1

I solved the problem, changes were made to the INSERT, and so the code became.

INSERT page:

$codvenda = mysql_insert_id();
$codproduto = $_REQUEST['codproduto']; 
$quant = $_REQUEST['quant']; 
$preco = $_REQUEST['preco']; 

for($i=0; $i<count($codproduto) AND ($quant) AND ($preco); $i++){   

$query_insert = mysql_query("INSERT INTO itemvenda (codvenda, codproduto, quant, preco) values ('$codvenda', '$codproduto[$i]', '$quant[$i]', '$preco[$i]')");
        //printf("Last inserted record has id %d\n", mysql_insert_id());
}

And in the Form was added [] after the names of the names in the input:

Form:

    echo '<tr style="font-size:11px; font-weight:bold; color:#000;">       
        <input size="1" type="hidden" name="codproduto[]" value="'.$codigo.'" />
        <input size="1" type="hidden" name="quant[]" value="'.$qtd.'" />
        <input size="5" type="hidden" name="preco[]" value="'.$preco.'" />
      </tr>';

I hope this publication can help other curious people like me solve this kind of problem.

Thanks for everyone's attention, and big hug.

    
19.12.2015 / 23:48