help with shop cart

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

tsalmeida
Forum Commoner
Posts: 38
Joined: Sat Jul 06, 2013 2:23 pm

help with shop cart

Post by tsalmeida »

I am developing a shopping cart.
In this cart I have to select whether the customer wants to share the value of the product more than once a month

example.
product costs $ 50.00, divided in three months would be 3 x $ 19.00, divided in six months would be 6x 10.00.

this part is right.

My problem is time to save it in the db.

to display the correct values I used a switch in every way that is selected brings a different value.

when I save the db, always brings the reset value, does not bring the value of the variable that place.

follows the codes.

SESSION

Code: Select all

     
session_start();
       
      if(!isset($_SESSION['carrinho'])){
         $_SESSION['carrinho'] = array();
      }
       
      //adiciona produto
       
      if(isset($_GET['acao'])){
          
         //ADICIONAR CARRINHO
         if($_GET['acao'] == 'add'){
            $idproduto = intval($_GET['idproduto']);
            if(!isset($_SESSION['carrinho'][$idproduto])){
               $_SESSION['carrinho'][$idproduto] = 1;
            }else{
               //$_SESSION['carrinho'][$idproduto] += 1;
            }
         }
          
         //REMOVER CARRINHO
         if($_GET['acao'] == 'del'){
            $idproduto = intval($_GET['id']);
            if(isset($_SESSION['carrinho'][$idproduto])){
               unset($_SESSION['carrinho'][$idproduto]);
            }
         }
		 
          
         //ALTERAR QUANTIDADE
         if($_GET['acao'] == 'up'){
            if(is_array($_POST['prod'])){
               foreach($_POST['prod'] as $idproduto => $qtd){
                  $idproduto  = intval($idproduto);
                  $qtd = intval($qtd);
                  if(!empty($qtd) || $qtd <> 0){
                     $_SESSION['carrinho'][$idproduto] = $qtd;
                  }else{
                     unset($_SESSION['carrinho'][$idproduto]);
                  }
               }
            }
         }
      }
SWITCH and html table

Code: Select all

 if(count($_SESSION['carrinho']) == 0){
                        echo '<tr><td colspan="5">Não há produto no carrinho</td></tr>';
                     }else{
                        require("conexao.php");
		
                          $total = 0;
						  
                        foreach($_SESSION['carrinho'] as $idproduto => $qtd){
                              $sql   = "SELECT *  FROM estoque WHERE idproduto= '$idproduto'";
                              $qr    = mysql_query($sql) or die(mysql_error());
                              $ln    = mysql_fetch_assoc($qr);
                              $idprodut = $ln['idproduto'];
                              $marca  = $ln['marca'];
                              $modelo  = $ln['modelo'];
                              $cor  = $ln['cor'];
                              $numero  = $ln['numero'];
                              $preco = number_format($ln['precovenda'], 2, ',', '.');
                              $sub   = number_format($ln['precovenda'] * $qtd, 2, ',', '.');
                               
                         
                             
                        //if (!empty($_POST)) {
        
        switch ($_POST['code']) {
			
			
                case 1: 
						$sql6 = mysql_query("SELECT precovenda FROM estoque WHERE idproduto= '$idproduto'");
						$resu6 = mysql_fetch_assoc($sql6);
						$value = $resu6['precovenda']; 
						$forma = 'A vista';
						$formacb = 'A Vista';
						$valuetotal = $value * 1;
                        break;
                case 2: 
                        $sql7 = mysql_query("SELECT precotres FROM estoque WHERE idproduto= '$idproduto'");
						$resu7 = mysql_fetch_assoc($sql7);
						$value = $resu7['precotres']; 
						$forma = '3x de ';
						$formacb = '3x';
						$valuetotal = $value * 3;
                        break;
				case 3: 
                        $sql8 = mysql_query("SELECT precoseis FROM estoque WHERE idproduto= '$idproduto'");
						$resu8 = mysql_fetch_assoc($sql8);
						$value = $resu8['precoseis']; 
						$forma = '6x de ';
						$formacb = '6x';
						$valuetotal = $value * 6;
                        break;
                //default:
                      //  $value = '';            
        }
        
//}
$total += $valuetotal * $qtd;
                           echo '<tr>
                     			<td>'.$idprodut.'</td>        
                                 <td>'.$marca.'</td>
                     			 <td>'.$modelo.'</td>
                  				 <td>'.$cor.'</td>
            					 <td>'.$numero.'</td>
                                 <td><input type="text" size="1" name="prod['.$idproduto.']" value="'.$qtd.'" /></td>
								 <td><form method="post" action="carrinho.php">
								 <select name="code" onchange="this.form.submit();">
										<option>'; if (!empty($_POST)){ echo $formacb; } else{ echo 'Selecione...'; } echo '</option>
										<option value="1">A Vista</option>
										<option value="2">3x</option>
										<option value="3">6x</option>
										</select>
                                 <td>'.$forma.' R$'. number_format($value, 2, ',', '.'). ' </td>';
								 echo '<td>R$ '. number_format($valuetotal, 2, ',', '.'). '</td>
                                 <td><a href="?acao=del&id='.$idproduto.'">Remove</a></td>
                              </tr>';
                        }
						
                         $total = number_format($total, 2, ',', '.');
                         $valuetota = number_format($valuetotal, 2, ',', '.');
						   
						   echo '<tr>
						   <td> </td>
                                    <td colspan="7">Total</td>
                                    <td>R$ '.$total.'</td>
									<td> </td>
                              </tr>';
                     }
               ?>

