PHP Shopping Cart Session problems - array-push

I have yet another problem with my shopping cart. Everytime I run this code:
if(isset($_GET["atc"]))
{
extract($_GET);
$link = mysqli_connect("localhost", "root", "*******", "souljaz");
$sql = "SELECT * FROM products WHERE id='{$pid}'";
if($result = mysqli_query($link, $sql))
{
while($row = mysqli_fetch_assoc($result))
{
array_push($_SESSION["prod_names"], $row["name"]);
}
}
}
I get this error message:
Warning: array_push() expects parameter 1 to be array, null given in C:\Aapche2.2\htdocs\products.php on line 20
So I changed my code to this:
$_SESSION["prod_names"] = array();
if(isset($_GET["atc"]))
{
extract($_GET);
$link = mysqli_connect("localhost", "root", "*******", "souljaz");
$sql = "SELECT * FROM products WHERE id='{$pid}'";
if($result = mysqli_query($link, $sql))
{
while($row = mysqli_fetch_assoc($result))
{
array_push($_SESSION["prod_names"], $row["name"]);
}
}
}
Then I get unexpected results because everytime the script runs the $_SESSION["prod_names"] = array(); is reset. So array_push() doesnt work as intented.

You could do a check on your array to see if it's empty before assigning it, that way it will only initialize the first time.

Related

How to get Invoice data in magento?

i am trying here ,
see i am getting order data but, i am not getting any $order->hasInvoice()
$orderID = 100000062;
$order = Mage::getModel('sales/order')->load($orderID);
if ($order->hasInvoices()) {
$invIncrementIDs = array();
foreach ($order->getInvoiceCollection() as $inv) {
$invIncrementIDs[] = $inv->getIncrementId();
} Mage::log($invIncrementIDs);
}
Could you please try the following code:
$orders_invoice = Mage::getModel("sales/order_invoice")->getCollection();
foreach($orders_invoice as $val) {
print_r($val->getData());
}

Adding attribute options programmatically are not available for use immediately

I'm creating Magento attribute options via a script, but I need to then be able to get the new ID and use it straight away in the same script.
At the moment it's not pulling the id through - if I kill the script and re-start it it picks up the created option and returns the ID, but not as part of the same script.
Here is the code I am using:
$attr = Mage::getModel('catalog/product')->getResource()->getAttribute($key);
if ($attr->usesSource()) {
$vattr_id = $attr->getSource()->getOptionId($value);
}else{
echo "No Source";
$vattr_id = false;
}
if($vattr_id){
return $vattr_id;
}else{
$attr_model = Mage::getModel('catalog/resource_eav_attribute');
$attr = $attr_model->loadByCode('catalog_product', $key);
$attr_id = $attr->getAttributeId();
$option['attribute_id'] = $attr_id;
$option['value'][$value][0] = $value;
$option['value'][$value][1] = $value;
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$setup->addAttributeOption($option);
$attr = Mage::getModel('catalog/product')->getResource()->getAttribute($key);
if ($attr->usesSource()) {
$vattr_id = $attr->getSource()->getOptionId($value);
echo "AttrID: $vattr_id";
}
}
Running this (with the required Mage::app() etc), creates the option, you can see it in the Magento back end, but the $vattr_id is NULL. If I reload the script, then it finds the attribute option in that first block as it should.
I guess it's something to do with how Magento is caching the models, but not sure where I need to look to clear these?
function getAttributeOptionId($attributeName, $attributeValue) {
/* #var $attribute Mage_Eav_Model_Entity_Attribute */
$attribute = Mage::getModel("eav/entity_attribute")->loadByCode("catalog_product", $attributeName);
// checking attribute code
if ($attribute->getId()) {
$source = $attribute->getSource();
$options = $source->getAllOptions();
// looking for existing id
foreach ($options as $optionValue) {
if ($attributeValue == $optionValue["label"]) {
return $optionValue["value"];
}
}
// making new option
$addOptionData = array(
"attribute_id" => $attribute->getId(),
"value" => array(array($attributeValue))
);
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$setup->addAttributeOption($addOptionData);
// getting new id
$attribute = Mage::getModel("eav/entity_attribute")->loadByCode("catalog_product", $attributeName);
$source = $attribute->getSource();
$options = $source->getAllOptions();
foreach ($options as $optionValue) {
if ($attributeValue == $optionValue["label"]) {
return $optionValue["value"];
}
}
}
return null;
}
echo getAttributeOptionId("brand", "Intel");

