PHP delete item from Shopping cart - php

I created a very simple shopping cart that just add item s to it and delete items from it and empty the cart too now I know I have a lot of issues in my code but I am trying to fix them as well
first see my code
if (isset($_SESSION['cart'])) {
foreach ($_SESSION['cart'] as $c) {
echo $c['name'] . '<br />';
echo $c['price'] . '<br />';
echo 'Remove item<br />';
}
}
if (isset($_POST['buy'])) {
//header("Location:?pid=18&pl=" . $pl);
if (isset($_POST['buy'])) {
$getData = $db->prepare('SELECT * FROM plans WHERE id=?');
$getData->bind_param('i', $pl);
if ($getData->execute()) {
$res = $getData->get_result();
if (($pn = $res->fetch_object()) !== null) {
$proCode = rand(1, 100);
$item['name'] = $pn->plan_name;
$item['price'] = $pn->price_dollar;
$item['code'] = $proCode;
$_SESSION['cart'][] = $item;
}
}
}
}
echo 'Empty Cart';
if (isset($_GET['rc']) && isset($_SESSION['cart'])) {
$rem = $_GET['rc'];
$ses = $_SESSION['cart'];
foreach ($_SESSION['cart'] as $cartItem) {
if ($cartItem["code"] == $rem) {
unset($ses[$rem]);
}
}
/*if (($key = array_search($rem, $ses)) !== false) {
unset($ses[$key]);
}*/
var_dump($ses);
}
if (isset($_GET['ac']) == 'empty' && isset($_SESSION['cart'])) {
unset($_SESSION['cart']);
}
for now the adding new products is working fine with me but the issue
comes when I am trying to remove one item from the caret it return back and noting seems to happened, and the item still there in the cart

you are unsetting $ses variable not $_SESSION...
Please have a look at the updated code, you dont even need to use a forloop, you can just unset the variable as I done below
if (isset($_GET['rc']) && isset($_SESSION['cart']))
{
$rem = $_GET['rc'];
if(isset($_SESSION['cart'][$rem]))
{
unset($_SESSION['cart'][$rem]);
}
}
let me know if this help you
EDIT
Please update your buy product function to below one.. you are using auto increament key for array.. it should be the primary key (here your product code)
if (isset($_POST['buy'])) {
//header("Location:?pid=18&pl=" . $pl);
if (isset($_POST['buy'])) {
$getData = $db->prepare('SELECT * FROM plans WHERE id=?');
$getData->bind_param('i', $pl);
if ($getData->execute()) {
$res = $getData->get_result();
if (($pn = $res->fetch_object()) !== null) {
$proCode = rand(1, 100);
$item['name'] = $pn->plan_name;
$item['price'] = $pn->price_dollar;
$item['code'] = $proCode;
$_SESSION['cart'][$proCode] = $item;
}
}
}
}

