Page 1 of 1

need some advice/help

Posted: Wed Feb 23, 2011 4:29 pm
by mrzebra
Hello,

I'm hoping someone can help me with this. I'm trying to pass a javascript variable to php for my php shopping cart. What I have is a gift basket that has 4 products in it and the user selects a scent for each from a drop down menu. I have the selections appearing in a textarea box like this:

Foaming Bath Butter 8oz: Mango Papaya
Body Scrub 8oz: Pomegranate
Body Mist 150mL: Bamboo & Teak
Hand Cream 60mL: Unscented

I have the textarea contents saved in a variable "description." The user then clicks on "Confirm" to confirm the scents which creates the url:
giftBox50.php?&scent=Foaming Bath Butter 8oz: Mango Papaya Body Scrub 8oz: PomegranateBody Mist 150mL: Bamboo & TeakHand Cream 60mL: Unscented

I then use the $_GET['scent'] to retrieve the scents. When the user clicks "add to cart" the url displays:
cart.php?id=11&pid=11&scent=Foaming

I would like the cart to display the following under the scent column when the item is added to the cart:
Foaming Bath Butter 8oz: Mango Papaya, Body Scrub 8oz: Pomegranate, Body Mist 150mL: Bamboo & Teak, Hand Cream 60mL: Unscented

I'm not sure how to pass the data so it will do this. I'm also running into a problem when the scent has a & in the name...

Here is my code for my gift box page:

Code: Select all

<?php
session_start();
require_once("connect.php");
error_reporting(0);
ini_set('display_errors','1');
?>



<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

	<head>
		<script type="text/javascript" src="./js/functions.js"></script>
		<title>$50 Gift Box</title>

<script language=javascript>
// set each of the default scents to "unscented" for each product in this gift basket
var bathScent="Unscented";
var scrubScent="Unscented";
var mistScent="Unscented";
var creamScent="Unscented";

// initialize the variable 'description' that will display the scents selected, in the textarea box like this:
// ................................................. 
// .	Foaming Bath Butter 8oz: Unscented		   .
// .	Body Scrub 8oz: Unscented				   .
// .	Body Mist 150mL: Unscented				   .
// .	Hand Cream 60mL: Unscented				   .
// .................................................
//////////////////////////////////////////////////////////////
var description="Foaming Bath Butter 8oz: " + bathScent + "\n Body Scrub 8oz: " + scrubScent + "\nBody Mist 150mL: " + mistScent +"\nHand Cream 60mL: " + creamScent;

// function that is called to set the bathScent to whatever scent is selected from the drop down menu under Foaming Bath Butter
function set_bath_scent(x) {
	
	bathScent=x;
	
	// updates the textarea field with the scent selected
	updateScents(bathScent);
	
	
}

// function that sets the body scrub scent selected from the menu
function set_scrub_scent(x) {
	scrubScent=x;
	
	// update body scrub scent
	updateScents(x);
}


// sets body mist scent
function set_mist_scent(x) {
	
	mistScent=x;

	// update body mist scent
	updateScents(mistScent);
}


// set the hand cream scent
function set_cream_scent(x) {
	
	creamScent=x;

	// update hand cream scent	
	updateScents(creamScent);
}

function updateScents(x) {
	
	description="Foaming Bath Butter 8oz: " + bathScent + "\n Body Scrub 8oz: " + scrubScent + "\nBody Mist 150mL: " + mistScent +"\nHand Cream 60mL: " + creamScent;

	// display the updated scents selected from the drop down menus
	document.getElementById("gift_box_description").value = description;
	
	
}	


</script>
	
	 			
	</head>

<body background="#1d1d1d" onLoad='document.getElementById("gift_box_description").value = description';>



