change a foreach view according to the data it receives

Asked

Viewed 69 times

1

I don’t know exactly how to ask this question, I’m developing a pizzeria system, where it has a very simple shopping cart that picks up the pizza id and displays in the cart when the customer selects, however I need to send two flavored pizza to this shopping cart and I don’t know how to do am beginner someone could help me, I will try to clarify as best as I can.

I have a menu that has items registered in the database, the menu shows pizzas of a flavor as for example: mozzarella, so far so good

on the menu there is a menu of pizzas two flavors where the customer selects two flavors and sends two Ids via ajax to the cart but the cart only picks up an id

follows the code that picks up the ids

<?php
session_start();
if (!isset($_SESSION['carrinho'])) {
    $_SESSION['carrinho'] = array();
} //adiciona produto
if (isset($_GET['acao'])) {
    //ADICIONAR CARRINHO
    if ($_GET['acao'] == 'add') {
        $id = intval($_GET['id']);
        if (!isset($_SESSION['carrinho'][$id])) {
            $_SESSION['carrinho'][$id] = 1;
        } else {
            $_SESSION['carrinho'][$id]+= 1;
        }
    }

    //REMOVER CARRINHO
    if ($_GET['acao'] == 'del') {
        $id = intval($_GET['id']);
        if (isset($_SESSION['carrinho'][$id])) {
            unset($_SESSION['carrinho'][$id]);
        }
    } //ALTERAR QUANTIDADE
    if ($_GET['acao'] == 'up') {
        if (is_array($_POST['prod'])) {
            foreach ($_POST['prod'] as $id => $qtd) {
                $id = intval($id);
                $qtd = intval($qtd);
                if (!empty($qtd) || $qtd <> 0) {
                    $_SESSION['carrinho'][$id] = $qtd;
                } else {
                    unset($_SESSION['carrinho'][$id]);
                }
            }
        }
    }
}

and the code of the foreach iterating the array and displaying the products

                   <?php
    $total = 0;
    foreach ($_SESSION['carrinho'] as $id => $qtd) {
        $sql = "SELECT *  FROM cadprod WHERE id_prod= '$id'";
        $qrs = mysqli_query($conn1, $sql) or die(mysqli_error($conn1));
        $lns = mysqli_fetch_assoc($qrs);
        $nome = $lns['nome_prod'];
        $preco = number_format($lns['preco_prod'], 2, ',', '.');
        $valor = $lns['preco_prod'];
        $sub = number_format($lns['preco_prod'] * $qtd, 2, ',', '.');
        $total+= $lns['preco_prod'] * $qtd;
                        echo '<tr>
                        <td data-th="Produto">
                                <div class="row">
                                    <div class="col-sm-10">
                                        <h4 class="nomargin text-uppercase text-center">' . $nome . '</h4>
                                    </div>
                                </div>
                            </td>
                            <td class="text-center" data-th="Quantidade"><input  class="form-control text-center" type="number" size="3" name="prod[' . $id . ']" value="' . $qtd . '" /></td>
                            <td data-th="valor"  class="text-center">R$ ' . $preco . '</td>
                            <td data-th="Subtotal" class="text-center">R$ ' . $sub . '</td>
                            <td  data-th=" ">
                                <a  href="carrinho.php?link=' . $bdv . '&acao=del&id=' . $id . '" class="pegaHref btn btn-danger btn-md"><i class="fa fa-trash-o"></i></a>                      
                            </td>
                        </tr>';
    }

     $subtotal = number_format($total, 2, '.', ',');

$frete = str_replace(",",".", $frete);
$frete =  floatval($frete);   
$valortotal = $frete + $total;
$valortotal = floatval($valortotal);




}
    ?>  

i am trying to make the time the user select two flavors show the two flavors of the pizza in the cart with the value of the most expensive.

1 answer

2


Dear follows a suggested solution, I hope you understand, any doubt I reply again.

First if you must confirm that the two values are being sent, I recommend using comma to concatenate

//concatena os ids como a baixo (ou dentro de um laço de repetição pra ser mais inteligente)
ids = opcao1 + "," + opcao2; //exemplo simples
$.ajax({
 url:"..",
 data:{ids:ids}
})

on the server the most significant change will be

//$_SESSION['carrinho'][$id] = 1;
 $_SESSION['carrinho'][] = [$ids,1];



//para que em algum momento seja manipulado o array de sabores de um pedido
foreach( $_SESSION['carrinho'] as $unidade){

$pizza['sabores'] = $unidade[0].split(","); //retorna array
$pizza['quantidade'] = $unidade[1];
//ok para um ou vários ids de sabor

}

this increases the complexity of the code a little but the effort will definitely be rewarded

Browser other questions tagged

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