finish button and querys(in this part is my problem, whent i hit finish button, always send the variable $valuetota with 0)

Code: Select all

if(isset($_POST['enviar'])){
	$formapagamento = $_POST['forma'];	
	$sqlinserevenda = mysql_query("INSERT into pedido(valortotal,data,formapagamento) VALUES ('$total',NOW(),'$formapagamento')")or die(mysql_error());
	$idvenda = mysql_insert_id();
	
	foreach($_SESSION['carrinho'] as $idproduto => $qtd){	
	$valortemp1 = mysql_query("SELECT * FROM valortemp");
	$valortempr = mysql_fetch_assoc($valortemp1);
	$valorvenda = $valortempr['valortemp'];
	$sql1   = "SELECT *  FROM estoque WHERE idproduto= '$idproduto'";
	$qr1    = mysql_query($sql1) or die(mysql_error());
	$ln1    = mysql_fetch_assoc($qr1);
	//$sub1 = $ln1['precovenda'];
	
	$sqlinsereitens = mysql_query("INSERT into itenspedido(idpedido,idproduto,quantidadeitens,valorunitario,data) VALUES('$idvenda','$idproduto','$qtd','$valuetota',NOW())")or die(mysql_error());
	$sqlestoque = ("UPDATE estoque SET saldoestoque = saldoestoque - $qtd WHERE idproduto =  $idproduto ") or die(mysql_error());
	$sqlestoquesql    = mysql_query($sqlestoque) or die(mysql_error());
	
	$sqlestoque2 = ("UPDATE estoque SET totalsaida = totalsaida + $qtd WHERE idproduto =  $idproduto ") or die(mysql_error());
	$sqlestoquesql2    = mysql_query($sqlestoque2) or die(mysql_error());
		

}


	echo '<script> alert("Venda concluida!'.$valuetotal.'")</script>';
	echo '<script> window.location = "vender.php"</script>';
	unset($_SESSION['carrinho']);
	
	}

?>
<form action="" method="POST" enctype="multipart/form-data"> 
	<select id ="forma" name="forma">
		<option>Selecione...</option>
		<option value="Dinheiro">Dinheiro</option>
		<option value="Cartão de Crédito">Cartão de Crédito</option>
		<option value="Cartão de Débito">Cartão de Débito</option>
		<option value="Cheque">Cheque</option>
		<option value="Vale">Vale</option>
	</select>
	<input type="submit" name="enviar" value="Finalizar Venda" />
</form>
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: help with shop cart

Post by requinix »

You don't give $valuetota a value anywhere in that code. You may set it on another page but that doesn't matter because it's a different page.

It looks like you need to calculate the totals in that code too. Same way you calculated them on the other page.
tsalmeida
Forum Commoner
Posts: 38
Joined: Sat Jul 06, 2013 2:23 pm

Re: help with shop cart

Post by tsalmeida »

requinix wrote:You don't give $valuetota a value anywhere in that code. You may set it on another page but that doesn't matter because it's a different page.

It looks like you need to calculate the totals in that code too. Same way you calculated them on the other page.

i set this variable the format

Code: Select all

$valuetota = number_format($valuetotal, 2, ',', '.');
cant do this?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: help with shop cart

Post by requinix »

You can do that. But right now you're doing it on a different page, in a different PHP file, and that variable will disappear when the script finishes.
tsalmeida
Forum Commoner
Posts: 38
Joined: Sat Jul 06, 2013 2:23 pm

Re: help with shop cart

Post by tsalmeida »

requinix wrote:You can do that. But right now you're doing it on a different page, in a different PHP file, and that variable will disappear when the script finishes.

