Php Update Cart

Hiya guys, I have this script i have wrote, it seems to work although there’s a little problem.

[php]<?php
include ‘login/dbc.php’;
page_protect();

if (isset($_SESSION[‘user_id’])) {
$user = $_SESSION[‘user_id’];
$quantity = $_POST[“postquantity”];
$prod_id = $_POST[“postname”];

$rs_duplicate = mysql_query("select count(*) as total from cart where product_id='$prod_id' AND cart_user=".$_SESSION['user_id']."") or die(mysql_error());
$result = mysql_query("SELECT * FROM cart WHERE product_id='$prod_id' AND cart_user=".$_SESSION['user_id']."");

list($total) = mysql_fetch_row($rs_duplicate);
if ($total > 0)
{
while($row = mysql_fetch_array($result))
{
$tot_quantity = $quantity + $row[‘quantity’];
mysql_query(“UPDATE cart SET
quantity=’$tot_quantity’ WHERE cart_user=”.$_SESSION[‘user_id’]." AND product_id=’$prod_id’");
echo “#”. $tot_quantity;
}
} else {
mysql_query("INSERT into cart
(
cart_user,
product_id,
quantity
)
VALUES
(
‘$user’,
‘$prod_id’,
‘$quantity’
)
");
}

echo "Product ID: $prod_id";
echo "<br>quantity_calc:  ".$quantity_calc." <br>";
echo "Quantity: $quantity";
echo "<br><br>";

echo "
	i need to select the productid,
	we will then use this to insert into cart.
	also insert our userid into cart user
";

}else{ echo “no stop!”; }?>[/php]

This is just ment to check if the product allready exists and then update depending on the value thats sent to it…
Now it does work, theres just one problem though… It randomly when changing the values on the two products i have in the database, it decides to update both… Although most of the time it works… Why is it that it randomly does it??

Many thanks
Lewis Stevens

I suppose your WERE clause:
[php]
WHERE product_id=’$prod_id’ AND cart_user=".$_SESSION[‘user_id’]."");
[/php]
will always give you a unique single record? Or it should at least.

If that is the case, then change your while to an if like this:
[php]
if($row = mysql_fetch_array($result))
[/php]

Using it this way, you will always only update one record and be sure not to update the complete table.
The fact that both record updated at the same time must have happened when they had the same prod_id value. The while loop will update both.

Change thee prod_id value for each record, change the while to if and try it again.

Omg you are a lifesaver! I dont even know why that would work, although If does seem like it fits more… lol Why doesnt it work right with while? I thought it would be the same but only as the statement is being exectuted :confused:

Sponsor our Newsletter | Privacy Policy | Terms of Service