update product quantity in cart php session - php

I develop a new ecommerce site using PHP. I manage cart related data to database and store that data in session. The issue is when I add a product if the product is not in cart it adds that but if a product already exists it doesn't update quantity. This is my code for reference. I use key as product id
$getUserTemp['products']=array();
$mode=mysqli_real_escape_string($conn,$_POST['mode']);
$productId=mysqli_real_escape_string($conn,$_POST['product_id']);
$quantity=mysqli_real_escape_string($conn,$_POST['quantity']);
$productData=getSingleProduct("SELECT id,name,
quantity as quantity_in_stock,
original_price,discounted_price
from `products`
where id=".$productId."");
$productData['quantity']=$quantity;
switch ($mode) {
case 'add-to-cart':
if(empty($getUserTemp['products'])){
$getUserTemp['products'][$productId]=$productData;
}else{
foreach ($getUserTemp['products'] as $key => $value) {
if($key == $productId){
$value['quantity']+=$quantity;
$value[$productId]=$value;
}else{
$getUserTemp['products'][$productId]=$productData;
}
}
}
mysqli_query($conn,"UPDATE `session_cart` set session_data='".json_encode($getUserTemp)."' where user_id='".$currentLoggedUserId."'");
print_r($getUserTemp);
break;
}
My array data:
Array
(
[user] => Array
(
[id] => 8
[profile_id] => 6
[user_name] => bala#mail.com
[role] => user
[password] => $2y$10$bL4LybXcOX6nkEgRAM6Jjerrz2czEZJLWv7W1MNg.vWscb39NEsx2
)
[products] => Array
(
[38] => Array
(
[id] => 38
[name] => HP
[quantity_in_stock] => 33
[original_price] => 50.00
[discounted_price] => 40.00
[quantity] => 1
)
[8] => Array
(
[id] => 8
[name] => ASUS VivoBook 15 (2021) Core i3 10th Gen - (8 GB/512 GB SSD/Windows 11 Home) X515JA-EJ362WS Thin and Light Laptop (15.6 inch, Transparent Silver, 1.80 kg, With MS Office)
[quantity_in_stock] => 20
[original_price] => 50.00
[discounted_price] => 40.00
[quantity] => 1
)
)
)

Related

how to get the first galley image value in multidimensional array

Here i having one multidimensional using this array productId wise i am making one more array,from this array i having Galery array, from this i have to take first prodcutImage value, i don't how can achive this, if any one update my asnwer
I having array like this
print_r($productByCode)
Array
(
[0] => Array
(
[productId] => 5
[adminproductId] => 1Delivery00123
[categoryName] => Computer Accessories
[brandName] => Dell
[title] => Dell Inspiron 5000 Series 5547 5555 5557 5558 Internal Laptop Keyboard (Black)
[subTitle] => Dell Keyboard
[price] => 200
[discountType] => Percentage
[discountValue] => 20
[afterDiscount] => 160
[shipppingAmount] => 150
[taxPercentage] => 25
[Galery] => Array
(
[0] => Array
(
[gId] => 13
[productId] => 5
[prodcutImage] => 1.jpeg
)
[1] => Array
(
[gId] => 14
[productId] => 5
[prodcutImage] => 2.jpeg
)
[2] => Array
(
[gId] => 15
[productId] => 5
[prodcutImage] => 3.jpeg
)
)
)
)
I have tried like this
$itemArray = array
(
$productByCode[0]["productId"]=>array
(
'categoryName'=>$productByCode[0]["categoryName"],
'productId'=>$productByCode[0]["productId"],
'brandName'=>$productByCode[0]["brandName"],
'subTitle'=>$productByCode[0]["subTitle"],
'quantity'=>$Qty_total,
'price'=>$productByCode[0]["afterDiscount"],
'taxPercentage'=>$productByCode[0]["taxPercentage"].'%',
'shipppingAmount'=>$productByCode[0]["shipppingAmount"],
'qtyprice'=>round($productByCode[0]["afterDiscount"])
)
);
Current Output
Array
(
[5] => Array
(
[categoryName] => Computer Accessories
[productId] => 5
[brandName] => Dell
[subTitle] => Dell Keyboard
[quantity] => 1
[price] => 160
[taxPercentage] => 25%
[shipppingAmount] => 150
[qtyprice] => 160
)
)
Expected Output
Array
(
[5] => Array
(
[categoryName] => Computer Accessories
[productId] => 5
[brandName] => Dell
[subTitle] => Dell Keyboard
[quantity] => 1
[price] => 160
[taxPercentage] => 25%
[shipppingAmount] => 150
[qtyprice] => 160
[prodcutImage] => 1.jpeg
)
)
If I understood you requirement, You've already tried like this way to assign values to different array element, So just grab the Galery value like this using nested array element accessing way & add this element at the last of your array.
'prodcutImage' => $productByCode[0]['Galery'][0]['prodcutImage']
So it will like this,
$itemArray = array
(
$productByCode[0]["productId"]=>array
(
'categoryName'=>$productByCode[0]["categoryName"],
'productId'=>$productByCode[0]["productId"],
'brandName'=>$productByCode[0]["brandName"],
'subTitle'=>$productByCode[0]["subTitle"],
'quantity'=>$Qty_total,
'price'=>$productByCode[0]["afterDiscount"],
'taxPercentage'=>$productByCode[0]["taxPercentage"].'%',
'shipppingAmount'=>$productByCode[0]["shipppingAmount"],
'qtyprice'=>round($productByCode[0]["afterDiscount"]),
'prodcutImage' => $productByCode[0]['Galery'][0]['prodcutImage']
)
);

MySQL Data from multiple tables in a muli-level array

Would be great if anyone can help? I currently have the data below being output by the code at the bottom but ranther than it repeating for each order_product_id I want to build an multi level array from the data.
Current output:
[0] => Array
(
[order_product_id] => 43
[order_id] => 1
[product_id] => 161
[name] => Hoodie
[model] => Hoodie
[quantity] => 1
[price] => 23.9500
[total] => 23.9500
[tax] => 0.0000
[reward] => 0
[option_id] => 141
[option_name] => Hoodie Style
[option_value] => Pull over
)
[1] => Array
(
[order_product_id] => 43
[order_id] => 1
[product_id] => 161
[name] => Hoodie
[model] => Hoodie
[quantity] => 1
[price] => 23.9500
[total] => 23.9500
[tax] => 0.0000
[reward] => 0
[option_id] => 142
[option_name] => Hoodie Colour
[option_value] => Light Pink
)
[2] => Array
(
[order_product_id] => 43
[order_id] => 1
[product_id] => 161
[name] => Hoodie
[model] => Hoodie
[quantity] => 1
[price] => 23.9500
[total] => 23.9500
[tax] => 0.0000
[reward] => 0
[option_id] => 143
[option_name] => Adult Sizes
[option_value] => Ladies Meduim 10-12
)
Desired array where each product has all its options in multi level rather than how the current set up shows it:
[0] => Array
(
[order_product_id] => 43
[order_id] => 1
[product_id] => 161
[name] => Hoodie
[model] => Hoodie
[quantity] => 1
[price] => 23.9500
[total] => 23.9500
[tax] => 0.0000
[reward] => 0
Array
(
[0] => Array
(
[option_id] => 141
[option_name] => Hoodie Style
[option_value] => Pull over
)
[1] => Array
(
[option_id] => 142
[option_name] => Hoodie Colour
[option_value] => Light Pink
)
[2] => Array
(
[option_id] => 141
[option_name] => Adult Sizes
[option_value] => Ladies Meduim 10-12
)
)
)
The current output is being built by this:
$sql = "SELECT site_order_product.*,
site_order_option.order_option_id AS option_id, site_order_option.name AS option_name, site_order_option.value AS option_value
FROM site_order_product
INNER JOIN site_order_option ON site_order_product.order_product_id = site_order_option.order_product_id; ";
$result=mysqli_query($dbh2,$sql);
if($result) {
$row = mysqli_fetch_all($result,MYSQLI_ASSOC);
return $row;
} else {
return false;
}
Thanks for any help!
NOTE : The feature that your looking is lazy loading. ORM suits best
for your problem. To name some of ORM's RedBean, Doctrine, Propel.
This is an example just for the sake of demonstration.
Without any proper database table schema its difficult to give you the exact answer output what you were looking for. But will help you with some example which will do the same.
Think that your having the products table and orders table.
Products
id | product_name | product_price | product_notes
Orders
id | product_id | order_number
Problem your facing : Now if you query for products then you will get the list of products details. But the problem you were facing was to gets its respective orders too.
Solution : When you loop into each product, get the respective product id and query all the orders for that product and assign into one main array.
/* Get the list of products */
$productsQuery = mysqli_query($link, "SELECT * FROM products");
/* Array to hold the details or products and its respective order per product */
$productDetails = array();
if(mysqli_num_rows($productsQuery) > 0){
$productCount = 0;
while($product = mysqli_fetch_assoc($productsQuery)){
$productId = $product['id'];
/* Assign the product details to productDetails array */
$productDetails[$productCount] = $product;
/* Get the details of orders which respective productid */
$ordersQuery = mysqli_query($link, "SELECT * FROM orders WHERE product_id = ".$productId);
if(mysqli_num_rows($ordersQuery) > 0){
while($order = mysqli_fetch_assoc($ordersQuery)){
/* Here we have assigned the product orders to respective product */
$productDetails[$productCount]['orders'] = $order;
}
}else{
/* If no order assign an empty array */
$productDetails[$productCount]['orders'] = [];
}
}
}

PHP Session Array Update

I wish to update a single product quantity from a session with a new value using php.
How can I do this.
Array data is as displayed
Array
(
[products] => Array
(
[0] => Array
(
[name] => Ford AA Flatbed
[code] => IWV001
[qty] => 1
[price] => 15.00
[weight] => 0.12
)
[1] => Array
(
[name] => Ford AA Stakebed
[code] => IWV003
[qty] => 1
[price] => 15.00
[weight] => 0.21
)
)
)
any help would be most appreciated.
I want to be able to search through the session and find the product by code and update the quantity within that product.
Something like this:
foreach($products as &product) {
if ($product[code] == $codeToUpdate) {
$product[qty] = $newQty;
}
}
Of course, this is a sequential search so it will be slow for large data sets.

Magento Event Observer to group product collection by category

I'm creating an events observer module which will group upsell products by category,
below is my module's model/observer.php file,
public function updateUpsells($observer)
{
$iCurrentCategory = Mage::registry('current_category')->getId();
$event = $observer->getEvent();
$oUpsellCollection = $event->getCollection();
foreach ($oUpsellCollection->getItems() as $key => $oUpsellProduct) {
$aCategoriesIds = $oUpsellProduct->getCategoryIds();
if (!in_array($iCurrentCategory, $aCategoriesIds)) {
$oUpsellCollection->removeItemByKey($key);
}
}
}
}
After enabling this module i can include upsell product's category id's in upsell.phtml file by echo $this->getItemCollection()->getItems()
as a result i got,
Array
(
[170] => Mage_Catalog_Model_Product Object
(
.........................
[_data:protected] => Array
(
[entity_id] => 170
[entity_type_id] => 10
[attribute_set_id] => 44
[type_id] => simple
[category_ids] => Array
(
[0] => 12
[1] => 26
)
.......................
)
[171] => Mage_Catalog_Model_Product Object
(
.........................
[_data:protected] => Array
(
[entity_id] => 171
[entity_type_id] => 10
[attribute_set_id] => 44
[type_id] => simple
[category_ids] => Array
(
[0] => 16
[1] => 24
)
.......................
)
)
So now how can i group this array results by category. Example mentioned 2 upsell products assigned to 4 different categories, as a result i need to group products like,
Category id 12
product1 | Product2
Category id 26
product1 | Product2

check if cart item has the same property

Am using the codeigniter cart library, but now the client wants users to only be able to checkout items from one category at at a time because of some issues with their payment gateway.
Current the site has a single checkout logic for all categories.
When a users adds an items to the cart, i have an array like this
Array
(
[d8df18561040f3d9bd9868f5c5aaa7c2] => Array
(
[rowid] => d8df18561040f3d9bd9868f5c5aaa7c2
[id] => MYU_SC1
[qty] => 1
[price] => 500
[name] => WAEC Scratch Card
[service_image] => assets/img/waec.jpg
[service_category] => scratch_cards
[subtotal] => 500
)
[99483fe03da62c9e98ce71232998f447] => Array
(
[rowid] => 99483fe03da62c9e98ce71232998f447
[options] => Array
(
[size] => 36
[colour] => N/A
)
[id] => 80433426a546064bf5f8d09a6e7fdabc
[qty] => 1
[price] => 5000
[name] => Green Vee Jeans
[service_image] => http://localhost/myunivacity/uploads/apparels/IMG_0425.JPG
[service_category] => apparels
[subtotal] => 5000
)
)
how i do check if whether or not the items in the cart have same value for "service_category" element?. Thanks for the help
You could go with something like this:
<?php
$categories = array();
foreach($this->cart->contents() as $cart_item) {
if(!isSet($categories[$cart_item["service_category"]]) {
$categories[$cart_item["service_category"]] = 1;
}
else {
$categories[$cart_item["service_category"]]++;
}
}
print_r($categories);
?>
This fills an array with a count per category

Categories