I have some function which I use in my cart application:
session_start();
if(!isset($_SESSION['products'], $_SESSION['price'], $_SESSION['product_names'],$_SESSION['product_id'])) {
$_SESSION['products'] = 0;
$_SESSION['price'] = 0;
$_SESSION['product_names'] = array();
$_SESSION['product_id'] = array();
}
if(isset($_POST['add'])) {
$_SESSION['product_names'][] = $_POST['product_name'];
$_SESSION['products']++;
$_SESSION['price'] += $_POST['price'];
}
if(isset($_POST['empty'])) {
session_destroy();
header('Location:index.php');
}
The question is, how can I add this into a class and call it in my view page?
I mean it will still work as <?php echo $_SESSION['price']?>. How can I make this work?
Try this class you're doing in a wrong way.
session_start();
class Shopping {
public function __construct()
{
}
//get cart products
public function getCartProducts()
{
$cart = array();
if(isset($_SESSION['cart'])) {
$cart = unserialize($_SESSION['cart']);
}
return $cart;
}
//add product to cart
public function addToCart($product_details)
{
$cart = $this->getCartProducts();
$product_id = $product_details['product_id'];
$is_quantity = $this->addQuantity($product_id); //check if product already exists in session if then increase the quantity
if(!$is_quantity) {
$product_details = array(
'qty' => $product_details['qty'],
'price' => $product_details['price'],
'product_name' => $product_details['name'],
'product_id' => $product_id
);
array_push($cart, $product_details);
$_SESSION['cart'] = serialize($cart);
}
}
//add quantity if product already exists
private function addQuantity($product_id)
{
$cart = $this->getCartProducts();
$i = 0;
foreach ($cart as $product) {
if($product['product_id'] == $product_id)
{
$product['qty'] += 1;
$cart[$i] = $product;
$_SESSION['cart'] = serialize($cart);
return true;
}
$i++;
}
return false;
}
public function clearCart()
{
unset($_SESSION['cart']);
}
public function removeProduct($product_id)
{
$cart = $this->getCartProducts();
$new_cart = array();
foreach ($cart as $product) {
if($product['product_id'] != $product_id)
array_push($new_cart, $product);
}
$_SESSION['cart'] = serialize($new_cart);
}
}
$shop = new Shopping();
$shop->addToCart(array('product_id'=>1,'name'=>'test 1','price'=>'120.00','qty'=>1));
$shop->addToCart(array('product_id'=>3,'name'=>'test 2','price'=>'120.00','qty'=>1));
This is an example of my approach using session in class. References work pretty well.
class Cart {
private $container ;
public function __construct(&$container){
if (!isset($container) || !is_array($container))
$session['cart'] = array() ;
$this->container = &$container ;
}
public function productExists($id){
return (isset($this->container[$id])) ;
}
}
$cart = new Cart($_SESSION['cart']) ;
At this point all changes in container can be performed in $_SESSION['cart'] . The rest of session array is not affected, that should be safe.
Related
This code is not completely splitting my order. Still subtotal and grand total of bill is not split up. This code is splitting order's product fine. Is there any other code that is working well with this. I want to split order on the bases of supplier. The products from one supplier should be in one order and the other one's should be in other. Please suggest me some useful links.
Below is my code. This is an observer of order save.
<?php
class Custom_SplitOrderObserver_Model_Checkout_Type_Onepage extends Mage_Checkout_Model_Type_Onepage {
/**
* Create order based on checkout type. Create customer if necessary.
*
* #return Mage_Checkout_Model_Type_Onepage
*/
public function saveOrder() {
$this->validate();
$isNewCustomer = false;
switch ($this->getCheckoutMethod()) {
case self::METHOD_GUEST:
$this->_prepareGuestQuote();
break;
case self::METHOD_REGISTER:
$this->_prepareNewCustomerQuote();
$isNewCustomer = true;
break;
default:
$this->_prepareCustomerQuote();
break;
}
$cart = $this->getQuote();
$key = 0;
foreach ($cart->getAllItems() as $item) {
$key = $key + 1;
$temparray[$key]['product_id'] = $item->getProduct()->getId();
$temparray[$key]['qty'] = $item->getQty();
$cart->removeItem($item->getId());
$cart->setSubtotal(0);
$cart->setBaseSubtotal(0);
$cart->setSubtotalWithDiscount(0);
$cart->setBaseSubtotalWithDiscount(0);
$cart->setGrandTotal(0);
$cart->setBaseGrandTotal(0);
$cart->setTotalsCollectedFlag(false);
$cart->collectTotals();
}
$cart->save();
foreach ($temparray as $key => $item) {
$customer_id = Mage::getSingleton('customer/session')->getId();
$store_id = Mage::app()->getStore()->getId();
$customerObj = Mage::getModel('customer/customer')->load($customer_id);
$quoteObj = $cart;
$storeObj = $quoteObj->getStore()->load($store_id);
$quoteObj->setStore($storeObj);
$productModel = Mage::getModel('catalog/product');
$productObj = $productModel->load($item['product_id']);
$quoteItem = Mage::getModel('sales/quote_item')->setProduct($productObj);
$quoteItem->setBasePrice($productObj->getFinalPrice());
$quoteItem->setPriceInclTax($productObj->getFinalPrice());
$quoteItem->setData('original_price', $productObj->getPrice());
$quoteItem->setData('price', $productObj->getPrice());
$quoteItem->setRowTotal($productObj->getFinalPrice());
$quoteItem->setQuote($quoteObj);
$quoteItem->setQty($item['qty']);
$quoteItem->setStoreId($store_id);
$quoteObj->addItem($quoteItem);
$quoteObj->setBaseSubtotal($productObj->getFinalPrice());
$quoteObj->setSubtotal($productObj->getFinalPrice());
$quoteObj->setBaseGrandTotal($productObj->getFinalPrice());
$quoteObj->setGrandTotal($productObj->getFinalPrice());
$quoteObj->setStoreId($store_id);
$quoteObj->collectTotals();
$quoteObj->save();
$this->_quote = $quoteObj;
$service = Mage::getModel('sales/service_quote', $quoteObj);
$service->submitAll();
if ($isNewCustomer) {
try {
$this->_involveNewCustomer();
} catch (Exception $e) {
Mage::logException($e);
}
}
$this->_checkoutSession->setLastQuoteId($quoteObj->getId())
->setLastSuccessQuoteId($quoteObj->getId())
->clearHelperData();
$order = $service->getOrder();
if ($order) {
Mage::dispatchEvent('checkout_type_onepage_save_order_after', array('order' => $order, 'quote' => $quoteObj));
$quoteObj->removeAllItems();
$quoteObj->setTotalsCollectedFlag(false);
$quoteObj->collectTotals();
}
/**
* a flag to set that there will be redirect to third party after confirmation
* eg: paypal standard ipn
*/
$redirectUrl = $this->getQuote()->getPayment()->getOrderPlaceRedirectUrl();
/**
* we only want to send to customer about new order when there is no redirect to third party
*/
if (!$redirectUrl && $order->getCanSendNewEmailFlag()) {
try {
$order->sendNewOrderEmail();
} catch (Exception $e) {
Mage::logException($e);
}
}
// add order information to the session
$this->_checkoutSession->setLastOrderId($order->getId())
->setRedirectUrl($redirectUrl)
->setLastRealOrderId($order->getIncrementId());
// as well a billing agreement can be created
$agreement = $order->getPayment()->getBillingAgreement();
if ($agreement) {
$this->_checkoutSession->setLastBillingAgreementId($agreement->getId());
}
}
// add recurring profiles information to the session
$profiles = $service->getRecurringPaymentProfiles();
if ($profiles) {
$ids = array();
foreach ($profiles as $profile) {
$ids[] = $profile->getId();
}
$this->_checkoutSession->setLastRecurringProfileIds($ids);
// TODO: send recurring profile emails
}
Mage::dispatchEvent(
'checkout_submit_all_after', array('order' => $order, 'quote' => $this->getQuote(), 'recurring_profiles' => $profiles)
);
return $this;
}
}
Actually after fetching the data from the Database, i want to create a new Object and insert this object to the array but when i check the array it shows the NULL value
here is my code:
<?php
$query = "sql query";
$filter_Result = mysqli_query($con, $query);
$newOrders = Array();
while ($row = mysqli_fetch_array($filter_Result)) {
$order;
$orderId = $row['order_id']; //fetch row id
$temp = check_id($newOrders, $orderId);
if ($temp != null) {
$order = $temp;
} else {
echo " <br>";
$order = new Order($row['order_id'], $row['status'], $row['created_Date']);
$newOrders[] = $order;
}
$item = new Item($row['status'], $row['quantity']);
$order->AddItem($item, null);
}
function check_id($newOrders, $orderId) {
$length = count($newOrders);
for ($i = 0; $i < $length; $i++) {
if ($newOrders[$i]->$orderId == $orderId)
return $newOrders[$i];
}
return null;
}
foreach ($newOrders as $order) {
}
?>
You have a variable in your Order class
var $order_Id;
But then you try to assign value to $orderId which does not exist
$this->orderId = $orderId;
I would suggest turning all PHP errors on while developing. You can include this in your php code to see if you get any errors. It is very hard to see all the small errors with naked eye :) Let PHP do it for you.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
More about error reporting here.
You have several small mistakes, e.g. using "this" incorrectly, using different name for "orderId", plus a wrong name for the constructors. The constructor name should be "Order" or "__construct", same for "Item" constructor.
class Order {
/* Member variables */
var $orderId;
var $status;
var $createdDate;
var $items = array();
function Order($orderId, $status, $createdDate)
{
$this->orderId = $orderId;
$this->status = $status;
$this->createdDate = $createdDate;
}
function AddItem($itemId,$quantity)
{
$item = new Item($itemId,$quantity);
$items[] = $item;
}
}
$c = new Order(1, 'OK', 'today');
print_r($c);
Now i found the Solution in the PHP we have to use __construct() for the creating a Constructor....
So use it __construct instead of class name for more info visit:
__construct() vs SameAsClassName() for constructor in PHP
new_order.php
<?php
class Order {
/* Member variables */
var $order_Id;
var $status;
var $createdDate;
var $items = array();
function __Order($order_Id, $status, $createdDate)
{
$this->order_Id = $order_Id;
$this->status = $status;
$this->createdDate = $createdDate;
}
function AddItem($itemId,$quantity)
{
$item = new Item($itemId,$quantity);
$items[] = $item;
}
}
class Item {
var $productId;
var $productName;
var $quantity;
var $personalization;
function __Item($productId, $quantity)
{
$this->productId = $productId;
$this->productName = $productName;
$this->quantity = $quantity;
$this->personalization = $personalization;
}
}
?>
I am creating an API where I'm inserting product_id, Product_Size, quantity, product_name in an array called product-info.
Now I want to update the other values when product id is already existing.
my code for insertion in controller:
if(!empty($product_info1)){
foreach ($product_info1 as $value) {
$product_id = isset($value->product_id) ? $value->product_id : 0;
$Product_Size = isset($value->Product_Size) ? $value->Product_Size : 0;
$quantity = isset($value->quantity) ? $value->quantity : 0;
$product_name = isset($value->product_name) ? $value->product_name : 0;
if( $ok = 1)
$this->api_details_model->productinventory_track($product_id,$Product_Size,$quantity,$product_name);
{
$api_status="true";
$api_message="Done";
}
// $this->api_details_model->checkProductid($product_id);
}
}
model:
function productinventory_track($product_id,$Product_Size='',$quantity='',$product_name='')
{
if($product_id>=0)
{
$data = array('product_name'=>$product_name,'size_id'=>$Product_Size,'stock_count'=>$quantity,'product_id'=>$product_id);
if($this->db->insert('product_inventory', $data)){ return true; }else{ return false; }
}
please tell me the code for update
Controller:
$productInfo = $this->db->api_details_model->get($product_id);
$productArray['product_name'] = 'yourValue';
$productArray['size_id'] = 'yourValue';
$productArray['stock_count'] = 'yourValue';
// Means that there is no product with that ID in the database
if($productInfo == null)
$this->db->api_details_model->add($productArray);
// It was found an ID in the database
else
$this->db->api_details_model->edit($product_id, $productArray);
Functions in model:
public function add($data)
{
$this->db->insert('product_inventory', $data);
}
public function edit($id, $data)
{
$this->db->where('id', $id)
->update('product_inventory', $data);
}
public function get($id)
{
$this->db->where('id', $id);
return $this->db->get('product_inventory')->row();
}
I have the following opencart function to add product in session
Consider this as my $bean_sku and $product_id
$bean_id = 'werwer-23423s-sd-01';
$product_id = 120;
public function add($product_id, $bean_sku, $qty = 1, $option = array()) {
if (!$option) {
$key = (int)$product_id;
} else {
$key = (int)$product_id . ':' . base64_encode(serialize($option));
}
if ((int)$qty && ((int)$qty > 0)) {
if (!isset($this->session->data['cart'][[$bean_sku][$key]])) { echo 'not set';
$this->session->data['cart'][[$bean_sku][$key]] = (int)$qty;
} else { echo 'session set';
$this->session->data['cart'][[$bean_sku][$key]] += (int)$qty;
}
}
echo $this->session->cart;
exit;
$this->data = array();
}
In the above function I have added $bean_sku But I am unable to set the session. Each time when I run getting not set.
Try as
$this->session->data['cart'][$bean_sku.$key] = (int)$qty;
Try
$this->session->data['cart'][$bean_sku][$key]
instead of
$this->session->data['cart'][[$bean_sku][$key]]
I noticed laravel re-preform the insertion action when the timeout occurs
How can I shop it from retiring to insert the data again when timeout error fires ?
loop
foreach ($comments_data as $comment_data)
{
if ( ! empty($comment_data['date']))
{
$total_rating[] = $this->check_rating_value($comment_data['rating']);
$comment_id = ( new Comment() )->saveComments($shop, $comment_data, $product_id, $urls, $shop_options);
( new Comments_images() )->save_images($comment_id, $shop, $comment_data['images']);
}
}
inserting code
public function saveComments($shop, $comments_data, $product_id, $url, $shop_options)
{
$date = Carbon::parse($comments_data['date']);
if ($shop_options->filter_status == 1)
{
$comments = str_replace(explode(',', $shop_options->filter_find_words), explode(',', $shop_options->filter_alter_words), $comments_data['comment']);
} else
{
$comments = $comments_data['comment'];
}
$faker = Factory::create();
$this->shop_name = $shop;
$this->comment = $comments;
$this->rating = $this->check_rating_value($comments_data['rating']);
$this->product_id = $product_id;
$this->user_name = $faker->userName;
$this->product_url = $url;
$this->created_at = $date->toDateTimeString();
$this->country = $comments_data['country'] == 'IL' ? 'PS' : $comments_data['country'];
$this->view = 1;
$this->save();
return $this->id;
}