How to create custom script for import products in magento

I am working on magento 1.8 version.
I need to create custom script or extenson for import product from my custom csv file which have some different fields.
Any help would be much appriciated.
Thanks
Best way is to use OS Magmi, is much more faster than script an is simple to configure and periodical run.
http://sourceforge.net/projects/magmi/
You can also create a script which can you run.
you need to get data from csv file to memory
2 convert them to array
3 list array for each product
4 in foreach loop save or update product.
Some basic script:
<?php
$max_i = 20000; // maximal ammount
chdir(dirname(__FILE__)); /
//error_reporting(E_ALL | E_STRICT);
//ini_set("display_errors", 1);
ini_set("memory_limit","1024M");
ini_set('max_execution_time', 3600000);
date_default_timezone_set('Europe/Prague');
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$time_start = microtime_float();
//////// SKU from CSV
$csv = file_get_contents ('yourcsvfile.csv');
function parse_csv ($csv_string, $delimiter = ";", $skip_empty_lines = true, $trim_fields = true)
{
$enc = preg_replace('/(?<!")""/', '!!Q!!', $csv_string);
$enc = preg_replace_callback(
'/"(.*?)"/s',
function ($field) {
return urlencode(utf8_encode($field[1]));
},
$enc
);
$lines = preg_split($skip_empty_lines ? ($trim_fields ? '/( *\R)+/s' : '/\R+/s') : '/\R/s', $enc);
return array_map(
function ($line) use ($delimiter, $trim_fields) {
$fields = $trim_fields ? array_map('trim', explode($delimiter, $line)) : explode($delimiter, $line);
return array_map(
function ($field) {
return str_replace('!!Q!!', '"', utf8_decode(urldecode($field)));
},
$fields
);
},
$lines
);
}
// list to array
$vystup = parse_csv($csv);
$seznamsku = array();
foreach ($vystup as $sku) {
array_push($seznamsku, $sku[0]);
unset($seznamsku[0]);
$seznamskufin = array_filter($seznamsku, 'strlen');
};
require("../../app/Mage.php");
echo "START ".date('h:i:s')."\n\n";
Mage::init();
// Set an Admin Session
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
Mage::getSingleton('core/session', array('name' => 'adminhtml'));
$userModel = Mage::getModel('admin/user');
$userModel->setUserId(1);
$session = Mage::getSingleton('admin/session');
$session->setUser($userModel);
$session->setAcl(Mage::getResourceModel('admin/acl')->loadAcl());
$pocet = 1;
foreach ($seznamskufin as $item) {
echo "\n number(".$pocet.")..sku(".$item.")..";
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$item);
if(is_object($product)) { //if is product exist in Magento
if (empty($product->getShortDescription())) { // if is value empty
$product->setShortDescription($ZboziDetail['info']); // write to magento
echo "..(importing)..";
}
else
{
echo "..(skipped).."; // exists
};
$product->save(); // save to magento
echo "..saved";
} else { echo ".(skiped)"; };
unset($item);
unset($product);
unset($ZboziDetail);
unset($product_imageUrl);
unset($newimage);
unset($e);
$pocet++;
};
$time_end = microtime_float();
$time = $time_end - $time_start;
echo " \n\n All done in ".$time." seconds.";
$logfile = fopen('log.txt', 'a');
fwrite($logfile, $seznamskufin);
fclose($logfile);
unset($response);
unset($vystup);
unset($seznamsku);
unset($seznamskufin);
?>
I think the easiest and safest way is to create a simple script (outside Magento) that transforms your csv to the csv structure used for import in System->Import/Export->Import.
TO see the format of the csv you need go to System->Import/Export->Export and export your current products.

Use Tierprices of other customergroup

