Updating values of array - PHP
I have a shopping cart. I add items to them and this is the code of inserting an item to the cart.
My problem is that for some reason, when I have more than one element in my cart, If I add more quantity to one item, the quantity will be updated on the item with index + 1.
For example.
Empty cart now.
Add item A, 1 quantity.
Cart = item A , 1 quantity
Add item B, 1 quantity.
Cart = item A , 1 quantity, item B 1 quantity.
But now comes the problem.
If i add item A 1 quantity again. My cart will be
Cart = item A, 1 quantity, item B 2 quantity....
Can someone help me ?
<?php
session_start();
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["quantity"])) {
$productByCode = $db_handle->runQuery("SELECT * FROM products WHERE id='" . $_GET["id"] . "'");
$itemArray = array($productByCode[0]["id"]=>array('name'=>$productByCode[0]["name"], 'id'=>$productByCode[0]["id"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["price"], 'image'=>$productByCode[0]["image"]));
if(!empty($_SESSION["cart_item"])) {
if(in_array($productByCode[0]["id"],array_keys($_SESSION["cart_item"]))) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode[0]["id"] == $k) {
if(empty($_SESSION["cart_item"][$k]["quantity"])) {
$_SESSION["cart_item"][$k]["quantity"] = 0;
}
$_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"];
}
}
} else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
} else {
$_SESSION["cart_item"] = $itemArray;
}
}
?>
And this is the code I use to output HTML.
$template->setCurrentBlock("SHOPPINGCART");
foreach ($_SESSION["cart_item"] as $item){
$item_price = $item["quantity"]*$item["price"];
$template->setVariable("item_image", $item['image']);
$template->setVariable("item_name", $item['name']);
$template->setVariable("item_id", $item['id']);
$template->setVariable("item_quantity", $item['quantity']);
$template->setVariable("item_price", $item['price']);
$template->parseCurrentBlock();
}
php
add a comment |
I have a shopping cart. I add items to them and this is the code of inserting an item to the cart.
My problem is that for some reason, when I have more than one element in my cart, If I add more quantity to one item, the quantity will be updated on the item with index + 1.
For example.
Empty cart now.
Add item A, 1 quantity.
Cart = item A , 1 quantity
Add item B, 1 quantity.
Cart = item A , 1 quantity, item B 1 quantity.
But now comes the problem.
If i add item A 1 quantity again. My cart will be
Cart = item A, 1 quantity, item B 2 quantity....
Can someone help me ?
<?php
session_start();
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["quantity"])) {
$productByCode = $db_handle->runQuery("SELECT * FROM products WHERE id='" . $_GET["id"] . "'");
$itemArray = array($productByCode[0]["id"]=>array('name'=>$productByCode[0]["name"], 'id'=>$productByCode[0]["id"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["price"], 'image'=>$productByCode[0]["image"]));
if(!empty($_SESSION["cart_item"])) {
if(in_array($productByCode[0]["id"],array_keys($_SESSION["cart_item"]))) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode[0]["id"] == $k) {
if(empty($_SESSION["cart_item"][$k]["quantity"])) {
$_SESSION["cart_item"][$k]["quantity"] = 0;
}
$_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"];
}
}
} else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
} else {
$_SESSION["cart_item"] = $itemArray;
}
}
?>
And this is the code I use to output HTML.
$template->setCurrentBlock("SHOPPINGCART");
foreach ($_SESSION["cart_item"] as $item){
$item_price = $item["quantity"]*$item["price"];
$template->setVariable("item_image", $item['image']);
$template->setVariable("item_name", $item['name']);
$template->setVariable("item_id", $item['id']);
$template->setVariable("item_quantity", $item['quantity']);
$template->setVariable("item_price", $item['price']);
$template->parseCurrentBlock();
}
php
Is the problem in database cart or session cart only?
– Renzchler
Nov 22 '18 at 3:23
only session cart.
– James Fernandez
Nov 22 '18 at 3:26
Try this$_SESSION["cart_item"][$k - 1]["quantity"] += $_POST["quantity"];
orif($productByCode[$k]["id"] == $k)
Don't Know which part of code does what. I should leave comments in code
– SilvioCro
Nov 22 '18 at 3:31
@SilvioCro, I tried and didnt work. Thanks neverthless.
– James Fernandez
Nov 22 '18 at 3:45
The whole handling of the cart array data is rather bogus and convoluted. You don’t have to test whether$_SESSION["cart_item"]
is empty. All those in_array calls and looping over all the data to find a specific item, also unnecessary.$_SESSION["cart_item"][some-product-id]
is either set or not. If not, add an entry, using$_SESSION["cart_item"][some-product-id] = […]
, otherwise add to the existing quantity value,$_SESSION["cart_item"][some-product-id]["quantity"] += ...
– misorude
Nov 22 '18 at 8:09
add a comment |
I have a shopping cart. I add items to them and this is the code of inserting an item to the cart.
My problem is that for some reason, when I have more than one element in my cart, If I add more quantity to one item, the quantity will be updated on the item with index + 1.
For example.
Empty cart now.
Add item A, 1 quantity.
Cart = item A , 1 quantity
Add item B, 1 quantity.
Cart = item A , 1 quantity, item B 1 quantity.
But now comes the problem.
If i add item A 1 quantity again. My cart will be
Cart = item A, 1 quantity, item B 2 quantity....
Can someone help me ?
<?php
session_start();
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["quantity"])) {
$productByCode = $db_handle->runQuery("SELECT * FROM products WHERE id='" . $_GET["id"] . "'");
$itemArray = array($productByCode[0]["id"]=>array('name'=>$productByCode[0]["name"], 'id'=>$productByCode[0]["id"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["price"], 'image'=>$productByCode[0]["image"]));
if(!empty($_SESSION["cart_item"])) {
if(in_array($productByCode[0]["id"],array_keys($_SESSION["cart_item"]))) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode[0]["id"] == $k) {
if(empty($_SESSION["cart_item"][$k]["quantity"])) {
$_SESSION["cart_item"][$k]["quantity"] = 0;
}
$_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"];
}
}
} else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
} else {
$_SESSION["cart_item"] = $itemArray;
}
}
?>
And this is the code I use to output HTML.
$template->setCurrentBlock("SHOPPINGCART");
foreach ($_SESSION["cart_item"] as $item){
$item_price = $item["quantity"]*$item["price"];
$template->setVariable("item_image", $item['image']);
$template->setVariable("item_name", $item['name']);
$template->setVariable("item_id", $item['id']);
$template->setVariable("item_quantity", $item['quantity']);
$template->setVariable("item_price", $item['price']);
$template->parseCurrentBlock();
}
php
I have a shopping cart. I add items to them and this is the code of inserting an item to the cart.
My problem is that for some reason, when I have more than one element in my cart, If I add more quantity to one item, the quantity will be updated on the item with index + 1.
For example.
Empty cart now.
Add item A, 1 quantity.
Cart = item A , 1 quantity
Add item B, 1 quantity.
Cart = item A , 1 quantity, item B 1 quantity.
But now comes the problem.
If i add item A 1 quantity again. My cart will be
Cart = item A, 1 quantity, item B 2 quantity....
Can someone help me ?
<?php
session_start();
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["quantity"])) {
$productByCode = $db_handle->runQuery("SELECT * FROM products WHERE id='" . $_GET["id"] . "'");
$itemArray = array($productByCode[0]["id"]=>array('name'=>$productByCode[0]["name"], 'id'=>$productByCode[0]["id"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["price"], 'image'=>$productByCode[0]["image"]));
if(!empty($_SESSION["cart_item"])) {
if(in_array($productByCode[0]["id"],array_keys($_SESSION["cart_item"]))) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode[0]["id"] == $k) {
if(empty($_SESSION["cart_item"][$k]["quantity"])) {
$_SESSION["cart_item"][$k]["quantity"] = 0;
}
$_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"];
}
}
} else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
} else {
$_SESSION["cart_item"] = $itemArray;
}
}
?>
And this is the code I use to output HTML.
$template->setCurrentBlock("SHOPPINGCART");
foreach ($_SESSION["cart_item"] as $item){
$item_price = $item["quantity"]*$item["price"];
$template->setVariable("item_image", $item['image']);
$template->setVariable("item_name", $item['name']);
$template->setVariable("item_id", $item['id']);
$template->setVariable("item_quantity", $item['quantity']);
$template->setVariable("item_price", $item['price']);
$template->parseCurrentBlock();
}
php
php
edited Nov 22 '18 at 3:27
James Fernandez
asked Nov 22 '18 at 3:01
James FernandezJames Fernandez
257
257
Is the problem in database cart or session cart only?
– Renzchler
Nov 22 '18 at 3:23
only session cart.
– James Fernandez
Nov 22 '18 at 3:26
Try this$_SESSION["cart_item"][$k - 1]["quantity"] += $_POST["quantity"];
orif($productByCode[$k]["id"] == $k)
Don't Know which part of code does what. I should leave comments in code
– SilvioCro
Nov 22 '18 at 3:31
@SilvioCro, I tried and didnt work. Thanks neverthless.
– James Fernandez
Nov 22 '18 at 3:45
The whole handling of the cart array data is rather bogus and convoluted. You don’t have to test whether$_SESSION["cart_item"]
is empty. All those in_array calls and looping over all the data to find a specific item, also unnecessary.$_SESSION["cart_item"][some-product-id]
is either set or not. If not, add an entry, using$_SESSION["cart_item"][some-product-id] = […]
, otherwise add to the existing quantity value,$_SESSION["cart_item"][some-product-id]["quantity"] += ...
– misorude
Nov 22 '18 at 8:09
add a comment |
Is the problem in database cart or session cart only?
– Renzchler
Nov 22 '18 at 3:23
only session cart.
– James Fernandez
Nov 22 '18 at 3:26
Try this$_SESSION["cart_item"][$k - 1]["quantity"] += $_POST["quantity"];
orif($productByCode[$k]["id"] == $k)
Don't Know which part of code does what. I should leave comments in code
– SilvioCro
Nov 22 '18 at 3:31
@SilvioCro, I tried and didnt work. Thanks neverthless.
– James Fernandez
Nov 22 '18 at 3:45
The whole handling of the cart array data is rather bogus and convoluted. You don’t have to test whether$_SESSION["cart_item"]
is empty. All those in_array calls and looping over all the data to find a specific item, also unnecessary.$_SESSION["cart_item"][some-product-id]
is either set or not. If not, add an entry, using$_SESSION["cart_item"][some-product-id] = […]
, otherwise add to the existing quantity value,$_SESSION["cart_item"][some-product-id]["quantity"] += ...
– misorude
Nov 22 '18 at 8:09
Is the problem in database cart or session cart only?
– Renzchler
Nov 22 '18 at 3:23
Is the problem in database cart or session cart only?
– Renzchler
Nov 22 '18 at 3:23
only session cart.
– James Fernandez
Nov 22 '18 at 3:26
only session cart.
– James Fernandez
Nov 22 '18 at 3:26
Try this
$_SESSION["cart_item"][$k - 1]["quantity"] += $_POST["quantity"];
or if($productByCode[$k]["id"] == $k)
Don't Know which part of code does what. I should leave comments in code– SilvioCro
Nov 22 '18 at 3:31
Try this
$_SESSION["cart_item"][$k - 1]["quantity"] += $_POST["quantity"];
or if($productByCode[$k]["id"] == $k)
Don't Know which part of code does what. I should leave comments in code– SilvioCro
Nov 22 '18 at 3:31
@SilvioCro, I tried and didnt work. Thanks neverthless.
– James Fernandez
Nov 22 '18 at 3:45
@SilvioCro, I tried and didnt work. Thanks neverthless.
– James Fernandez
Nov 22 '18 at 3:45
The whole handling of the cart array data is rather bogus and convoluted. You don’t have to test whether
$_SESSION["cart_item"]
is empty. All those in_array calls and looping over all the data to find a specific item, also unnecessary. $_SESSION["cart_item"][some-product-id]
is either set or not. If not, add an entry, using $_SESSION["cart_item"][some-product-id] = […]
, otherwise add to the existing quantity value, $_SESSION["cart_item"][some-product-id]["quantity"] += ...
– misorude
Nov 22 '18 at 8:09
The whole handling of the cart array data is rather bogus and convoluted. You don’t have to test whether
$_SESSION["cart_item"]
is empty. All those in_array calls and looping over all the data to find a specific item, also unnecessary. $_SESSION["cart_item"][some-product-id]
is either set or not. If not, add an entry, using $_SESSION["cart_item"][some-product-id] = […]
, otherwise add to the existing quantity value, $_SESSION["cart_item"][some-product-id]["quantity"] += ...
– misorude
Nov 22 '18 at 8:09
add a comment |
1 Answer
1
active
oldest
votes
I don't quite understand your code but to be sure you are getting the product details and putting it to the cart session correct me if I'm wrong.
if(isset($_POST['quantity'])){
$qty = $_POST['quantity'];
$pid = $_POST['id'];
//retrieve product as object
$result = json_encode($db_handle->runQuery("SELECT * FROM products WHERE id='" . $_GET["id"] . "'"));
//decode the object
$item = json_decode($result);
//assign product id as key and the item collection as value
$_SESSION['cart_item'][$pid] = $item;
//then you have to assign the quantity
$_SESSION['cart_item'][$pid]->quantity = $qty;
//You can check now that quantity is updating accordingly and you have access to all props of your product
var_dump($_SESSION['cart_item']);
echo $_SESSION['cart_item'][$pid]->quantity;
}
I hope this helps!
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53423265%2fupdating-values-of-array-php%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
I don't quite understand your code but to be sure you are getting the product details and putting it to the cart session correct me if I'm wrong.
if(isset($_POST['quantity'])){
$qty = $_POST['quantity'];
$pid = $_POST['id'];
//retrieve product as object
$result = json_encode($db_handle->runQuery("SELECT * FROM products WHERE id='" . $_GET["id"] . "'"));
//decode the object
$item = json_decode($result);
//assign product id as key and the item collection as value
$_SESSION['cart_item'][$pid] = $item;
//then you have to assign the quantity
$_SESSION['cart_item'][$pid]->quantity = $qty;
//You can check now that quantity is updating accordingly and you have access to all props of your product
var_dump($_SESSION['cart_item']);
echo $_SESSION['cart_item'][$pid]->quantity;
}
I hope this helps!
add a comment |
I don't quite understand your code but to be sure you are getting the product details and putting it to the cart session correct me if I'm wrong.
if(isset($_POST['quantity'])){
$qty = $_POST['quantity'];
$pid = $_POST['id'];
//retrieve product as object
$result = json_encode($db_handle->runQuery("SELECT * FROM products WHERE id='" . $_GET["id"] . "'"));
//decode the object
$item = json_decode($result);
//assign product id as key and the item collection as value
$_SESSION['cart_item'][$pid] = $item;
//then you have to assign the quantity
$_SESSION['cart_item'][$pid]->quantity = $qty;
//You can check now that quantity is updating accordingly and you have access to all props of your product
var_dump($_SESSION['cart_item']);
echo $_SESSION['cart_item'][$pid]->quantity;
}
I hope this helps!
add a comment |
I don't quite understand your code but to be sure you are getting the product details and putting it to the cart session correct me if I'm wrong.
if(isset($_POST['quantity'])){
$qty = $_POST['quantity'];
$pid = $_POST['id'];
//retrieve product as object
$result = json_encode($db_handle->runQuery("SELECT * FROM products WHERE id='" . $_GET["id"] . "'"));
//decode the object
$item = json_decode($result);
//assign product id as key and the item collection as value
$_SESSION['cart_item'][$pid] = $item;
//then you have to assign the quantity
$_SESSION['cart_item'][$pid]->quantity = $qty;
//You can check now that quantity is updating accordingly and you have access to all props of your product
var_dump($_SESSION['cart_item']);
echo $_SESSION['cart_item'][$pid]->quantity;
}
I hope this helps!
I don't quite understand your code but to be sure you are getting the product details and putting it to the cart session correct me if I'm wrong.
if(isset($_POST['quantity'])){
$qty = $_POST['quantity'];
$pid = $_POST['id'];
//retrieve product as object
$result = json_encode($db_handle->runQuery("SELECT * FROM products WHERE id='" . $_GET["id"] . "'"));
//decode the object
$item = json_decode($result);
//assign product id as key and the item collection as value
$_SESSION['cart_item'][$pid] = $item;
//then you have to assign the quantity
$_SESSION['cart_item'][$pid]->quantity = $qty;
//You can check now that quantity is updating accordingly and you have access to all props of your product
var_dump($_SESSION['cart_item']);
echo $_SESSION['cart_item'][$pid]->quantity;
}
I hope this helps!
answered Nov 22 '18 at 4:53


RenzchlerRenzchler
7010
7010
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53423265%2fupdating-values-of-array-php%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Is the problem in database cart or session cart only?
– Renzchler
Nov 22 '18 at 3:23
only session cart.
– James Fernandez
Nov 22 '18 at 3:26
Try this
$_SESSION["cart_item"][$k - 1]["quantity"] += $_POST["quantity"];
orif($productByCode[$k]["id"] == $k)
Don't Know which part of code does what. I should leave comments in code– SilvioCro
Nov 22 '18 at 3:31
@SilvioCro, I tried and didnt work. Thanks neverthless.
– James Fernandez
Nov 22 '18 at 3:45
The whole handling of the cart array data is rather bogus and convoluted. You don’t have to test whether
$_SESSION["cart_item"]
is empty. All those in_array calls and looping over all the data to find a specific item, also unnecessary.$_SESSION["cart_item"][some-product-id]
is either set or not. If not, add an entry, using$_SESSION["cart_item"][some-product-id] = […]
, otherwise add to the existing quantity value,$_SESSION["cart_item"][some-product-id]["quantity"] += ...
– misorude
Nov 22 '18 at 8:09