<div id="wrapper">
	<div id="main">
		<center><img src="./images/50giftBoxLogo.gif"></center>
		<table border="0" width="98%"  cellspacing=10 cellpadding=5>
			<?php 
				# connect to the data base and put the product scents into an array $n[]
				$sql = "SELECT * FROM productscents ORDER BY scentName ASC";
				$query = mysql_query($sql);
				
				$n=array();				
				$prodId;
				$i=0;
					
				// put the scent names and IDs into an array	
				while ( $row = mysql_fetch_assoc($query)) {	
					$n[$i]=$row['scentName'];
					$scent_id[$i]=$row['scentId'];					
					$i++;
					
				}

				$count=count($n);
				$count--;
				
				# gets product price
				$sql= "SELECT products.productPrice FROM products WHERE products.productName = '$50 Gift Box'";
				$result = mysql_query($sql);	
				$row = mysql_fetch_array($result);
				$price=$row['productPrice'];
				
				# gets product id from the products table
				$sql2= "SELECT products.productId FROM products WHERE products.productName = '$50 Gift Box'";
				$result2 = mysql_query($sql2);	
				$row2 = mysql_fetch_array($result2);
				$prodId=$row2['productId'];
				
				
				
				?>					
					<tr valign=center>
						 
						 <td><br><br><br>
							<table border=1 width=98% cellspacing=5>
								
								<tr valign=top>
					    	                 <th align=center valign=top >
										<font color="#999999">
										 8oz Foaming Bath Butter
										</font>	
									</th>
									
									<th align=center valign="top">
										<font color="#999999">
										8oz Body Scrub 
										</font>	
									</th>
								</tr>
								
								
								
								<tr valign=top>
									
									<td align=center valign=top >
									<select id="bathButter8oz" class="dropMenu" onChange="set_bath_scent(this.options[selectedIndex].value)"; >
										
											
											<?php 
												// add each scent into the dropdown menu for Foaming Bath Butter
												echo "<option>  --  Select Scent  --  </option>";
												for ($y=0; $y<=$count;) {
													
													echo "<option value='".$n[$y]."'>".$n[$y]."</option>";													
													$y++;
												}
													
												
																						
											?>
										</select><br><br><br>
										
									</td>
									
									<td align=center valign="top">
										<select id="bodyScrub8oz" class="dropMenu" onChange="set_scrub_scent(this.options[selectedIndex].value)"; >
					
											<?php 
												// add each scent into the dropdown menu for Body Scrub
												$menu="<option>  --Select Scent--  </option>";
												for ($y=0; $y<=$count;) {
													$menu.="<option value='".$n[$y]."'>".$n[$y]."</option>";
													$y++;
												}
												echo $menu;											
											?>
										</select><br><br><br>
											
									</td>				
									
									
									
								</tr>
								
					
								<tr valign=top>
									<th colspan align=center valign=top>
										<font color="#999999">
										150mL Body Mist
										</font>
									</th>
									
									<th align=center valign=top>
										<font color="#999999">
										60mL Hand Cream
										</font>
									</th>
									
									
								</tr> 
								
								
								
								
								<tr>	
								
									<td  align=center valign=top>
										<select id="bodyMist" class="dropMenu" onChange="set_mist_scent(this.options[selectedIndex].value";>
											
											<?php 
												// add each scent into the dropdown menu for Body Mist
												$menu="<option>  --Select Scent--  </option>";
												for ($y=0; $y<=$count;) {
													$menu.="<option value='".$n[$y]."'>".$n[$y]."</option>";
													$y++;
												}
												echo $menu;											
											?>
										</select><br><br><br>
										
									</td>
									
									<td align=center valign=top>
										<select id="handCream60" class="dropMenu" onChange="set_cream_scent(this.options[selectedIndex].value)";>
											
											<?php 
												// add each scent into the dropdown menu for Hand Cream by looping through the $n[] array
												$menu="<option>  --Select Scent--  </option>";
												for ($y=0; $y<=$count;) {
													$menu.="<option value='".$n[$y]."'>".$n[$y]."</option>";
													$y++;
												}
												echo $menu;		
																					
											?>
										</select><br><br><br>
										
									</td>
								</tr>
								
								
								
								<tr>
									<!-- ################### Display box where the scents chosen for each product will be displayed ################# -->
									<td colspan=2 align=center valign=center>
										
										<textarea overflow=hidden id="gift_box_description" name="gift_box_description" readOnly=true 
										style="width: 600px; text-align: center; height: 80px; overflow: hidden; border:1px; 
										background: #1d1d1d; font-face: arial; font-size: 16px; color: #999999;"></textarea>	
										
										
									</td>
								</tr>
								
								
									
								<tr>
									<td colspan=2 align=center valign=bottom><br>
										<!-- Post the javaScript Variable description so the value can be used by PHP -->
										<a href=# action=post onClick="window.location.href='giftBox50.php?&scent='+description";>Confirm Scents</a>
										<br><br><br>
									</td>
								</tr>	
								
								
								
								<!-- table row with the ADD TO CART & VIEW CART links -->
								<tr>
								
									<td align="center" valign=center >
										<div>
											<span>
											<form method=post action='cart.php' name='form2'>
												<input type="hidden" name="id" id="id" value="<?php echo $prodId;?>"/>
												<input type="hidden" name="pid" id="pid" value="<?php echo $prodId;?>"/>
												<input type="hidden" name="scent" id="scent" value="<?php print_r( $_GET['scent']);?>"/>
											
												<a href=cart.php?id=<?php echo $prodId?>&pid=<?php echo $prodId;?>&scent=<?php echo $_GET['scent']; ?> ;>Add to Cart</a>
												<br>
																		
									
											</form>
											</span>	
										</div>	
									</td>
									<td align=center valign=top>
										<a href="cart.php">View Cart</a>
									</td>	
						
								</tr>
																			
									
					
							</table></tr>
			
			
			
			</table>
			
		
		</div>
		
		
	<div id="sidebar">
			<?php require ("menu.html"); ?>
			
		
		
		</div>
	</div> <!-- End wrapper class -->



