Jump to content

Need some help


mrzebra81

Recommended Posts

Hi,

 

I need some help fixing up this code. I can add items to my cart but when I want to updated the quantity in the cart it will change the quantity on all the items except the first item added to the cart. The same thing happens when I want to remove an item from the cart. I'm trying to code it, so when the person updates the quantity to 0 in the cart, the item will be removed completely from the cart. It is not doing that for some reason, it just puts the quantity to 0 and leaves it in the cart.

 

I'm not sure what I'm doing wrong. I've tried using a text link "Remove" in the cart and it will remove all items except the first item added to the cart. Again, I'm trying to change it so when the customer updates the quantity to 0, the item is removed from the cart. However it is putting the quantity to 0 and not removing it from the cart.

 

Here is my code:

 


<?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(0 => array("id" =>$id, "product_id" => $product_id, "scent"=>$product_scent, "quantity" => 1 ));
	}else {
		foreach($_SESSION["cart_array"] as $each_item) {
			$i++;
			while(list($key, $value)=each($each_item)) {
				if ($key == "id" && $value == $id) {	
					array_splice($_SESSION["cart_array"], $i-1, 1, array(array("id" =>$id, "product_id" => $product_id, "scent"=>$product_scent, "quantity" => $each_item['quantity']+1)));
					$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 ));
		}
	}
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'] != "") {
	$item_to_adjust=$_POST['item_to_adjust'];
	$quantity=$_POST['quantity'];
	$product_id=$_POST['name'];
	$product_scent=$_POST['scent'];
	$i=0;

	if($_POST['item_to_adjust']['quantity'] == 0) {
		$key_to_remove=$_POST['item_to_adjust'];
		unset($_SESSION["cart_array"]['$key_to_remove']);

	} 

	if(count($_SESSION["cart_array"])<=1) {
	unset($_SESSION["cart_array"]);

	}else {

	foreach($_SESSION["cart_array"] as $each_item) {
		$i++;
			while(list($key, $value)=each($each_item)) {
				if ($key == "id" && $value == $item_to_adjust) {	
					array_splice($_SESSION["cart_array"], $i-1, 1, array(array("id" =>$item_to_adjust, "product_id" => $product_id, "scent"=>$product_scent, "quantity" => $quantity)));

				}  // close if 

			}// close while
	} // close foreach

	}
}
?>


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

$cartOutput="";
$total="";

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 {
$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"] )) {



		$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 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."'/>
								<input type=hidden value'".$i."'/>
								<font color='#999999' size='-1'><a href=# onClick='submit()'>Update</a><br>
								</form>
								</font></td>
							<td width=5%><font color='#999999'>$".$price.".00</font></td>
							<td width=10%><font color='#999999'>$".$subtotal.".00</font></td>

						</tr>";			
		$i++;

	} 
}
}


?>

 

Any help would be greatly appreciated. Thansk

Link to comment
Share on other sites

To be honest your code is a little confusing and the comments don't explain what the code is doing.

 

For example, you have a loop to iterrate through all the cart objects in the session. If there is a match on the ID you are using a counter ($i) to remove that item and replace it with what was POSTed. That's way more compicated than it should be. First of all you should use

foreach($_SESSION["cart_array"] as $idx => $each_item)

Then use $idx (or whatever you want to call it) instead of using an artificial counter. Second, there is no need to use array slice. Simply redefine the array index using the POSTEd values.

 