i'm trying to get my pricing extension working but i'm stucking at the tierprices.
If a visitor comes to my site i added a paramter to the cookie.
Example: http://www.foo.com/category/product.html?sidx=5
Now the visitor enters my site with the sidx parameter. Now the Observer: catalog_product_get_final_price sets the finalprice with the first tierprice of this Product of Customergroup 5.
The Customergroup of the visitor is still NOT LOGGED IN. Now i need the other tierprices of the Customergroup ID 5 without registering.
I have googled a lot to find a solution for that but i don't get the point.
Best Regards
boti
If you want to get the Tier prices for any product:
$product = Mage::getModel('catalog/product')->load(PRODUCT_ID_HERE);
$tierPrices = $product->getData('tier_price');
if (!is_array($tierPrices)) {
$tierPrices = array();
}
$result = array();
foreach ($tierPrices as $tierPrice) {
$row = array();
$row['customer_group_id'] = (empty($tierPrice['all_groups']) ? $tierPrice['cust_group'] : 'all' );
$row['website'] = ($tierPrice['website_id'] ? Mage::app()->getWebsite($tierPrice['website_id'])->getCode() : 'all');
$row['qty'] = $tierPrice['price_qty'];
$row['price'] = $tierPrice['price'];
$result[] = $row;
}
// $result now has an array of all tier prices...
// looking for cust_group = 5 would be trivial:
foreach ($tierPrices as $tierPrice) {
if($tierPrice['cust_group'] == 5) {
return $tierPrice; // this is what you want..
}
}

Magento: UPDATE and DELETE programatically from frontend, not working?

i am trying to update the product from frontend but it does not let me update all the fields of the product,
Here is the code of index controller FOR UPDATING:
public function updateVproductAction(){
if($addvp = $this->getRequest()->getPost())
{
/*********************** Product Update ***************************/
/**
* Get the resource model
*/
$resource = Mage::getSingleton('core/resource');
/**
* Retrieve the write connection
*/
$writeConnection = $resource->getConnection('core_write');
/**
* Retrieve our table name
*/
$table = $resource->getTableName('catalog/product');
/**
* Set the product ID
*/
$productId = $addvp['product']['id'];
/**
* Set the new SKU
* It is assumed that you are hard coding the new SKU in
* If the input is not dynamic, consider using the
* Varien_Db_Select object to insert data
*/
//$newSku = 'new-sku';
$sku = $addvp['product']['sku'];
$name = $addvp['product']['name'];
$description = $addvp['product']['description'];
$short_description = $addvp['product']['short_description'];
$weight = $addvp['product']['weight'];
$news_from_date = $addvp['product']['news_from_date'];
$news_to_date = $addvp['product']['news_to_date'];
$status = $addvp['product']['status'];
$price = $addvp['product']['price'];
$special_price = $addvp['product']['special_price'];
$tax_class_id = $addvp['product']['tax_class_id'];
$meta_title = $addvp['product']['meta_title'];
$meta_keyword = $addvp['product']['meta_keyword'];
$meta_description = $addvp['product']['meta_description'];
$stock_data = array(
'is_in_stock' => 1,
'qty' => $addvp['product']['stock_data']['qty']
);
$query = "UPDATE {$table} SET sku = '{$sku}', name = '{$name}', description = '{$description}', short_description = '{$short_description}', weight = '{$weight}', news_from_date = '{$news_from_date}', news_to_date = '{$news_to_date}', status = '{$status}', price = '{$price}', special_price = '{$special_price}', tax_class_id = '{$tax_class_id}', meta_title = '{$meta_title}', meta_keyword = '{$meta_keyword}', meta_description = '{$meta_description}', stock_data = '{$stock_data}' WHERE entity_id = "
.(int) $productId;
try
{
/**
* Execute the query
*/
$writeConnection->query($query);
echo "successfully updated product with ID: ". $productId ."<br />";
}
catch (Exception $e)
{
echo "Could not update product with ID: ". $productId ."<br />";
}
}
}
Can anyone please help and correct me where i am wrong ?
For Deleting a product i am simply calling this function from Helper :
public function vDeleteproduct($vprod){
//print_r($vprod); exit;
try
{
$product = Mage::getSingleton('catalog/product')->load($vprod);
Mage::dispatchEvent('catalog_controller_product_delete', array('product' => $product));
$product->delete();
//$product = Mage::getModel('catalog/product')->load($vprod)->delete();
echo "successfully deleted product with ID: ". $vprod ."<br />";
}
catch (Exception $e)
{
echo "Could not delete product with ID: ". $vprod ."<br />";
}
return;
}
It too don't work :(
Plz help.
FOR DELETING PRODUCTS :
i have found the answer for this by just giving access to delete from non-admin area (i.e. frontend). And it did the magic for me.
http://inchoo.net/ecommerce/magento/programming-magento/how-to-delete-magento-product-from-frontend-template-code-from-view-files/
Above link helped me to find the solution.

Resources