Difficulty writing 3 different input names with foreach

Asked

Viewed 76 times

0

Hello, I am creating a shopping cart and need to record via form the products selected by the customer. Almost everything is working, missing only record the products in the table itemvenda.

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’t write more than 1 product, if I buy 2, 3 or more products, it only records the last one on the list.

I’m putting down the INSERT used to save data to 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 that I can record all products listed by foreach, I would be grateful.

Hugs to all.

  • How is Voce "inserting" the data into the super global $_SESSION ? so it seems Voce is inserting one string at a time! try to create an array and store in the super global.

  • Hello Rafael Acioly, beauty? You show me how to create the array, because I’m a beginner in PHP, but I’m trying to learn how to work with it.

1 answer

1

I solved guys, changes were made in INSERT, and so was the code.

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 that this publication can help other curious like me to solve this kind of problem.

Thanks for everyone’s attention, and big hug.

Browser other questions tagged

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