</body>
</html>

I'm new to php and any help or advice would be greatly appreciated. I've been trying to work this out for days. Lol.

Re: need some advice/help

Posted: Thu Feb 24, 2011 11:40 am
by danwguy
If I'm not mistaken when you use $_GET['scent'] it see's the space after foaming and stops reading. you might want to use values instead of names, or put some underscores or dashes in the names when you post them to the url.

Re: need some advice/help

Posted: Thu Feb 24, 2011 12:25 pm
by AbraCadaver
I can't pick through all of that, but if you're building the get var in js then use encodeURIComponent(). If building it in PHP use urlencode().

Re: need some advice/help

Posted: Thu Feb 24, 2011 7:15 pm
by mrzebra
Thanks for the input. Sorry it's hard to follow. I find it complicating myself. Lol. There is probably an easier way to do what I want.

My GET value is in php. The description variable is a javaScript variable and it stores: "Foaming Bath Butter 8oz: Scent selected here Body Scrub 8oz: Scent goes here, etc." This variable is used to display the selected scents in the text area. The person then clicks on "Confirm" and the page reloads and the value of "description" is passed into the url:

giftBox50.php?id=11&scent=Foaming Bath Butter 8oz: Scent selected here....

I then use the $_GET['scent'] to pass this info to my php shopping cart.

I'm thinking in my cart.php page I will have to add a description variable to the cart array, since the scent for other products is passed as an integer(scent_id) and then the scent is looked up in the database. So i'm thinking for the gift box, i will have to pass a description variable or possibly store the gift box scents into an array and pass the array. Then add an if statement:

If the product id is 11 then
under the scent column in the cart display, loop through the array. So the cart would be something like this:
__11_____$50 Gift Box______________Foaming Bath Butter 8oz: scent[0], Body Scrub 8oz: scent[1], Body Mist 150mL: scent[2], Hand Cream 60mL: scent[3].___1__$50.00__$50.00
_10027___Elite Hand Cream 120mL____Pomegranate___________________________________________________________________________________________2___$20.00__$40.00


The columns are the ID, Product Name, Scent, Quantity, Price and Total Price.

If the Product Id is not 11, then do the rest of the code.

Would this work....hopefully it makes sense. I'm also having a problem with my cart, I can't adjust the quanity or remove the very first item in the cart. I can remove and adjust the quantity on all the other items in the cart. Here is my cart code:

Code: Select all




<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors','1');
require_once("connect.php");
?>








