Jump to content

Add Variations To Cart


son

Recommended Posts

I have a simple shopping cart page running so far (adding main items and updating the basket). The code is:

if (isset($_REQUEST['do']) && ($_REQUEST['do'] == 'add')){	if (isset($_GET['qty2']))	{	$qty2 = (int) $_GET['qty2'];	}	else	{	$qty2 = 1;	}	if (isset($_GET['fn']))	{	$fn = (int) $_GET['fn'];	}	elseif (isset($_POST['fn']))	{	$fn = (int) $_POST['fn'];	}	else	{	$fn = 0;	}	if (isset($_GET['var']))	{	$var = (int) $_GET['var'];	}	elseif (isset($_POST['var']))	{	$var = (int) $_POST['var'];	}	else	{	$var = 0;	}	if (isset($_GET['age']))	{	$age = (int) $_GET['age'];	}	elseif (isset($_POST['age']))	{	$age = (int) $_POST['age'];	}	else	{	$age = 0;	}	if (isset($_GET['id']))	{	$id = (int) $_GET['id'];		if ($id > 0)		{		$id_query = "SELECT product, price FROM products WHERE product_id = $id";		$id_result = mysqli_query ($dbc, $id_query);			if (mysqli_num_rows($id_result) == 1)			{				if ($fn != 0)				{				$_SESSION['cart'][$id]['fn'] = $fn;				}				if ($var != 0)				{				$_SESSION['cart'][$id]['var'] = $var;				}				if ($age != 0)				{				$_SESSION['cart'][$id]['age'] = $age;				}							list ($product, $price) = mysqli_fetch_array($id_result, MYSQLI_NUM);				if (isset($_SESSION['cart'][$id]))				{				$_SESSION['cart'][$id]['qty'] += $qty2;				echo "<p>Another copy of the following item has been added to your cart: <strong>$product</strong>.</p>\n";				}				else				{				$_SESSION['cart'][$id]['qty'] = $qty2;				echo "<p>The following item has been added to your cart: <strong>$product</strong>.</p>\n";				}			}		}	}}elseif (isset($_REQUEST['do']) && ($_REQUEST['do'] == 'update')){	foreach ($_POST['qty'] as $k => $v)	{	$pid = (int) $k;	$qty = (int) $v;		if ($qty == 0)		{		unset ($_SESSION['cart'][$pid]);		}		elseif ($qty > 0)		{		$_SESSION['cart'][$pid]['qty'] = $qty;		}	}	foreach ($_POST['fn'] as $u => $i)	{	$pid = (int) $u;	$fn = (int) $i;	$_SESSION['cart'][$pid]['fn'] = $fn;	}	foreach ($_POST['age'] as $r => $o)	{	$pid = (int) $r;	$age = (int) $o;	$_SESSION['cart'][$pid]['age'] = $age;	}	echo "<p>The cart has been updated.</p>\n";}if ($_SESSION['cart'] && !empty($_SESSION['cart'])){$cart_query = "SELECT product_id, product, code, detail, price, discount_id, img1 FROM products WHERE product_id IN (";	foreach($_SESSION['cart'] as $id => $v)	{	$cart_query .= (int) $id . ',';	}$cart_query = substr ($cart_query, 0, -1) . ") ORDER BY product";$cart_result = mysqli_query ($dbc, $cart_query);	if (mysqli_num_rows($cart_result) > 0)	{	echo "<form action=\"cart.php\" method=\"post\" name=\"cart\" id=\"cart\">\n";	echo "<table style=\"margin-top:15px;\">\n";	echo "<tr><th>Item</th><th>Description</th><th>Qty</th><th class=\"right\">Price</th></tr>\n";	$total = 0;		while ($row = mysqli_fetch_array($cart_result, MYSQLI_ASSOC))		{		$product_name = $row['product'];		$product_code = $row['code'];		$product_detail = $row['detail'];		$price = $row['price'];		$price_unaltered = $row['price'];		if ($row['discount_id'] != '')		{		$discount = $row['discount_id'];		$discount = (int) $discount;		}		else		{		$discount = 0;		}		$img = $row['img1'];		$size = getimagesize("products/basket/{$img}");		$subtotal = $_SESSION['cart'][$row['product_id']]['qty']* $price;		$total += $subtotal;					// depending on total apply reductions on total	if ($total >= 3000)	{		if ($discount == 2)		{		$price = $price * 0.9;		}		if ($discount == 1)		{		$price = $price * 1;		}		else		{		$price = $price;		}	}	$subtotal2 = $_SESSION['cart'][$row['product_id']]['qty']* $price;	$total2 += $subtotal2;	$grand_total = $total2;	$saving = $total - $total2;	$percent = (100/$total) * $total2;	$percent = 100 - $percent;	$price = number_format($price, 2);			echo "<tr>";		echo "<td><img src=\"" . $basketPath . $img . "\" " . $size[3] . " alt=\"" . $product_name . "\" /></td>";		echo "<td>" . $product_name . "<br />Product Code: " . $product_code . "<br />Size in cm: " . $product_detail . "<br  />";		$fn_name = $_SESSION['cart'][$row['product_id']]['fn'];		$age_name = $_SESSION['cart'][$row['product_id']]['age'];		echo "</td>";		echo "<td><input type=\"text\" style=\"width: 2em\" name=\"qty[{$row['product_id']}]\" value=\"{$_SESSION['cart'][$row['product_id']]['qty']}\" /> <a href='#'><img src='assets/delete.gif' width='15' height='15' alt='Click to remove item' onclick=\"document.forms['cart'].elements['qty[{$row['product_id']}]'].value='0'; document.forms['cart'].submit()\"></a>";		echo "<p style=\"margin-left:0;\">";		if ($price_unaltered == 0)		{		echo "<span class=\"small\">POA</span>";		}		else		{		echo "<span class=\"small\">Per item: £" . $price_unaltered . "</span>";		}		echo "</p>";		echo "</td>";		if ($subtotal2 == 0)		{		echo "<td class=\"right\">POA</td>";		}		else		{		echo "<td class=\"right\">£" . number_format($subtotal, 2) . "</td>";		}		echo "</tr>\n";		}		echo "<tr><td colspan=\"3\" class=\"right noBorder\">Sub Total:</td><td class=\"right\">£ " . number_format($total, 2) . "</td></tr>\n";		echo "<tr><td colspan=\"3\" class=\"right noBorder\">Discount (" . number_format($percent, 2) . "%):</td><td class=\"right\">£ " . number_format($saving, 2) . "</td></tr>\n";		echo "<tr><td colspan=\"3\" class=\"right noBorder\"><strong>Grand Total (incl. VAT and delivery):</strong></td><td class=\"right\"><strong>£ " . number_format($grand_total, 2) . "</strong></td></tr>\n";		echo "<tr><td colspan=\"4\" class=\"noBorder\"> </td></tr>\n";		echo "<tr><td colspan=\"4\" class=\"right noBorder\" style=\"padding-right:0;\">";		echo "<input type=\"hidden\" name=\"do\" value=\"update\" />\n";		echo "<input type=\"submit\" value=\"Update Total\" id=\"submitted\" name=\"submitted\" />";		echo "</td></tr>\n";		echo "<tr><td colspan=\"4\" class=\"noBorder\"> </td></tr>\n";		echo "<tr><td colspan=\"4\" class=\"noBorder\">";		if (isset($_SESSION['back']) && $_SESSION['back'] != '')		{		$backlink = $_SESSION['back'];		}		else		{		$backlink = 'index.php';		}		echo "<a href=\"" . $backlink . "\" title=\"Continue Shopping\">Continue Shopping</a> </td></tr>\n";		echo "</table>\n";		echo "</form>\n";	}}else{echo "<p>Currently there are no items added to this page.</p>\n";}

On product page I had to add now a drop-down called 'var' which always has the main product showing which is stored in products table (in drop down with value of 0 as it is not a product variation as such). Now, some products have variations, which means that they share common characteristics, but differ for example in price. The fields which are different are stored in variations table and the association with main product is done via parent column that references product_id of main product (from products table). They will also show after main product in drop down. I have added now the relevant fields to gather varitation id in cart session, but am lost as in how to display the correct data when a variation is added. The relevant query is:

$cart_query = "SELECT product_id, product, code, detail, price, discount_id, img1 FROM products WHERE product_id IN (";	foreach($_SESSION['cart'] as $id => $v)	{	$cart_query .= (int) $id . ',';	}$cart_query = substr ($cart_query, 0, -1) . ") ORDER BY product";$cart_result = mysqli_query ($dbc, $cart_query);

How can I display the data from variation table if relevant product is added with value different to 0 from variation drop down and otherwise display data from products table? Also, how can I easily email the data stored in session to a dedicated email address?Any help, hints, kicks appreciated...Son

Link to comment
Share on other sites

So is the value in the dropdown the ID of the record in the variation table? Wouldn't you just use that ID to look up the record, and since that table has the parent ID you could also look up the parent record? Is that what you're asking?

Link to comment
Share on other sites

So is the value in the dropdown the ID of the record in the variation table? Wouldn't you just use that ID to look up the record, and since that table has the parent ID you could also look up the parent record? Is that what you're asking?
This is exactly what I am asking. The value in dropdown is id of record in variation table, but since the parent itself is not in variation table (I run a separate query on products table to produce first option of dropdown which is main product and hard-code a value of 0) I am not sure as how to run the query accordinly...Also, any idea how to send all data stored in session to designated email address?Son
Link to comment
Share on other sites

Right, so you get the ID from the dropdown and check if it's 0. If it is, I assume you're using that hidden ID in the form as the ID of the product, so if the dropdown value is 0 then you would just look up that ID. If the dropdown value wasn't 0 then you would do a join between the products and variations table to get both the variation and parent product data.The session is just an array, you can loop through the session like any other array and build a message string to email out.

Link to comment
Share on other sites

Right, so you get the ID from the dropdown and check if it's 0. If it is, I assume you're using that hidden ID in the form as the ID of the product, so if the dropdown value is 0 then you would just look up that ID. If the dropdown value wasn't 0 then you would do a join between the products and variations table to get both the variation and parent product data.The session is just an array, you can loop through the session like any other array and build a message string to email out.
I have a hidden id in form, which is always the product_id from products table. Therefore a variation will be added with the variation_id from my variations table (if main product is chosen it will be passed as 0) which is chosen from dropdown. Does this make any change to what you said? Will have a go otherwise...Son
Link to comment
Share on other sites

  • 4 weeks later...
All you need to do is check if the variation ID is 0, if it is then you don't do a join to get the product details, if it's not 0 then you join the two tables to get everything.
Will try that. Sorry for late reply, I catched a most horrible flu and are just back to work now (still not feeling great:-()...Son
Link to comment
Share on other sites

I have done this, but it does repeat the same product over and over again. The relevant code is:

if ($_SESSION['cart'] && !empty($_SESSION['cart'])){	if ($var == 0)	{	$cart_query = "SELECT p.product_id, p.product, p.code, p.detail, p.price, p.discount_id, p.img1 FROM products as p WHERE p.product_id IN (";	}	else	{	$cart_query = "SELECT p.product_id, pv.product, pv.code, pv.detail, pv.price, p.discount_id, p.img1 FROM products as p, productsVar as pv WHERE p.product_id IN (";	}		foreach($_SESSION['cart'] as $id => $v)		{		$cart_query .= (int) $id . ',';		}	$cart_query = substr ($cart_query, 0, -1) . ") ORDER BY p.product";	$cart_result = mysqli_query ($dbc, $cart_query);

Why does this happen?Son

Link to comment
Share on other sites

If you're doing a join it's going to return one record for each combination of joined records. So if the product has 1 entry in the products table, and 3 entries in the productsVar table, then the join will return 3 records. You'll need to loop through them yourself to add each option to the parent product record, or when you loop through the products you need to keep track of the last product you saw so that you can tell if the current record is a new product or another option for the previous product.

Link to comment
Share on other sites

If you're doing a join it's going to return one record for each combination of joined records. So if the product has 1 entry in the products table, and 3 entries in the productsVar table, then the join will return 3 records. You'll need to loop through them yourself to add each option to the parent product record, or when you loop through the products you need to keep track of the last product you saw so that you can tell if the current record is a new product or another option for the previous product.
It actually displays other non-related records 10 to 15 times (which is not the correct number of existing variations) for each product I add (which is really odd). However, when I have my 'normal query' as
$cart_query = "SELECT p.product_id, p.product, p.code, p.detail, p.price, p.discount_id, p.img1 FROM products as p WHERE p.product_id IN (";		foreach($_SESSION['cart'] as $id => $v)		{		$cart_query .= (int) $id . ',';		}	$cart_query = substr ($cart_query, 0, -1) . ") ORDER BY p.product";	$cart_result = mysqli_query ($dbc, $cart_query);

how can I loop through the variations to check if that variation has been added to cart page and how do I add each option to the parent product record? I have never produced a cart before and was glad I came up with a simple solution. The recent requested changes go a bit beyond my horizon and I would be more than grateful for more help and hints (unfortunately it also does not help I developed a nasty chest infection which makes my concentration very poor:-().SonReason for edit: Added 'which is not the correct number of existing variations' which is important piece of info

Link to comment
Share on other sites

You'll just need to keep an array of everything. So you would get the database results and loop through them and add each product to a products array. For each row, you would check to see if the product is already in the products array and if it is then you add the variation to the existing product, or else you add a new product. Once the products array is finished then you loop through the products array to write everything onto the page. Each product in the array could have another array of variations where you add each option for the product.

Link to comment
Share on other sites

You'll just need to keep an array of everything. So you would get the database results and loop through them and add each product to a products array. For each row, you would check to see if the product is already in the products array and if it is then you add the variation to the existing product, or else you add a new product. Once the products array is finished then you loop through the products array to write everything onto the page. Each product in the array could have another array of variations where you add each option for the product.
Do you have an example? This would be great! This is far away from anything I have done before...Son
Link to comment
Share on other sites

$products = array();while ($row = mysql_fetch_assoc($result)){  $prod_idx = false;  for ($i = 0; $i < count($products); $i++)  {	if ($products[$i]['product_id'] == $row['product_id'])	{	  $prod_idx = $i;	  break;	}  }  if ($prod_idx === false)  {	// add new product	$prod = array(	  'product_id' => $row['product_id'], 	  'product' => $row['product'],	  'variations' => array()	);	$prod_idx = count($products);	$products[$prod_idx] = $prod;  }  // add variation to product  $var = array(	'code' => $row['code'],	'detail' => $row['detail']  );  $products[$prod_idx]['variations'][] = $var;}print_r($products);

Link to comment
Share on other sites

Any my query with the if-clause is ok as it is?

if ($var == 0){$cart_query = "SELECT p.product_id, p.product, p.code, p.detail, p.price, p.discount_id, p.img1 FROM products as p WHERE p.product_id IN (";}else{$cart_query = "SELECT p.product_id, pv.product, pv.code, pv.detail, pv.price, p.discount_id, p.img1 FROM products as p, productsVar as pv WHERE  p.product_id IN (";}		foreach($_SESSION['cart'] as $id => $v)		{		$cart_query .= (int) $id . ',';		}	$cart_query = substr ($cart_query, 0, -1) . ") ORDER BY p.product";	$cart_result = mysqli_query ($dbc, $cart_query);

I think I got your example in theory, am just confused now about my query...Son

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...