different page? why? i dont understand...

is there any way to resolve my problem?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: help with shop cart

Post by requinix »

Alright, one step at a time:

You posted three bits of code. What files do they belong to? Are they all in different files? Are two or all three of them in the same file?
tsalmeida
Forum Commoner
Posts: 38
Joined: Sat Jul 06, 2013 2:23 pm

Re: help with shop cart

Post by tsalmeida »

requinix wrote:Alright, one step at a time:

You posted three bits of code. What files do they belong to? Are they all in different files? Are two or all three of them in the same file?

i just separate to post here...they are in the same file.

full code

Code: Select all

<?php
//carrinho
      session_start();
       
      if(!isset($_SESSION['carrinho'])){
         $_SESSION['carrinho'] = array();
      }
       
      //adiciona produto
       
      if(isset($_GET['acao'])){
          
         //ADICIONAR CARRINHO
         if($_GET['acao'] == 'add'){
            $idproduto = intval($_GET['idproduto']);
            if(!isset($_SESSION['carrinho'][$idproduto])){
               $_SESSION['carrinho'][$idproduto] = 1;
            }else{
               //$_SESSION['carrinho'][$idproduto] += 1;
            }
         }
          
         //REMOVER CARRINHO
         if($_GET['acao'] == 'del'){
            $idproduto = intval($_GET['id']);
            if(isset($_SESSION['carrinho'][$idproduto])){
               unset($_SESSION['carrinho'][$idproduto]);
            }
         }
		 
          
         //ALTERAR QUANTIDADE
         if($_GET['acao'] == 'up'){
            if(is_array($_POST['prod'])){
               foreach($_POST['prod'] as $idproduto => $qtd){
                  $idproduto  = intval($idproduto);
                  $qtd = intval($qtd);
                  if(!empty($qtd) || $qtd <> 0){
                     $_SESSION['carrinho'][$idproduto] = $qtd;
                  }else{
                     unset($_SESSION['carrinho'][$idproduto]);
                  }
               }
            }
         }
      }
       
       


include 'administrativo.php';?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Carrinho de Compras</title>
</head>
 
<body>
<div id="carrinho">
<table>
    <caption>Carrinho de Compras</caption>
    <thead>
          <tr>
	            <th>Código</th>
	            <th >Marca</th>
				<th >Modelo</th>
				<th >Cor</th>
				<th >Numero</th>
	            <th >Quantidade</th>
	            <th >A Vista/Parcelado</th>
	            <th >Preço</th>
	            <th >Total</th>
	            <th >Remover</th>
          </tr>
    </thead>
    
            <form action="?acao=up" method="POST">
    <tfoot>
          <center> <tr>
            <td colspan="5"><input type="submit" value="Atualizar Carrinho" /></td>
            <tr>
            <td colspan="5"><a href="vender.php">Continuar Comprando</a></td>
            
           
    </tfoot>
      
    <tbody>
               <?php
			  
			  
                     if(count($_SESSION['carrinho']) == 0){
                        echo '<tr><td colspan="5">Não há produto no carrinho</td></tr>';
                     }else{
                        require("conexao.php");
		
                          $total = 0;
						  
                        foreach($_SESSION['carrinho'] as $idproduto => $qtd){
                              $sql   = "SELECT *  FROM estoque WHERE idproduto= '$idproduto'";
                              $qr    = mysql_query($sql) or die(mysql_error());
                              $ln    = mysql_fetch_assoc($qr);
                              $idprodut = $ln['idproduto'];
                              $marca  = $ln['marca'];
                              $modelo  = $ln['modelo'];
                              $cor  = $ln['cor'];
                              $numero  = $ln['numero'];
                              $preco = number_format($ln['precovenda'], 2, ',', '.');
                              $sub   = number_format($ln['precovenda'] * $qtd, 2, ',', '.');
                               
                         
                             
                        //if (!empty($_POST)) {
        
        switch ($_POST['code']) {
			
			
                case 1: 
						$sql6 = mysql_query("SELECT precovenda FROM estoque WHERE idproduto= '$idproduto'");
						$resu6 = mysql_fetch_assoc($sql6);
						$value = $resu6['precovenda']; 
						$forma = 'A vista';
						$formacb = 'A Vista';
						$valuetotal = $value * 1;
                        break;
                case 2: 
                        $sql7 = mysql_query("SELECT precotres FROM estoque WHERE idproduto= '$idproduto'");
						$resu7 = mysql_fetch_assoc($sql7);
						$value = $resu7['precotres']; 
						$forma = '3x de ';
						$formacb = '3x';
						$valuetotal = $value * 3;
                        break;
				case 3: 
                        $sql8 = mysql_query("SELECT precoseis FROM estoque WHERE idproduto= '$idproduto'");
						$resu8 = mysql_fetch_assoc($sql8);
						$value = $resu8['precoseis']; 
						$forma = '6x de ';
						$formacb = '6x';
						$valuetotal = $value * 6;
                        break;
                //default:
                      //  $value = '';            
        }
        
//}
$total += $valuetotal * $qtd;
                           echo '<tr>
                     			<td>'.$idprodut.'</td>        
                                 <td>'.$marca.'</td>
                     			 <td>'.$modelo.'</td>
                  				 <td>'.$cor.'</td>
            					 <td>'.$numero.'</td>
                                 <td><input type="text" size="1" name="prod['.$idproduto.']" value="'.$qtd.'" /></td>
								 <td><form method="post" action="carrinho.php">
								 <select name="code" onchange="this.form.submit();">
										<option>'; if (!empty($_POST)){ echo $formacb; } else{ echo 'Selecione...'; } echo '</option>
										<option value="1">A Vista</option>
										<option value="2">3x</option>
										<option value="3">6x</option>
										</select>
                                 <td>'.$forma.' R$'. number_format($value, 2, ',', '.'). ' </td>';
								 echo '<td>R$ '. number_format($valuetotal, 2, ',', '.'). '</td>
                                 <td><a href="?acao=del&id='.$idproduto.'">Remove</a></td>
                              </tr>';
                        }
						
                         $total = number_format($total, 2, ',', '.');
                         $valuetota = number_format($valuetotal, 2, ',', '.');
						   
						   echo '<tr>
						   <td> </td>
                                    <td colspan="7">Total</td>
                                    <td>R$ '.$total.'</td>
									<td> </td>
                              </tr>';
                     }
               ?>
    
     </tbody>
        </form>
