Total in shopping cart

2

I'm having trouble with the cart, if I put $preço =$linha['preço']; it displays the value correctly, but if I put number_format down, it zeroes out the result:

$preço = number_format((float) $linha['preço'] * $qtd, 2, ',', '.');

And the total of the products is not being done, I was told to have to use javascript, but I do not know javascript, can anyone help?

<?php
include(dirname(__FILE__) . './funcao/conecta.php');
session_start();

if (!isset($_SESSION['shop'])) {
    $_SESSION['shop'] = array();
}

if (isset($_GET['acao'])) { // adicionar produto
    $id = isset($_GET['id']) ? intval($_GET['id']) : null;
    if ($_GET['acao'] == 'add') {
        if (!isset($_SESSION['shop'][$id])) {
            $_SESSION['shop'][$id] = 1;
        }
    } elseif ($_GET['acao'] == 'del') {  //REMOVER shop
        if (isset($_SESSION['shop'][$id])) {
            unset($_SESSION['shop'][$id]);
        }
    }

//ALTERAR QUANTIDADE
    //Se existir $_POST['prod'] então começa..
    if (isset($_POST['prod']))
        if ($_GET['acao'] == 'atualizar') {
            if (is_array($_POST['prod'])) {
                foreach ($_POST['prod'] as $id => $qtd) {
                    $id = intval($id);
                    $qtd = intval($qtd);
                    if (!empty($qtd) || $qtd <> 0) {
                        $_SESSION['shop'][$id] = $qtd;
                    } else {
                        unset($_SESSION['shop'][$id]);
                    }
                }
            }
        }
}
?>

HTML:

<!doctype html>
<html>
    <head>
        <meta charset='utf8'>
        <title>Seja Bem Vindo!</title>
        <link rel="stylesheet" href="css/default.css">
    </head>
    <body>
        <div><h2>Suas Compras Efetuadas:</h2>
            <br>
            <table border="1" width="100%">
                <thead>
                    <tr>
                        <th width="10%">FOTO</th>
                        <th width="10%">NOME</th>
                        <th width="10%">DESCRIÇÃO</th>
                        <th width="10%">TAMANHO</th>
                        <th width="10%">COR</th>
                        <th width="10%">PREÇO</th>
                        <th width="10%">QTD.</th>
                        <th width="10%">SUBTOTAL</th>
                        <th width="10%">REMOVER</th>
                    </tr>
                </thead>
                <tr><td colspan="9">
                        <form action="?acao=atualizar" method="post">
                            <table><tfoot>
                                    <tr>
                                        <td><input type="submit" value="Atualizar"></td>
                                    </tr><tr>
                                        <td><a href="./index.php">Continuar Comprando</a></td>
                                    </tr><tr>
                                        <td><a href="./admin/finalizar.php">Finalizar Pedido</a></td>
                                </tfoot></table>
                        </form>
                    </td></tr>
                <tbody>
                    <?php
                    $total = 0;
                    if (count($_SESSION['shop']) == 0) {
                        echo '<tr><td colspan="9"><div class="#">O cesto de compras esta vazio!</td></tr>';
                    } else {
                        $conn = new PDO("mysql:host=localhost;dbname=loja", "root", "");
                        foreach ($_SESSION['shop'] as $id => $qtd) {
                            $cart = $conn->prepare("SELECT * FROM produtos WHERE  id=$id");
                            $cart->setFetchMode(PDO::FETCH_ASSOC);
                            $cart->execute();
                            while ($linha = $cart->fetch()) {
                                $foto = $linha['foto'];
                                $nome = $linha['nome'];
                                $descricao = $linha['descricao'];
                                $tamanho = $linha['tamanho'];
                                $cor = $linha['cor'];




                              $preço = number_format((float) $linha['preço'] * $qtd, 2, ',', '.');
                              $sub = number_format((float) $linha['preço'] * $qtd, 2, ',', '.');
                                $sub =  $linha['preço'] * $qtd;
                                $total += $preço;
                                $total = number_format($total, 2, ',', '.');
                                echo '<tr>
                                             <td><img src = "' . $foto . ' " width = "100px"</td>
                                             <td>' . $nome . '</td>
                                             <td>' . $descricao . '</td>
                                             <td>' . $tamanho . '</td>
                                             <td>' . $cor . '</td>

                                             <td>R$ ' . $preço . '</td>
                                             <td><input type="text" size="3" name="prod[' . $id . ']" value="' . $qtd . '" /></td>
                                             <td>R$ ' . $sub . '</td>
                                             <td colspan = "9"><a href="?acao=del&id=' . $id . '"><img src="./imagens/remover.png" width="70" height="70" ></td>
                                             </tr>';
                            }
                        }
                    }
                    ?>
            </table>
        </div>
    </body>
</html>
    
asked by anonymous 18.01.2016 / 16:31

1 answer

1

Dude, I ran a test on your code using the link site and ran normally.

Note:

1 - In good programming practice never use special characters like "ç" in the variables

2- Before concatenating, check that the variable is declared before ... in the "$ total + = $ price"; first of all put "$ total = 0;"

3 - Use floatval to convert the values "floatval ($ line ['price'])" and make sure the user is using "." instead of "," otherwise use replace in the variable.

<?php
$linha = Array();
$linha['preco'] = "5,5";
$linha['preco'] = str_replace(",",".",$linha['preco']);
$total =0; 
$qtd =3;
$preco = number_format(floatval($linha['preco']) * $qtd, 2, ',', '.');
$sub =  $linha['preco'] * $qtd;
$total += $preco;
echo '
<p>com o number_format: R$ ' . $preco . '</p>
<p>sem o number_format: R$ ' . $sub . '</p>';
 ?>
    
18.01.2016 / 16:56