But, even all that is superfulous. I see no reason to make your cart data so complicated. You should just be saving the cart as a simple array ($_SESSION["cart_array"]) with the product ID as the key and the quantity as the value. The product ID should be to a unique product that contains the scent and "id" (not sure what the difference would be between ID and product ID.

 

At the very least - if you do need the multidimensional array - use the unique ID (whichever one that is) as the index for each cart item. That way you don't have to loop through all the current cart records to find a match.

 

BUt, I think I can see why your code to remove an item is not working

		if($_POST['item_to_adjust']['quantity'] == 0) {
		$key_to_remove=$_POST['item_to_adjust'];
		unset($_SESSION["cart_array"]['$key_to_remove']);

	}

Do you even have a POST value of $_POST['item_to_adjust']['quantity']??? Based upon the variables you define above it seems you have two distinct POST values for 'item_to_adjust' and 'quantity'. So, that statemetn is never returning true. Even if it did the code within wouldn't work based upon my understanding of your structure.

 

You really need to think about your structure and start over. But, I think this may work with your current code

    /* 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'] != "")
    {
        //Dump POST vars into new array
        $adjust['id']         = $_POST['item_to_adjust'];
        $adjust['product_id'] = $_POST['name'];
        $adjust['quantity']   = $_POST['quantity'];
        $adjust['scent']      = $_POST['scent'];

        //Loop through each cart product
        foreach($_SESSION["cart_array"] as $idx => $item)
        {
            //Check if this cart product matches the adjustment product
            if ($item['product_id'] == $adjust['product_id'])
            {
                //Check if adjustment qty is 0
                if($adjust['quantity']==0)
                {
                    //Remove the cart product
                    unset($_SESSION["cart_array"][$idx])
                }
                else
                {
                    //Change the cart product
                    $_SESSION["cart_array"][$idx] = $adjust;
                }
                //Exit the foreach loop
                break;
            }
        }
    }

Link to comment
Share on other sites

The other thing that makes this complicating is that I have 2 mysql tables...one with the product and the other has the scents. I have 10 different products that are available in each scent. For example...elite hand creams have an I'd of 1 and the scent pomegranate has an id of 36, so I combine the two to give the product the id of 136. This will be the unique id. I have the product pages dynamically made using the tables. I will try clean up the code. Hopefully this makes sense.

 

Link to comment
Share on other sites

For example...elite hand creams have an I'd of 1 and the scent pomegranate has an id of 36, so I combine the two to give the product the id of 136. This will be the unique id.

 

You had better rethink that approach . . . and quickly. What happens when you have a product with the ID 13 and a scent with the ID 6 - that would also have the unique(?) ID of 136.

 

The proper way to do this would be with three tables. Table one would list the product types (hand cream, lotion, etc.) and each would have a unique ID in that table. The second table would be the scents and again they would each have a unique ID (but they can repeat the IDs in the product table).

 

The third table would be for the products. In that table you would have three values: the unique ID of the product, the product ID and the scent ID.

 

Example:

product_types
=============
type_id type_name
1      Hand Cream
2      Lotion
3      Deoderant

scents
=============
scent_id scent_name
1       pomegranate
2       Lemon
3       Musk

products
=============
prod_id type_id scent_id
1       1       1
2       1       2
3       1       3
4       2       1
5       2       2
6       2       3
7       3       1
8       4       2
9       4       3

 

In the above example, the product with the ID "6" would be for the type 2 (Lotion) with the scent 3 (Musk)

Link to comment
Share on other sites

I do have leading 0s on the scent ids...not sure if that would help. So product 13 and scent 6 would have a unique id# of 1306. Would increasing the number of leading 0s to 3 or 4 make it better. We will never reach 100 products or 1000 scents. Would this be a good alternative?

Link to comment
Share on other sites

I do have leading 0s on the scent ids...not sure if that would help. So product 13 and scent 6 would have a unique id# of 1306. Would increasing the number of leading 0s to 3 or 4 make it better. We will never reach 100 products or 1000 scents. Would this be a good alternative?

 

It would be an alternative. But, I would not consider it a good alternative. You are using a database - at least use it in a manner that will give you the most benefit. By "making up" ids by combining two different IDs you don't have any logical entities in the database for each unique product. If you ever need to store data for each unique product (e.g. inventory) how will you store it? If you used your concatenation method, if you need that data it would be a multi-step process to query the product types and scents. Then in the PHP code you would combine those values to get all the product IDs, then you'd have to run another query to get the data.

Link to comment
Share on other sites

Ok. That makes sense. I will try restructure it so the code will be simpler. Now when I create the third table do I manually enter the data or is there a way I can join the two tables to create the third.

 

Assuming the new tables has the fields I described previously you can create all the records (associating every product type with every scent) with a single query.

 

INSERT INTO products_table (type_id, scent_id)
  SELECT t.type_id, s.scent_id
  FROM prod_types_table AS t
  JOIN scents_table AS s

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.