<?php 
// code to add item to the cart
	if(isset($_POST['id'])) {
		$found=false;
		$i=0;
		$id=$_POST['id'];
		$product_id=$_POST['pid'];
		$product_scent=$_POST['scent'];
		
		
		$cartOutput="";		
		
		
		// if the cart session is empty
		if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"])<1) {
			$_SESSION["cart_array"] = array();
			array_push($_SESSION["cart_array"], array("id" =>$id, "product_id" => $product_id, "scent"=>$product_scent, "quantity" => 1 ));
			sort($_SESSION["cart_array"],$product_id);
			
		}else {
			foreach($_SESSION["cart_array"] as $each_item) {
				$i++;
				while(list($key, $value)=each($each_item)) {
				
					// if the item is already in the cart, up the quantity by 1
					if ($key == "id" && $value == $id) {	
						
						$_SESSION["cart_array"][$i-1]['quantity']++;
						
						// sort the array by item ID
						sort($_SESSION["cart_array"],$product_id);
						
						$found=true;
					} // close if
				} // close while
			} // close foreach
			if($found == false) {
				array_push($_SESSION["cart_array"], array("id" =>$id, "product_id" => $product_id, "scent"=>$product_scent, "quantity" => 1 ));
				sort($_SESSION["cart_array"],$product_id);
				
			}
		}
	header("location: cart.php");
	exit();

}
?>

<?php 
// code to empty the cart
if(isset($_GET['cmd']) && $_GET['cmd'] == "emptycart") {
	unset($_SESSION["cart_array"]);
}

?>




<?php 
/* code to adjust the item quantity in the cart. If the quantity is set to 0, the item will be removed from the cart */ 

	if(isset($_POST['item_to_adjust']) && $_POST['item_to_adjust'] != "") {
		 $adjust['id']= $_POST['item_to_adjust'];	   
		 $adjust['quantity']= $_POST['quantity'];        
		 		 
		 $i=0;
		
		
		foreach($_SESSION["cart_array"] as $each_item) {
				$i++;	
			
				
				while(list($key, $value)=each($each_item)) {
									
					//if ($key == "id" && $value == $adjust['id']) {
					if($value == $adjust['id']) {	
								 
						//  if the quantity is set to 0, remove the item from the cart
						if ($adjust['quantity'] == 0) {
							// remove the item from the cart
							unset($_SESSION["cart_array"][$i-1]);
							sort($_SESSION["cart_array"],$adjust['id']);

						} else {
							// change the quantity of the item if not 0 
							$_SESSION["cart_array"][$i-1]['quantity'] = $adjust['quantity'];
							sort($_SESSION["cart_array"],$adjust['id']);
							} // close else
						

						} // close if 
				
				} // close while



		} // close foreach

		sort($_SESSION["cart_array"],$adjust['id']);
		header("location: cart.php");
		exit();

}
?>

						


<?php 
/* code that outputs the cart contents and totals up the cart */

$cartOutput="";
$total="0";
$pp_checkout_btn="";