</table>
<?php 
	
if(isset($_POST['enviar'])){
	$formapagamento = $_POST['forma'];	
	$sqlinserevenda = mysql_query("INSERT into pedido(valortotal,data,formapagamento) VALUES ('$total',NOW(),'$formapagamento')");
	//$valortemp = mysql_query ("INSERT INTO valortemp(valortemp) VALUES ('$valuetotal')");
	$idvenda = mysql_insert_id();
	
	foreach($_SESSION['carrinho'] as $idproduto => $qtd){	
	$valortemp1 = mysql_query("SELECT * FROM valortemp");
	$valortempr = mysql_fetch_assoc($valortemp1);
	$valorvenda = $valortempr['valortemp'];
	$sql1   = "SELECT *  FROM estoque WHERE idproduto= '$idproduto'";
	$qr1    = mysql_query($sql1) or die(mysql_error());
	$ln1    = mysql_fetch_assoc($qr1);
	//$sub1 = $ln1['precovenda'];
	
	$sqlinsereitens = mysql_query("INSERT into itenspedido(idpedido,idproduto,quantidadeitens,valorunitario,data) VALUES('$idvenda','$idproduto','$qtd','$valuetota',NOW())");
	$sqlestoque = ("UPDATE estoque SET saldoestoque = saldoestoque - $qtd WHERE idproduto =  $idproduto ") or die(mysql_error());
	$sqlestoquesql    = mysql_query($sqlestoque) or die(mysql_error());
	
	$sqlestoque2 = ("UPDATE estoque SET totalsaida = totalsaida + $qtd WHERE idproduto =  $idproduto ") or die(mysql_error());
	$sqlestoquesql2    = mysql_query($sqlestoque2) or die(mysql_error());
	
	//$sqlestoque1 = ("UPDATE estoque SET totalvenda = totalvenda + $sub1 WHERE idproduto =  $idproduto ") or die(mysql_error());
	//$sqlestoque1sql    = mysql_query($sqlestoque1) or die(mysql_error());
	

}


	echo '<script> alert("Venda concluida!'.$valuetota.'")</script>';
	echo '<script> window.location = "vender.php"</script>';
	unset($_SESSION['carrinho']);
	
	}

?>
<form action="" method="POST" enctype="multipart/form-data"> 
	<select id ="forma" name="forma">
		<option>Selecione...</option>
		<option value="Dinheiro">Dinheiro</option>
		<option value="Cartão de Crédito">Cartão de Crédito</option>
		<option value="Cartão de Débito">Cartão de Débito</option>
		<option value="Cheque">Cheque</option>
		<option value="Vale">Vale</option>
	</select>
	<input type="submit" name="enviar" value="Finalizar Venda" />