try to change your deleting cycle to this:
foreach ($_SESSION['cart'] as $key=>$cartItem) {
if ($cartItem["code"] == $rem) {
unset($_SESSION['cart'][$key]);
}

Related

Duplicate items when adding in my order in the cart

I have a problem with my shopping cart functionality of my restaurant website.
For example, if i add an item to the cart, then i add another item, then if I delete the one I added last and add it again, it's adding itself doubled in the session. Here I have the functions for adding and removing the items in the shopping cart:
function AddProd($id_prod, $quant) {
if(isset($_SESSION['cart'])){
$_SESSION['cart'].=$id_prod.'>'.$quant.",";
} else {
$_SESSION['cart']=$id_prod.'>'.$quant.",";
}
}
function RemoveFromCart($id_prod) {
if(isset($_SESSION['cart'])) {
$n = $_SESSION['cart'];
$prod_id = substr($n, 0, -1);
$ids = explode(',', $prod_id);
$prods = '';
foreach ($ids as $id) {
$i = explode('>', $id);
if($i[0] != $id_prod) $prods = $prods.''.$id.',';
}
$_SESSION['cart'] = $prods;
}
}
Here i have the function which sets the quantity of the item:
function SetCartNumber($conn) {
if(isset($_SESSION['cart'])) {
$n = $_SESSION['cart'];
$prod_id = substr($n, 0, -1);
$ids = array_map('trim', explode(',', $prod_id));
foreach ($ids as $id) {
$i = explode('>', $id);
$total = $total + $i[1];
}
return $total;
}
return 0;
}
Here it inserts into databse:
function LastId($conn, $tbl){
$s = 'SELECT `id` FROM `'.$tbl.'` ORDER BY `id` DESC LIMIT 1';
if ($r = mysqli_query($conn, $s)) {
$rowd = mysqli_fetch_array($r, MYSQLI_NUM);
return $rowd[0];
}
return -1;
}
$t_price = (empty(GetPromotion($connect))) ? $total_price : '<span style="color: white; font-weight: bold;">'.SetPromotion($connect).'</span> <span style="text-decoration: line-through; color: red;">'.$total_price.'</span>';
if(isset($_POST['delete_prod'])) {
RemoveFromCart($_POST['delete_prod']);
echo '<script type="text/JavaScript"> setTimeout("location.href = \'cart\';",100); </script>';
}
if(isset($_POST['decrease_prod'])) {
ProdsDecrease($_POST['decrease_prod']);
echo '<script type="text/JavaScript"> setTimeout("location.href = \'cart\';",100); </script>';
}
if(isset($_POST['increase_prod'])) {
ProdsIncrease($_POST['increase_prod']);
echo '<script type="text/JavaScript"> setTimeout("location.href = \'cart\';",100); </script>';
}
if (!empty($_POST['trimite']))
{
$str_name = ($str_name[strlen($str_name)-2] == ',') ? substr($str_name, 0, -2) : $str_name;
$str_name2 = ($str_name2[strlen($str_name2)-2] == ',') ? substr($str_name2, 0, -2) : $str_name2;
$price = (empty(SetPromotion($connect))) ? SetCartPrice($connect) : SetPromotion($connect);
$price = (!empty(GetPromotion($connect))) ? $price.' lei(Promotie activa: '.GetPromotion($connect).'%)' : $price;
$prods = MailProds($connect);
$quantity = SetCartNumber($connect);
$price1 = (empty(SetPromotion($connect))) ? SetCartPrice($connect) : SetPromotion($connect);
$price1 = floatval($price1);
$quantity = floatval($quantity);
$email = filter_input(INPUT_POST, 'email');
$telefon = filter_input(INPUT_POST, 'telefon');
$mentiuni = filter_input(INPUT_POST, 'mentiuni');
$tacamuri = filter_input(INPUT_POST, 'tacamuri');
if(!empty(get())) { $email = getEmail($connect); }
$sql = "INSERT INTO `comenzi`(`name`, `pret`, `cantitate`, `adresa_mail`, `nr_telefon`, `mentiuni`, `tacamuri`) VALUES ('$prods', '$price1', '$quantity', '$email', '$telefon', '$mentiuni', '$tacamuri')";
How could I solve the issue?
the problem is in addProd funtion function. you session must contains unique prodId values. but when you are adding the same product again. you are not deleting the first then you will face the problem.
so you should check if the product is already is in session or not, before adding it.
or you should update it.

creating simple shopping cart using PHP

I am trying to crate a very simple shopping cart
I am using a session and array to add the items to an array and save the array into session and display the items in this session properly like
item 1 name -- price
item 2 name -- price
and then take the total to my payment method.
here is the code I am using.
print_r($_SESSION['cart']);
if (isset($_POST['buy'])) {
//header("Location:?pid=18&pl=" . $pl);
$getData = $db->prepare('SELECT * FROM plans WHERE id=?');
$getData->bind_param('i', $pl);
if ($getData->execute()) {
$res = $getData->get_result();
if ($pn = $res->fetch_object()) {
$item['name'] = $pn->plan_name;
$item['price'] = $pn->price_dollar;
if (isset($_SESSION['cart'])) {
$_SESSION['cart'] = $item;
}
}
}
}
Issues
( ! ) Notice: Undefined index: cart
EDIT
this is what I end with
if (isset($_SESSION['cart'])) {
foreach ($_SESSION['cart'] as $c) {
echo $c['name'] . '<br />';
echo $c['price'] . '<br />';
echo 'Remove item<br />';
}
}
if (isset($_POST['buy'])) {
//header("Location:?pid=18&pl=" . $pl);
if (isset($_POST['buy'])) {
$getData = $db->prepare('SELECT * FROM plans WHERE id=?');
$getData->bind_param('i', $pl);
if ($getData->execute()) {
$res = $getData->get_result();
if (($pn = $res->fetch_object()) !== null) {
$proCode = range(1, 100);
shuffle($proCode);
$item['name'] = $pn->plan_name;
$item['price'] = $pn->price_dollar;
$item['code'] = $proCode;
$_SESSION['cart'][] = $item;
}
}
}
}
if (isset($_GET['rc']) && isset($_SESSION['cart'])) {
$rem = $_GET['rc'];
if (($key = array_search($rem, $_SESSION['cart'])) !== false) {
unset($_SESSION['cart'][$key]);
}
}
but still the delete not working
As I can see, you're trying to print a variable that isn't set. Plus, with this code:
if (isset($_SESSION['cart'])) {
$_SESSION['cart'] = $item;
}
You'll never be able to add an item to your cart. My way to do this is the following:
if (isset($_POST['buy'])) {
$getData = $db->prepare('SELECT * FROM plans WHERE id=?');
$getData->bind_param('i', $pl);
if ($getData->execute()) {
$res = $getData->get_result();
if ($pn = $res->fetch_object()) {
$item['name'] = $pn->plan_name;
$item['price'] = $pn->price_dollar;
$_SESSION['cart'][] = $item;
}
}
}
This way, even if the cart key isn't set, it will be set anyway. By the same time, it will permit you to have multiple items in your cart.
EDIT: The next thing to do, if you want to show your items is the following:
foreach ($_SESSION['cart'] as $k => $item) {
echo "item $item->id $item->plan_name -- $item->price_dollar";
}

How to Update Categories that Already Exists in Magento Database Using Custom Script

I have Already Created The Categories in Magento by using the custom script,
but issue is when I again run the same URL my script creates another set of same category. as i want to update the existing category and insert the new categories if exist in the csv.
My csv structure is:
Category 1,Description,Category 2,Description,Category 3,Description,Category 4,Description
1,COSTUMES,1,ADULTS,1,MENS
1,COSTUMES,1,ADULTS,1,MENS,2,ASIAN
1,COSTUMES,1,ADULTS,1,MENS,3,BIKER
1,COSTUMES,1,ADULTS,1,MENS,1,CAPES & ROBES
1,COSTUMES,1,ADULTS,1,MENS,5,CAVE PEOPLE
Thanking All of You in Advance For Your Answer
Below is my code to create multi level categories:
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/app/Mage.php';
umask(0);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$count = 0;
$file = fopen('export/web categories.csv', 'r');
function odd($var)
{
$odd = array();
foreach ($var as $k => $v) {
if ($k % 2 !== 0) {
$odd[$k] = $v;
}
}
return $odd;
}
function even($var)
{
$even = array();
foreach ($var as $k => $v) {
if ($k % 2 == 0) {
$even[$k] = $v;
}
}
return $even;
}
function strcount($str,$sy){
$ch= explode($sy, $str);
return count($ch);
}
$pos=0;
$row_config= array();
$test=array();
$catgoryID=array();
$parID = 1;
while (($line = fgetcsv($file)) !== FALSE) {
if(!in_array($valtest,$row_config)){
if($count == 0){
$count++;
continue;
}
$count++;
$filterd_data=array_filter($line);
$odd_cell_data=odd($filterd_data);
$even_cell_data=even($filterd_data);
$config=array();
$string='';
$intialID=$even_cell_data[0];
foreach($odd_cell_data as $key=>$val){
if(!in_array($val,$config)){
$config[] = $val;
$data['general']['name'] =$val;
$data['general']['meta_title'] = "";
$data['general']['meta_description'] = "";
$data['general']['is_active'] = "";
$data['general']['url_key'] = "";
$data['general']['is_anchor'] = 0;
$data['general']['position'] =1 ;
$storeId = 0;
$string .=$val.'~';
if(!array_key_exists($string, $row_config)){
$catID=createCategory($data, $storeId);
$catgoryID[$string]=$catID;
$row_config[$string]=$parID;
} else {
$parID =$row_config[$string] ;
$row_config[$string]=$row_config[$string];
}
if( strcount($string,'~')==2){
$parID=1;
}
$int[$string]=$parID;
assignCat($catgoryID[$string],$parID);
$parID = $catgoryID[$string];
sleep(0.5);
unset($data);
}
}
}
}
//This Function is used for create each category
function createCategory($data, $storeId) {
$category = Mage::getModel('catalog/category');
$category->setStoreId($storeId);
if (is_array($data)) {
$category->addData($data['general']);
if (!$category->getId()) {
$parentId = $data['category']['parent'];
if (!$parentId) {
if ($storeId) {
$parentId = Mage::app()->getStore($storeId)->getRootCategoryId();
} else {
$parentId = Mage_Catalog_Model_Category::TREE_ROOT_ID;
}
}
$parentCategory = Mage::getModel('catalog/category')->load($parentId);
$category->setPath($parentCategory->getPath());
} if ($useDefaults = $data['use_default']) {
foreach ($useDefaults as $attributeCode) {
$category->setData($attributeCode, null);
}
}
$category->setAttributeSetId($category->getDefaultAttributeSetId());
if (isset($data['category_products']) && !$category->getProductsReadonly()) {
$products = array();
parse_str($data['category_products'], $products);
$category->setPostedProducts($products);
} try {
$category->save();
$category = Mage::getModel('catalog/category')->load($category->getId());
$category->setPosition($data['general']['position']);
$category->addData($data['general']);
$category->save();
echo "Suceeded <br /> ";
} catch (Exception $e) {
echo "Failed <br />";
}
}
return $category->getId();
}
//This Function is used for moving category under respective parent
function assignCat($id, $parent){
$category = Mage::getModel( 'catalog/category' )->load($id);
Mage::unregister('category');
Mage::unregister('current_category');
Mage::register('category', $category);
Mage::register('current_category', $category);
$category->move($parent);
return;
}

Increase quantity when adding same item to cart session?

At the moment, I have a shopping cart that will add an item to the cart session. If another of the same item is added to the cart, it displays duplicate items, each with a quantity of 1.
What do I need to add/change for the code to update the quantity of an existing item? Instead of adding a duplicate item.
add_to_cart.php
session_start();
include 'cart.php';
$item_id = $_POST['item_id'];
$qty = $_POST['qty'];
$counter = $_SESSION['counter'];
$cart = new Cart();
if ($counter>0)
{
$cart = unserialize($_SESSION['cart']);
}
else
{
$_SESSION['counter'] = 0;
$_SESSION['cart'] = "";
}
if (($item_id == "")or ($qty < 1))
{
header("Location: products.php");
}
else
{
require_once('conn_db.php');
$query = "SELECT item_name, price FROM products WHERE (item_id=$item_id)";
$result = mysql_query($query) or die("Database Error");
if(mysql_num_rows($result) == 1)
{
$price = mysql_result($result, 0,"price");
$item_name = mysql_result($result, 0, "item_name");
$new_item = new Item($item_id, $item_name, $qty, $price);
$cart->add_item($new_item);
$_SESSION['counter'] = $counter+1;
$_SESSION['cart'] = serialize($cart);
header("Location: products.php");
mysql_close();
}
else
{
header("Location: products.php");
}
}
cart.php
class Item {
var $item_id;
var $item_name;
var $qty;
var $price;
var $deleted = false;
function get_item_cost() {
return $this->qty * $this->price;
}
function delete_item() {
$this->deleted = true;
}
function Item($item_id, $item_name, $qty, $price) {
$this->item_id = $item_id;
$this->item_name = $item_name;
$this->qty = $qty;
$this->price = $price;
}
function get_item_id() {
return $this->item_id;
}
function get_item_name() {
return $this->item_name;
}
function get_qty() {
return $this->qty;
}
function get_price() {
return $this->price;
}
}
class Cart {
var $items;
var $depth;
function Cart() {
$this->items = array();
$this->depth = 0;
}
function add_item($item) {
$this->items[$this->depth] = $item;
$this->depth++;
}
function delete_item($item_no) {
$this->items[$item_no]->delete_item();
}
function get_depth() {
return $this->depth;
}
function get_item($item_no) {
return $this->items[$item_no];
}
}
Fairly quick example, should put in you in the right direction. You'll need to chance your add_item() to check to see if the cart already contains the item
function add_item($item) {
$item_already_exists = false;
foreach ($this->items as $depth_id => $item_in_cart) { // loop through the current contents of the cart
if ($item_in_cart->get_item_id() == $item->get_item_id()) { // if the item already exists in the cart
$item_already_exists = true;
$item_exists_at = $depth_id;
break;
}
}
if ($item_already_exists == true) { //update the existing item
$this->items[$item_exists_at]->update_qty($item->get_qty());
} else { // add the new item
$this->items[$this->depth] = $item;
$this->depth++;
}
}
Then you'll need to create an update_quantity() in your Item class
function update_qty($qty) {
$this->qty += $qty;
}
Before adding the item check if it already exists in the shopping cart. If False, add it. If True, just change the quantity! :)

Update shipping price after picked price (PHP)

I am working on a shopping cart for my site. In the cart area I pull shipping details from the db, including the price depending on zip code. When the user clicks "update cart".
I am trying to update the total with the shipping price. If anyone can point me in the right direction of figuring this out.
This is my function to display the cart.
function showCart() {
$cart = $_SESSION['cart'];
$zip = $_SESSION['zipcode'];
if ($cart) {
$items = explode(',',$cart);
$contents = array();
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
$output[] = '<form action="cart.php?action=update" method="post" id="cart">';
$output[] = '<table>';
foreach ($contents as $id=>$qty) {
$sql = 'SELECT * FROM products WHERE id = '.$id;
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
extract($row);
$output[] = '<tr>';
$output[] = '<td>Remove</td>';
$output[] = '<td>'.$title.' by '.$author.'</td>';
$output[] = '<td>$'.$price.'</td>';
$output[] = '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>';
$output[] = '<td>$'.($price * $qty).'</td>';
$total += $price * $qty;
$output[] = '</tr>';
}
$output[] = '</table>';
$sql = 'SELECT * FROM zipcodes WHERE zipcode = '.$zip;
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$output[] = '<label>Price: </label><select name="delivery" id="delivery" class="long-field">';
$output[] = '<option value="">Please Select</option>';
$output[] = '<option value='.$row['free_dev'].'>$'.$row['free_dev'].'</option>';
$output[] = '<option value='.$row['next_day_dev'].'>$'.$row['next_day_dev'].'</option>';
$output[] = '</select>';
}
$output[] = '<p>Delivery Charge: <strong>$'.$delivery.'</strong></p>';
$output[] = '<p>Grand total: <strong>$'.$total.'</strong></p>';
$output[] = '<div><button type="submit">Update cart</button></div>';
$output[] = '</form>';
} else {
$output[] = '<p>You shopping cart is empty.</p>';
}
return join('',$output);
}
And this the update part via cart.php
case 'update':
if ($cart) {
$newcart = '';
foreach ($_POST as $key=>$value) {
if (stristr($key,'qty')) {
$id = str_replace('qty','',$key);
$items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart);
$newcart = '';
foreach ($items as $item) {
if ($id != $item) {
if ($newcart != '') {
$newcart .= ','.$item;
} else {
$newcart = $item;
}
}
}
for ($i=1;$i<=$value;$i++) {
if ($newcart != '') {
$newcart .= ','.$id;
} else {
$newcart = $id;
}
}
}
}
}
$cart = $newcart;
break;
Thank you. Any help is greatly appreciated!
PS i am using the tutorial for the cart from here http://v3.thewatchmakerproject.com/journal/276/
Given that the code you provide is fairly agnostic to this problem, it's unclear where you're running into a wall. But to get you started:
case 'update':
if ($cart) {
$newcart = '';
foreach ($_POST as $key=>$value) {
... //same thing as before
}
$newcart .= $shipping_price; //or however you're encoding this. It's unclear.
}
$cart = $newcart;
break;
And also replace:
$output[] = '<p>Grand total: <strong>$'.$total.'</strong></p>';
with:
$output[] = '<p>Grand total: <strong>$'.$total+ $shipping_price.'</strong></p>';
If I were you I would search for a PHP Class shopping cart, that code reminds me of some PHP4 (and it should since the example is from 2005).
I didn't find a good link for an example, I'll try to describe the idea bellow.
You create two classes one represents the item the other the shopping cart ( the first can be just a result from a DB with mysql_fetch_object or something like Pdo it will turn it into a stdClass from php
class someItem
{
public $id;
public $qty;
public $price;
public $totalprice;
public function __get($var)
{
if ($var == 'totalPrice') {
return $this->price*$this->qty;
}
return $this->$var;
}
}
class ShoppingCart
{
private $items;
public function addItem($someItem)
{
if (array_key_exists($someItem->id, $this->items)) {
$this->items[$someItem->id]->qty = $this->items[$someItem->id]->qty + $someItem->qty;
} else {
$this->items[$someItem->id] = $someItem;
}
}
public function removeItem($someItem)
{
unset($this->items[$someItem->id]);
}
public function getTotal()
{
$total = 0;
foreach($this->items as $item){
$total += $item->totalPrice;
}
return $total;
}
}
serialize the info into the session
$_SESSION['user']['cart'] = serialize($Shoppingcart);
set a new shopping cart when user logs in clean it when he logs out.
Adding and removing the items can be done before everything
// whatever operation you whant and deal according to your HTML Form
foreach ($_POST['cart'] as $itemId ) {
$ItemObj = $db->getitemAsObject($itemId); // Use PDO or something
$shoppingcart->addItem($itemObj);
}
Resave the shopping cart to session after post
$_SESSION['user']['cart'] = serialize($Shoppingcart);

Categories