if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"])<1) {
	$cartOutput= "<tr><td colspan=6 align=center><i><font face=arial color=#999999>Your shopping cart is empty</font></i></td></tr>";
} else {
	
	// start Paypal Checkout Button
	$pp_checkout_btn .='<form target="_self" action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
	<input type="hidden" name="shopping_url" value="my link goes here">
	<input type="hidden" name="page_style" value="copperCreek">
	<input type="hidden" name="cs" value="0">
	<input type=hidden name="cmd" value="_cart">
	<input type=hidden name="upload" value="1">
	<input type=hidden name="business" value="my email goes here">';
	
	
	// start the foreach loop
	$i=0;
	foreach($_SESSION["cart_array"] as $each_item) {
		
		$item_id=$each_item['id'];
		$prod_id=$each_item['product_id'];
		$scent=$each_item['scent'];
		
		
		// Get product name and price
		$sql=mysql_query("SELECT products.productPrice, products.productName FROM products WHERE productId='$prod_id' LIMIT 1");
		while ($row=mysql_fetch_array($sql)) {
			$product_name=$row["productName"];
			$price=$row["productPrice"];
			
		}
		// get scent
		$sql2=mysql_query("SELECT productscents.scentName FROM productscents WHERE scentId='$scent' LIMIT 1");
		while ($row2=mysql_fetch_array($sql2)) {
			$scent=$row2['scentName'];
			
		}
		
		$subtotal=$price*$each_item['quantity'];
		$total=$subtotal + $total;
		
		if(isset ($_SESSION["cart_array"] )) {
		
			// dynamic checkout button assembly
			$x=$i+1;
			$pp_checkout_btn.='<input type=hidden name="item_name_'.$x.'" value="'.$product_name.'">
							   <input type=hidden name="item_scent_'.$x.'" value="'.$scent.'">	
							   
							   <input type=hidden name="amount_'.$x.'" value="'.$price.'">
							   <input type=hidden name="quantity_'.$x.'" value="'.$each_item['quantity'].'">';
			
			// dynamic cart item dispaly
			
		
			
			$cartOutput.="<tr align=center>
								<td width=5%><font color='#999999'>".$each_item['id']."</font></td>
								<td width=30%><font color='#999999'>".$product_name."</font></td>
								<td width=35%><font color='#999999'>".$scent."</font></td>
								<td valign=center width=5%><font color='#999999'><form action=cart.php method=post>
									<input class=box name=quantity type=text size=1 width=3 maxlength=3 onKeyPress='return check_qty(event);' value=".$each_item['quantity'].">
									<input type=hidden name='item_to_adjust' value='".$item_id."'/>
									<input type=hidden name='name' value='".$product_name."'/>
									<input type=hidden name='scent' value='".$scent."'/>
									
									<br><font color='#999999' size='-1'><a href=# onClick='submit()'>Update</a><br>
									
									</font></td>
								<td width=5%><font color='#999999'>$".$price.".00</font></td>
								<td width=10%><font color='#999999'>$".$subtotal.".00</font></td>
								
							</tr></form>";			
			$i++;
			
			
			
		} // end if 
	} // end foreach
	
	
	// Finish the Paypal Checkout Button
	$pp_checkout_btn .='
	
	<input type=hidden name="return" value="success.php">
	<input type=hidden name="rm" value="2">
	<input type=hidden name="cbt" value="Return to Store">
	<input type=hidden name="cancel_return" value="cancel.php">
	<input type=hidden name="currency_code" value="CAD">
	
	<a href=# onclick=submit();><img src="https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif" align="center" border=0;"></a></form>';
	
}


?>
<body background="#1d1d1d">	
	
					
						<table border=1 width=100% cellspacing=0 cellpadding=5 id="carttable" ><form>
						
							<tr>
								
								
								<td colspan=6 align=center>
								
								<img src="./images/copperCreekLogo.gif">
								
									</td>
								</tr>
							<tr align=center>
								<td width=5%><strong><font color="#cbb659">ID</font></strong></td>
								<td width=30%><b><font color="#cbb659">Product Name</font></b></td>
								<td width=35%><b><font color="#cbb659">Scent</font></b></td>
								<td width=5%><b><font color="#cbb659">Quantity</font></b></td>
								<td width=5%><b><font color="#cbb659">Price</font></b></td>
								<td width=10%><b><font color="#cbb659">Total Cost</font></b></td>
								
							</tr>
							
																		
													<tr>
													<?php echo $cartOutput;?>														
													</tr>	
													
							
							<tr>
								<td colspan=3 align=center><font size=-1 color=#999999>***Update quantity to 0, to remove the item from your cart***</font></td>
								<td colspan=2 align=right><font face=arial color="#999999">Total Price:</font></td>
								<td align=center><?php echo "$".$total.".00";?></td>
							</tr>	
													
						<tr>
							<td colspan=3>
								<center>
									<a href="cart.php?cmd=emptycart"><font face=arial color="#cbb659">Empty Cart</a>							
									
								</font></center>					
							</td>
							<td colspan=3 valign=center><br>
								<center><font face=arial color="#999999"><?php echo $pp_checkout_btn; ?></font></center>				
							</td>
						</tr>
						</form>
						</table>
			
		</body>	
		



Hopefully this makes sense. I know my coding is somewhat confusing. Lol. I also used a tutorial for this cart script. I altered it so it works with my products.

Re: need some advice/help

Posted: Fri Feb 25, 2011 2:39 pm
by danwguy
I think your best bet is to save the scent's as a number variable and then for each number store the actual description. Like I said when you are passing the variable with $_GET your variable has spaces in it, so $_GET see's Foaming as the only part of that variable, you need to either pass the variables with encodeURICompnent() or urlencode() then they will be readable by $_GET. Or make it easy and say ?scent=1 in your url and then interpret that to be Foaming whatever later.