Updating Stock Levels in Magento from a CSV - php

I have a script that will update the stock quantities in Magento based on matching a SKU. This works fine as long as the headings in the CSV match the fields in Magento they are updating e.g.
sku,qty
ABC123,20
ABC124,20
However my source CSV the headings are named "product id" and "quantity" e.g.
product id,quantity
ABC123,20
ABC124,20
How would I remap the array key name so as the import would work?
require_once '../app/Mage.php';
umask(0);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$count = 0;
$file = fopen('/home/public_html/mysite/csvs/my.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
if ($count == 0) {
foreach ($line as $key=>$value) {
$cols[$value] = $key;
}
}
$count++;
if ($count == 1) continue;
#Convert the lines to cols
if ($count > 0) {
foreach($cols as $col=>$value) {
unset(${$col});
${$col} = $line[$value];
echo ${$col};
}
}
//print_r($cols); die();
// Check if SKU exists
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$sku);
if ( $product ) {
$productId = $product->getId();
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
$stockItemId = $stockItem->getId();
$stock = array();
if (!$stockItemId) {
$stockItem->setData('product_id', $product->getId());
$stockItem->setData('stock_id', 1);
} else {
$stock = $stockItem->getData();
}
foreach($cols as $col=>$value) {
$stock[$col] = $line[$value];
}
foreach($stock as $field => $value) {
$stockItem->setData($field, $value?$value:0);
}
$stockItem->save();
unset($stockItem);
unset($product);
}
echo "<br />Stock updated $sku";
}
fclose($file);

You can try the following article which works great:
http://www.blog.magepsycho.com/updating-product-qty-in-magento-in-an-easier-faster-way/
which is simply based on raw sql queries and very fast even for millions of sku's qty updates.
Thanks

Related

Custom Products Export PHP Script Not working

I need to export csv like, SKU | Category Id | Category Name, After export the SKU field empty remaining have the value.
Code : https://codeshare.io/5Q690Q
How to find the error?
try this code.
<?php
$mageFilename = 'app/Mage.php';
if (!file_exists($mageFilename)) {
echo $mageFilename." was not found";
exit;
}
require_once $mageFilename;
Mage::app();
try {
function getCategoryData()
{
$category = Mage::getModel('catalog/category');
$tree = $category->getTreeModel();
$tree->load();
$ids = $tree->getCollection()->getAllIds();
$categories = array();
$rootCategoryId = 2;
if ($ids)
{
foreach ($ids as $id)
{
$category->load($id);
$categories[$id]['name'] = $category->getName();
$categories[$id]['path'] = $category->getPath();
}
foreach ($ids as $id)
{
$path = explode('/', $categories[$id]['path']);
$string = '';
foreach ($path as $pathId)
{
if($pathId == 1 || $rootCategoryId == $pathId ) continue;
$string.= $categories[$pathId]['name'] . '/';
}
$categoryFullPaths[$id] = rtrim($string,"/");
}
}
return $categoryFullPaths;
}
function get_values_for_keys($mapping, $keys)
{
$output_arr = array();
foreach($keys as $key)
{
$output_arr[] = $mapping[$key];
}
return $output_arr;
}
$products = Mage::getModel("catalog/product")->getCollection();
$products->addAttributeToSelect('category_ids');
$products->addAttributeToSelect('sku');
$fp = fopen('var/export/exports.csv', 'w');
$csvHeader = array("sku", "category_ids","category_name");
fputcsv( $fp, $csvHeader,",");
$cat_name = array();
$cat_array = array();
$categoryFullPaths = getCategoryData();
foreach ($products as $product)
{
$sku = $product->getSku();
$categoryIds = implode('/', $product->getCategoryIds());//change the category separator
$_cate_name = join(',', get_values_for_keys($categoryFullPaths, $product->getCategoryIds()));
fputcsv($fp, array($sku, $categoryIds,$_cate_name), ",");
}
fclose($fp);
} catch (Exception $e) {
echo $e->getMessage();
exit;
}

Add new columns for CSV file

I have tree arrays with different lengths, and I want to display each array in a column of my csv file. That's the php script file I am using but no success; I got the data duplicated.
The attempt I tried was to feed empty cells with an empty string so that I can have 3 columns with the same lengths.
$categories = get_categories( $args );
$categories_level_1 = array();
$categories_level_2 = array();
$categories_level_3 = array();
foreach ($categories as $cat ) {
$cat_level =count( get_ancestors($cat->term_id, 'category') );
if($cat_level == 0){
$categories_level_1[] = $cat;
}else{
if($cat_level == 1){
$categories_level_2[] = $cat;
}elseif($cat_level == 2){
$categories_level_3[] = $cat;
}
}
}
fputcsv($file, array(utf8_decode('Catégories level 1')));
$i=0;
foreach ($categories_level_1 as $category) {
$i++;
$categorie_name = array(rw_mb_convert_encoding($category->name));
fputcsv($file, $categorie_name );
print_flush("\n liine created");
}
while( $i < count($categories_level_2)){
$i++;
fputcsv($file, array(" "));
print_flush("\n liine vide created");
}
fclose($file);
$newCsvData = array();
foreach ($categories_level_2 as $cat) {
if (($handle = fopen($csv_file_path, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$data[] = rw_mb_convert_encoding($cat->name);
$newCsvData[] = $data;
}
fclose($handle);
}
}
$handle = fopen($csv_file_path, 'w');
foreach ($newCsvData as $line) {
fputcsv($handle, $line);
}
fclose($handle);
I should get my columns with the folowwing structure :
But in reality that's the result I got :

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

Categories