Update shipping price after picked price (PHP) - 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);

Related

PHP delete item from Shopping cart

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]);
}

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;
}

How to show product attributes in list.phtml (Magento) where the Stock Availability is "In Stock"

I have found this code:
$attributeCode = 'shoe_size';
$product = Mage::getModel('catalog/product');
$productCollection = Mage::getResourceModel('eav/entity_attribute_collection')
->setEntityTypeFilter($product->getResource()->getTypeId())
->addFieldToFilter('attribute_code', $attributeCode);
$attribute = $productCollection->getFirstItem()->setEntity($product->getResource());
print_r($attribute->getData()); // print out the available attributes
$options = $attribute->getSource()->getAllOptions(false);
print_r($options); // print out attribute options
The problem is it prints all the shoe sizes. I want only those which are "in stock"
Thank you in advance!
<?php
if ($_product->isConfigurable()&&$_product->isSaleable()) {
$allProducts = $_product->getTypeInstance(true)->getUsedProducts(null, $_product);
$sizeArray = array();
foreach ($allProducts as $subproduct) {
if ($subproduct->isSaleable()) {
if($subproduct->getAttributeText('ATTRIBUTES')){
$sizeArray[] = $subproduct->getAttributeText('ATTRIBUTES');
}else{
$sizeArray[] = $subproduct->getAttributeText('size_shorts_and_capris');
}
}
}
echo $this->__('Sizes: ');
for ($x = count($sizeArray)-1; $x >= 0; $x--){
echo $sizeArray[$x];
if($x != 0)echo ', ';
}
}
?>
<span class="price hover-toggle">
<?php
if ($_product->isConfigurable()&&$_product->isSaleable()) {
$allProducts = $_product->getTypeInstance(true)->getUsedProducts(null, $_product);
$sizeArray = array();
foreach ($allProducts as $subproduct) {
if ($subproduct->isSaleable()) {
if($subproduct->getAttributeText('size')){
$sizeArray[] = $subproduct->getAttributeText('size');
}else{
$sizeArray[] = $subproduct->getAttributeText('size_shorts_and_capris');
}
}
}
echo $this->__('Sizes: ');
$customSizeArr = array();
$sizeOrder = array('S','M','L','XL','XXL');
if(!empty($sizeArray)){
foreach($sizeArray as $val){
if($val =='S')
$customSizeArr[0] = $val;
if($val =='M')
$customSizeArr[1] = $val;
if($val =='L')
$customSizeArr[2] = $val;
if($val =='XL')
$customSizeArr[3] = $val;
if($val =='XXL')
$customSizeArr[4] = $val;
}
}
ksort($customSizeArr);
echo (implode(", ",$customSizeArr));
}
?>
</span>

Build tree from parent_id id table structure

I'm trying to build a tree with the exact specifications of..
This Question
Basically I need to create a tree from a parent - id table structure.
I'm using this function to try to achieve the above;
private static function fetch_recursive($src_arr, $currentid = 0, $parentfound = false, $cats = array())
{
foreach($src_arr as $row)
{
if((!$parentfound && $row['category_id'] == $currentid) || $row['parent_id'] == $currentid)
{
$rowdata = array();
foreach($row as $k => $v)
$rowdata[$k] = $v;
$cats[] = $rowdata;
if($row['parent_id'] == $currentid)
$cats = array_merge($cats, CategoryParentController::fetch_recursive($src_arr, $row['category_id'], true));
}
}
return $cats;
}
But I'm getting an error from PHP :
Maximum function nesting level of 100 reached, aborting!
I'm ordering the db results by parent_id and then by id to help out with the issue but it still persists.
As a side note by table contains ~250 records.
Finally found a solution that fits my needs! Thanks for all the help everyone and also for the constructive criticism :)
Laravel 4 - Eloquent. Infinite children into usable array?
Solution:
<?php
class ItemsHelper {
private $items;
public function __construct($items) {
$this->items = $items;
}
public function htmlList() {
return $this->htmlFromArray($this->itemArray());
}
private function itemArray() {
$result = array();
foreach($this->items as $item) {
if ($item->parent_id == 0) {
$result[$item->name] = $this->itemWithChildren($item);
}
}
return $result;
}
private function childrenOf($item) {
$result = array();
foreach($this->items as $i) {
if ($i->parent_id == $item->id) {
$result[] = $i;
}
}
return $result;
}
private function itemWithChildren($item) {
$result = array();
$children = $this->childrenOf($item);
foreach ($children as $child) {
$result[$child->name] = $this->itemWithChildren($child);
}
return $result;
}
private function htmlFromArray($array) {
$html = '';
foreach($array as $k=>$v) {
$html .= "<ul>";
$html .= "<li>".$k."</li>";
if(count($v) > 0) {
$html .= $this->htmlFromArray($v);
}
$html .= "</ul>";
}
return $html;
}
}

Categories