Home > Net >  Problem with shopping cart adds same product multiple time
Problem with shopping cart adds same product multiple time

Time:08-08

I have php mysql shopping cart which works well, but problem is that if I add product which has code numbers only without any letter, product is added multiple time. For example product code: K001 is working ok, but if product code is 001 without K I have same problem.

$cartArray = array(
$code=>array(
'name'=>$name,
'code'=>$code,
'price'=>$price,
'quantity'=>1,
'image'=>$image)
);

if(empty($_SESSION["shopping_cart"])) {
$_SESSION["shopping_cart"] = $cartArray;
$status = "<div class='box'>Product is added to your cart!</div>";
}else{
$array_keys = array_keys($_SESSION["shopping_cart"]);
if(in_array($array_keys, $code)) {
$status = "<div class='box' style='color:red;'>
Product is already added to your cart!</div>";  
} else {
$_SESSION["shopping_cart"] = array_merge(
$_SESSION["shopping_cart"],
$cartArray
);
$status = "<div class='box'>Product is added to your cart!</div>";
}

}
}
?>

CodePudding user response:

I think your problem is that PHP mostly converts numers automaticaly to floats or ints (depending on the numbers). Try converting the $code to string before sending.

You can do this multiple ways:

$code = "$code"; But you can lose the leading zeros then

$code = strval($code); If the code it's integer then you also will losse the leading zeros

As you can see you can use multiple ways, but try not using leading zeros in PHP or add them later as in this solution: How to keep leading zeros in PHP integer

CodePudding user response:

I added please take a look, but have same problem

$row = mysqli_fetch_assoc($result);
$name = $row['name'];
$code = strval($row['code']);
$price = $row['price'];
$image = $row['file_name'];

$cartArray = array(
$code=>array(
'name'=>$name,
'code'=>$code,
'price'=>$price,
'quantity'=>1,
'image'=>$image)
);
  • Related