</form>
 </div>

Last edited by tsalmeida on Thu Feb 19, 2015 2:36 pm, edited 2 times in total.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: help with shop cart

Post by Christopher »

tsalmeida wrote:My problem is time to save it in the db.

to display the correct values I used a switch in every way that is selected brings a different value.

when I save the db, always brings the reset value, does not bring the value of the variable that place.
I see two SQL INSERT commands and two UPDATE commands. Which is the one that is not writing the correct data? And which field/value is not correct?
(#10850)
tsalmeida
Forum Commoner
Posts: 38
Joined: Sat Jul 06, 2013 2:23 pm

Re: help with shop cart

Post by tsalmeida »

Christopher wrote:
tsalmeida wrote:My problem is time to save it in the db.

to display the correct values I used a switch in every way that is selected brings a different value.

when I save the db, always brings the reset value, does not bring the value of the variable that place.
I see two SQL INSERT commands and two UPDATE commands. Which is the one that is not writing the correct data? And which field/value is not correct?

only this variable $valuetota is writing incorrect. all others is writting the correct data, only this is getting the valeu of 0.

this is the insert

Code: Select all

 $sqlinsereitens = mysql_query("INSERT into itenspedido(idpedido,idproduto,quantidadeitens,valorunitario,data) VALUES('$idvenda','$idproduto','$qtd','$valuetota',NOW())")or die(mysql_error());
this variable came from switch code
tsalmeida
Forum Commoner
Posts: 38
Joined: Sat Jul 06, 2013 2:23 pm

Re: help with shop cart

Post by tsalmeida »

any help pls?????
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: help with shop cart

Post by Celauran »

Have you checked that $value is always being set? Checked that your queries are always returning results? Is error reporting turned on? Are you getting undefined notices? There's no error checking in there that I can see.
tsalmeida
Forum Commoner
Posts: 38
Joined: Sat Jul 06, 2013 2:23 pm

Re: help with shop cart

Post by tsalmeida »

Celauran wrote:Have you checked that $value is always being set? Checked that your queries are always returning results? Is error reporting turned on? Are you getting undefined notices? There's no error checking in there that I can see.

the correct variable is $valuetota.

only a query that is not returning the correct value, which is precisely why I'm asking for help in the forum.

is not showing any error, only the variable that entering with zero value.

what happens is the following:

I need to select if the customer wants to split the payment or do at once. when I select the form of payment in the combo box, the page loads correctly and shows the value of the product, this process is done in the SWITCH I did.

When I go to finalize the sale by clicking the "FINALIZAR VENDA" the variable $valuetota appears with zero value.

I even added the variable in the alert script and it shows zero, that is, only when I click the button to finalize the variable is lost.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: help with shop cart

Post by Christopher »

tsalmeida wrote:this is the insert

Code: Select all

 $sqlinsereitens = mysql_query("INSERT into itenspedido(idpedido,idproduto,quantidadeitens,valorunitario,data) VALUES('$idvenda','$idproduto','$qtd','$valuetota',NOW())")or die(mysql_error());
this variable came from switch code
And if you do this:

Code: Select all

 print_r($valuetota);
 $sqlinsereitens = mysql_query("INSERT into itenspedido(idpedido,idproduto,quantidadeitens,valorunitario,data) VALUES('$idvenda','$idproduto','$qtd','$valuetota',NOW())")or die(mysql_error());
What is displayed?
(#10850)
tsalmeida
Forum Commoner
Posts: 38
Joined: Sat Jul 06, 2013 2:23 pm

Re: help with shop cart

Post by tsalmeida »

Christopher wrote:
tsalmeida wrote:this is the insert

Code: Select all

 $sqlinsereitens = mysql_query("INSERT into itenspedido(idpedido,idproduto,quantidadeitens,valorunitario,data) VALUES('$idvenda','$idproduto','$qtd','$valuetota',NOW())")or die(mysql_error());
this variable came from switch code
And if you do this:

Code: Select all

 print_r($valuetota);
 $sqlinsereitens = mysql_query("INSERT into itenspedido(idpedido,idproduto,quantidadeitens,valorunitario,data) VALUES('$idvenda','$idproduto','$qtd','$valuetota',NOW())")or die(mysql_error());
What is displayed?
i printscreen the result

Image
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: help with shop cart

Post by Celauran »

$valuetota is just a formatted version of $valuetotal which, in turn, is coming from $value set in your switch statement. So, as I asked earlier, have you confirmed that $value is getting set? Have you confirmed that the queries in your switch statement actually work?
Post Reply