Fairly new to php and following e commerce tutorials. When exploring a way to resolve a problem I had with a php code block, I came upon a post another person had with the same code block. https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/ The post suggested a way to simplify the code.
Original code block:
<?php
if (isset($_POST ['pid'])) {
$pid = $_POST ['pid'];
$wasFound = false;
$i = 0;
if (!isset ($_SESSION["cart_array"]) || count($_SESSION ["cart_array"])<1){
$_SESSION["cart_array"] = array (0=> array("item_id"=> $pid, "quantity" => 1));
} else {
foreach ($_SESSION["cart_array"] as $each_item) {
$i++;
while(list($key,$value)=each($each_item)){
if ($key== "item_id" && $value == $pid) {
array_splice ($_SESSION["cart_array"], $i-1,1, array(array("item_id"=>$pid,"quantity"=> $each_item['quantity']+1)));
$wasFound = true;
}
}
}
if($wasFound==false) {
array_push ($_SESSION["cart_array"], array("item_id"=> $pid, "quantity" => 1));
}
}
header("Location: cart.php");
exit();
}
?>
This was the suggested simplified code block and an explanation of what to do after changing code. I am unsure how to implement the the part suggested after the code block.
if (isset($_POST['pid'])) {
// add (+1) item to cart
$pid = (int)$_POST['pid']; // cast as integer
// valid pids are > 0
if($pid > 0){
if(!isset($_SESSION['cart_array'][$pid])){
// item is not in the cart, add it with quantity = 1
$_SESSION['cart_array'][$pid] = array("item_id" => $pid, "quantity" => 1); // I left the array in the cart the same, but it could also be simplified so that it is only the quantity, since the item_id is now the cart array index
} else {
// item is in the cart, increment quantity
$_SESSION['cart_array'][$pid]['quantity']++;
}
}
header("location: cart.php");
exit();
}
To get the details for the cart items, you need to run ONE query that gets all of them at the same time (putting a query inside of a loop is a resource killer.) For the definition of the cart that I have suggested, you can use array_keys to get all the item id's. You would then implode those into a comma separated list and put them into an IN() comparison in the WHERE clause in a query to get all the matching rows at once. Edited by PFMaBiSmAd, 27 December 2012 - 02:05 PM.
This is what I am considering adding to the code block:
if ($result = print_r(array_keys('cart_array',$pid))) {
$comma_seperated = implode("," $result);
// then use use $comma_seperated in query where needed later in annother code block?
}
Am I on the right path?