Top selling product collection programmatically in magento

Top selling products :

Here is way to get best selling product collection.

<?php 
/* Best Seller*/

$visibility = array(
Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG
);

$storeId = Mage::app()->getStore()->getId(); // get default store id

$_productCollection = Mage::getResourceModel('reports/product_collection')
     ->addAttributeToSelect('*')
     ->addOrderedQty()
     ->addAttributeToFilter('visibility', $visibility)
     ->setOrder('ordered_qty', 'desc');

 print_r($_productCollection);
?>

Product price update globally in magento using direct sql query

Update product price globally
<?php

$priceToAdd = 10; // custom product price

$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$write->query("
  UPDATE catalog_product_entity_decimal val
  SET  val.value = (val.value + $priceToAdd)
  WHERE  val.attribute_id = (
     SELECT attribute_id FROM eav_attribute eav
     WHERE eav.entity_type_id = 4 
       AND eav.attribute_code = 'price'
    )
");

// where eav.entity_type_id=4 is default attribute id

 

Update all prices from a certain store

This technique is useful when working in a multi-store Magento environment.

<?php

$priceToAdd = 6;
$storeId = 4;

$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$write->query("
  UPDATE catalog_product_entity_decimal val
  SET  val.value = (val.value + $priceToAdd)
  WHERE  val.attribute_id = (
     SELECT attribute_id FROM eav_attribute eav
     WHERE eav.entity_type_id = 4 
       AND eav.attribute_code = 'price'
    )
    AND val.store_id = $storeId
");

 

Update all product prices with a certain attribute set
<?php

$customPriceToAdd = 10;
$attributeSetId = 4;

$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$write->query("
  UPDATE catalog_product_entity_decimal val
  SET  val.value = (val.value + $customPriceToAdd)
  WHERE  val.attribute_id = (
     SELECT attribute_id FROM eav_attribute eav
     WHERE eav.entity_type_id = 4 
       AND eav.attribute_code = 'price'
    )
AND entity_id = ( 
   SELECT p.entity_id FROM catalog_product_entity p
   WHERE p.attribute_set_id = $attributeSetId
)
");

 

Update the Special Price
<?php

$custompriceToAdd = 10;

$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$write->query("
  UPDATE catalog_product_entity_decimal val
  SET  val.value = (val.value + $custompriceToAdd)
  WHERE  val.attribute_id = (
     SELECT attribute_id FROM eav_attribute eav
     WHERE eav.entity_type_id = 4 
       AND eav.attribute_code = 'special_price'
    )
");

 

Direct SQL Queries In Magento

Magento uses data models which provide a great way to access and modify data. By using competently named methods and clever abstraction, Varien hide away the complex SQL needed to perform data operations. While this makes learning models easier, it often impacts the speed of the operation and so the responsiveness of your website. This is true when saving models that use the EAV architecture.

Mostly, this cannot be avoided, however there are some situations where executing direct SQL queries would be simpler and much quicker leading to a more optimised Magento installation.

Example : Product price update globally in magento.

 

Database Connections In Magento

Magento will automatically connect to it’s database and provide two separate resources which you can use to access data: core_read and core_write.

<?php 
/** 
* Get the resource model 
*/ 

$resource = Mage::getSingleton('core/resource'); 

/** 
* Retrieve the read connection 
*/ 

$readConnection = $resource->getConnection('core_read');
	
/**
* Retrieve the write connection
*/
$writeConnection = $resource->getConnection('core_write');

?>

 

Table names and prefixes

A table prefix is a string of characters that is added to the start of every table name in your database. These are useful to installing multiple system into one database. It helps to distinguish each application’s data.

Magento has a simple built in function which allows you to add the prefix to a given table name.

Get a table name from a string
<?php

/**
* Get the resource model
*/

$resource = Mage::getSingleton('core/resource');
	
/**
* Get the table name
*/

$tableName = $resource->getTableName('catalog_product_entity');
	
/**
* if prefix was 'mage_' then the below statement
* would print out mage_catalog_product_entity
*/

echo $tableName;

?>

 

Get a table name from a string
<?php

/**
* Get the resource model
*/

$resource = Mage::getSingleton('core/resource');
	
/**
* Get the table name
*/

$tableName = $resource->getTableName('catalog/product');
	
/**
* if prefix was 'mage_' then the below statement
* would print out mage_catalog_product_entity
*/

echo $tableName;
?>

 

Reading From The Database

It would be much quicker to run a single query to obtain this value than to load in a whole product model .

Varien_Db_Select::fetchAll

This method takes a query as it’s parameter, executes it and then returns all of the results as an array.

<?php
	
/**
* Get the resource model
*/

$resource = Mage::getSingleton('core/resource');
	
/**
* Retrieve the read connection
*/

$readConnection = $resource->getConnection('core_read');
	
$query = 'SELECT * FROM ' . $resource->getTableName('catalog/product');
	
/**
* Execute the query and store the results in $results
*/

$results = $readConnection->fetchAll($query);
	
/**
* Print out the results
*/

var_dump($results);

 

Varien_Db_Select::fetchCol

This method is similar to fetchAll except that instead of returning all of the results, it returns the first column from each result row.

<?php
/**
* Get the resource model
*/

$resource = Mage::getSingleton('core/resource');
	
/**
* Retrieve the read connection
*/

$readConnection = $resource->getConnection('core_read');
	
/**
* Retrieve our table name
*/

$table = $resource->getTableName('catalog/product');

/**
* Execute the query and store the results in $results
*/

$sku = $readConnection->fetchCol('SELECT sku FROM ' . $table . ');
	
/**
* Print out the results
*/

var_dump($results);

 

Varien_Db_Select::fetchOne

Varien_Db_Select::fetchOne returns one value from the first row only.

<?php

/**
* Get the resource model
*/

$resource = Mage::getSingleton('core/resource');
	
/**
* Retrieve the read connection
*/

$readConnection = $resource->getConnection('core_read');

/**
* Retrieve our table name
*/

$table = $resource->getTableName('catalog/product');
	
/**
* Set the product ID
*/

$productId = 44;
	
$query = 'SELECT sku FROM ' . $table . ' WHERE entity_id = '. (int)$productId . ' LIMIT 1';
	
/**
* Execute the query and store the result in $sku
*/

$sku = $readConnection->fetchOne($query);
	
/**
* Print the SKU to the screen
*/

echo 'SKU: ' . $sku . '<br/>';

 

Writing To The Database

<?php

/**
* 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 = 44;
	
/**
* 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';
	
$query = "UPDATE {$table} SET sku = '{$sku}' WHERE entity_id = ". (int)$productId;
	
/**
* Execute the query
*/

$writeConnection->query($query);

10 ways to Improve Magento Performance or speed

Performance or speed is one of the key of most success of ecommerce store. High performance websites got more preference in search engine in comparison to slow loading website. Also if your ecommerce is fast or quick loading then it provides better experience to your website user, which means more conversion. If your website is built in Magento and you are experiencing the slow loading then you are at right place. In this article we will discuss some basic practices to improve magento performance.

1. Combine all JavaScript in single file and all CSS in single file

By following below steps you can merge your css and JS

  1. Please go to System -> Configuration
  2. Click on Developer tab from left section. It would be in the bottom of the page.
  3. Click on Developer tab from left section. It would be in the bottom of the page.

Screeshot :

css-js-merge

 

2 Use of Caching

Caching is one of the most preferred way to improve performance or speed in any software system. Use of caching is important to improve magento speed.

There must be rule of thumb to use opcode cache. I prefer to use APC for opcode caching. Opcode caching will increase speed of the code execution which will help to load your eCommerce pages faster.

Magento also caches some of variables and other things and developed its own cache system. By the magento cache values getting stored in file. File based caching are little slower. Use memcache or other in memory caching system.

 

3. Use Full Page Cache Feature

Magento provides facility to cache whole page which improves the store speed very considerably. You can enable full page caching by following below steps:

  1. Please go to System -> Configuration.
  2. From Left Navigation please click on System (Under Advanced section)
  3. Open External Full Page Cache Setting and select Yes to Enable external cache setting

Screeenshot :

img2

 

4. Use Content Delivery Network(CDN)

In ecommerce the biggest thing is user experience. If user experince will not be up to mark then your ecomm store performance in terms of conversion will always go down. To provide better experience you need to add better info graphics of your products. More infographics means more images, which again lead to slow your user experience. You can optimise user experience by delivering your images, js and css through CDN. CDN will serve your static files faster then your web server. To know more detail on how cdn works you can refer CDN Wiki Page.

5. Always be updated to upgrade your magento

Keep upgrading your magento to most updated version.  Also by updating magento chances of security attack on your store goes down. So upgrading magento to the lated version is always a good Idea.

Do the same things for the extensions and themes. Always keep your cheap football kits magento extension and theme on most updated version

6. Disable Unused Modules

  1. Please go to System -> Configuration
  2. Go to Advanced section from left navigation from configuration page.
  3. Open Disable module output section and select module to disable.

Screenshot :

img3

 

7.  Use Magento Compilation

Magento compilation process Cheap Manchester United football shirts makes class loading much more faster. Make sure to run this compiliation in non production hour of your website because it might take good amount of time to complete the process

Magento compilation process is given below :

  1. Please go to System -> Tools -> Compilation
  2. Click on Run Compilation Process button.

8. Disable Cheap Real Madrid football shirts Unwanted Logs

Logs are always good but always eat performance. So only required things should be log. If not requied always disable the exception and system log. It will always save lots of disk writing operation which will improve your magento store speed.

9. Enable the Flat Catalog

Enable the Flat Catalog module for products and categories in the Magento Admin Panel. We have seen quite significant improvements by turning on this feature, especially on large catalogs

10. Clean database log

Many Magento store keep unnecessary Cheap AC Milan football shirts data but it is not a wise choice because keeping that huge database makes your Magento store run slowly and less effectively. That’s why we need Clean database log. This way is not only easy but it also time saving. It takes Cheap England football shirts no more than 30 minutes to speed up Magento store

Run following code in database query box :

TRUNCATE `log_customer`;
TRUNCATE `log_query`;
TRUNCATE `log_summery`;
TRUNCATE `log_summery_type`;
TRUNCATE `log_url`;
TRUNCATE `log_url_info`;
TRUNCATE `log_visitor`;
TRUNCATE `log_visitor_info`;
TRUNCATE `log_visitor_online`;

Magento Custom Module Development

Throughout the Post, We’ll refer Magento Community Edition 1.9, though custom module structures are the same in all versions of Magento. Let’s quickly understand the basic structure of Magento.

Whenever you install a fresh Magento, you will notice the following Magento directory structure:

 mage_frsh_install_directory_struct

 

 

 

 

 

Magento MVC architecture

There is main entry point – index.php – from where the whole app will be initialized. Base on the requested URL appropriate controller will be called. Controller defines the pages and load the layout files for those pages. Layout files tells the controllers which block files to use. Block files collect the data from models and helpers files and pass it to templates files. Templates files receive data and render html.

Initially, this may be difficult to understand since it contains a few extra layers. To get more familiar with the flow of control, let’s develop a custom “Hello World” module.
Before Starting With Modules

I am assuming that you already have a working copy of Magento with version 1.9, Disable the cache. To Disable the cache Go to Magento Admin Panel > System > Cache Management > Select all cache type from left side checkboxes > Select Action: disable from right top drop down > click Submit.

The Structure of a Magento Module
Code Pools

Magento contains three type of code pools where the all custom and core modules of Magento are resides.

Core pools contain all the core modules which are by default comes with a Magento installation. These modules are written by Magento developers. It’s recommended not to modify these modules because whenever you will upgrade your Magento installation, all the core modules will be overwritten and your modifications will be lost.
Community pools contain all the modules – that is, custom modules – that are developed by third-party programmers to be installed through Magento Connect. These modules generally extend core modules and offer their own functionality that can often be used anywhere in Magento.
Local pools contain all the custom module that are going to be used for a particular project but are not readled in Magento Connect

Thus, we have two choice of pools: Community or Local. Since we are working on our own project, we are going to use a local pool, though there’s no restriction on using the community pool, either.

Structure

Magento modules consist of the following components:

Blocks contain functions that are used to display data in templates.
Models contain the business logic of modules.
Resource Models contains functions that are used for database interaction.
Controllers defines page layout and blocks files and are loaded when a URL is requested.
etc contains configuration files in XML formats which tells Magento how many files modules have and how the module interacts.
Helpers contain functions that are used for defining common business logic (such as image resize, validation). These functions can used anywhere across the Magento application
sql contains SQL scripts to create, modify, or delete SQL tables.

Module Naming

We need to give a name to our module. Generally, Magento module names are made of two parts: <Namespace>_<Module>. The best practice to give a Magento module a name is choose as an author or a company name and <Module> as a actual module name.

Based on these naming convention, I am giving our module the A2bizz_Mymodule name. We will reference this name throughout this series.

Code Set Up and Configuration

Lets create the directories base on above structure. Go to your Magento installation direction then navigate to app/code/local and create the directories as shown below.

Next, we will configure and activate our module by creating config file A2bizz_Mymodule.xml in the app/etc/modules directory. This directory contains config files for all modules.

<?xml version="1.0"?>
<config>
    <modules>
        <A2bizz_Mymodule>
        <active>true</active>
        <codePool>local</codePool>
        </A2bizz_Mymodule>
    </modules>
</config>

This file will tell Magento about the location of our module. In the active tag, we have specified true to enable our module. If everything is correct thus far, then you will find your module in the Magento Admin Panel > System > Configuration > Advanced > Advanced > Disable Modules Output list. From here you can enable and disable your module.
Getting Started: Development

Next we will create our module configuration file. This file will tell Magento all about our module. This includes how many files our module contains, what type of files (models, helpers, database classes), and so on.

Go to app/code/local/A2bizz/Mymodule/etc and create a config.xml file that will contain following content

<?xml version="1.0"?>
<config
    <modules>
        <A2bizz_Mymodule>
            <version>0.1.0    <!-- Version number of your module -->
        </A2bizz_Mymodule>
    </modules>
    <frontend>
        <routers>
            <mymodule>
                <use>standard</use>
                <args>
                    <module>A2bizz_Mymodule</module>
                    <frontName>mymodule</frontName>
                </args>
            </mymodule>
        </routers>
    </frontend>
</config>

Let’s go through line by line to understand each tag. Here, the first tag is that contains the name and version of our module. The version number is very important when it comes to updating your module update your module.

The tag will tell Magento about the controller dispatched. Inside the tag, we have defined that tells Magento how to access our controllers via the routing mechanism.

In the tag, we have defined module name in tag and frontend name in . By using a frontend name, we can access our module in frontend like yoursitename.com/index.php/mymodule/index.

By calling yoursitename.com/index.php/mymodule or yoursitename.com/index.php/mymodule/index Magento will look for index action of your module’s controller file. As such, we need to create our controller file.

Go to app/code/local/A2bizz/Mymodule/controllers and create file IndexController.php with following content.

Note that each file’s name and class names are case sensitive in Magento It’s very important that you are taking care in naming your work when creating files and classes.

<?php
class A2bizz_Mymodule_IndexController extends Mage_Core_Controller_Front_Action
{
    public function indexAction()
    {
        echo "Hello A2bizz";
    }
}

Now open URL yoursite.com/index.php/mymodule/index it will print “Hello A2bizz”. Awesome – we’re finally done with our first hello world module.
Controller Dispatch

Here we have extend the class Mage_Core_Controller_Front_Action that contains all the methods which are using in routing of url. The Magento class name reflects the location of class file. So the class Mage_Core_Controller_Front_Action resides in location Mage > Core > Controller > Front > Action.php

See the class name of our controller that is A2bizz_Mymodule_IndexController. Magento controller to be named in such a way that it reflects (tag)_(Action Controllername)(keyword Controller).

<module>tag = A2bizz_Mymodule (we have defined this tag in config.xml)
    Action Controllername = Index
    Action controller followed by the Controller keyword

Based on this pattern, the name of our controller is A2bizz_Mymodule_IndexController

Now see the URL pattern which is follow the below route pattern
yoursite.com/index.php/frontendname/actionControllername/actionmethod

 frontendname = mymodule
 actionControllername = Index
 actionmethodname = Index

Based on this URL pattern, our module’s URL is yoursite.com/index.php/mymodule/index/index. You can also access it using yoursite.com/index.php/mymodule because whenever you have not specified an actionController or actionmethod name, Magento loads the index controller and index action by default.

Now let’s create one more action: testAction .

<?php
class A2bizz_Mymodule_IndexController extends Mage_Core_Controller_Front_Action
{
    public function indexAction()
    {
        echo "Hello A2bizz";
    }
    public function testAction()
    {
        echo "test action";
    }
}

We can access the testAction using URL yoursite.com/index.php/mymodule/index/test. As explained earlier here

 frontendname = mymodule
 actionControllername = Index
 actionmethodname = test

This is how the controller works in Magento.

At first, it can be difficult to understand everything at once so We’ve included all of the source code to this module so that you can review it and implement your own work while using it as a guide.

Magento API, use in Android, Iphone, Windows Phone

There are two types of API to use in Magento –

* SOAP
* REST

SOAP

The Magento SOAP API provides ability to manage eCommerce stores by providing calls for working with resources such as customers, categories, products, and sales orders. It also allows to manage shopping carts and inventory.

http://yourmagentohost/api/?wsdl
http://yourmagentohost/api/soap/?wsdl

where yourmagentohost is the domain for your Magento host.

The following PHP example shows you how to make SOAP calls to the Magento API:

$client = new SoapClient('http://yourmagentohost/soap/api/?wsdl');

// If somestuff requires api authentification,
// then get a session token
$session = $client->login('apiUserName', 'apiKey');

$result = $client->call($session, 'stuff.method');
$result = $client->call($session, 'stuff.method', 'arg1');
$result = $client->call($session, 'stuff.method', array('arg1', 'arg2', 'arg3'));
$result = $client->multiCall($session, array(
     array('stuff.method'),
     array('stuff.method', 'arg1'),
     array('stuff.method', array('arg1', 'arg2'))
));


// If you don't need the session anymore
$client->endSession($session);

Magento : Base Url , Skin Url , Media Url , Js Url , Store Url and Current Url

1. Get Base Url :

Mage::getBaseUrl();

2. Get Skin Url :

Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN);

(a) Unsecure Skin Url :

$this->getSkinUrl('images/imagename.jpg');

(b) Secure Skin Url :

$this->getSkinUrl('images/imagename.gif', array('_secure'=>true));

3. Get Media Url :

Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);

4. Get Js Url :

Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS);

5. Get Store Url :

Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);

6. Get Current Url

Mage::helper('core/url')->getCurrentUrl();

Get Url in cms pages or static blocks

1. Get Base Url :

{{store url=""}}

2. Get Skin Url :

{{skin url='images/imagename.jpg'}}

3. Get Media Url :

{{media url='/imagename.jpg'}}

4. Get Store Url :

{{store url='mypage.html'}}
cheap Barcelona football shirts  |
cheap Real Madrid football shirts  |
cheap Manchester United football shirts  |
cheap England football shirts  |
cheap AC Milan football shirts  |
cheap Inter Milan football shirts  |
cheap Liverpool footbal lshirts  |
cheap France football shirts  |
cheap Juventus football shirts  |
cheap Celtic football shirts  |
cheap Celtic football shirts  |
cheap Italy football shirts  |
cheap Inter Milan football shirts  |
cheap Barcelona football shirts  |
cheap Chelsea football kits  |
cheap Arsenal football kits  |
cheap Liverpool football shirts  |
cheap Real Madrid football shirts  |
cheap Portugal football shirts  |
cheap Belgium football shirts  |
cheap Barcelona football shirts  |
cheap France football shirts  |
cheap Germany football shirts  |
cheap North Ireland football shirts  |
cheap Juventus football shirts  |
cheap AC Milan football shirts  |
cheap Manchester United football shirts  |
cheap Italy football shirts  |
cheap Manchester United football shirts  |
cheap Real Madrid football shirts  |
cheap Real Madrid football shirts  |
cheap Chelsea football shirts  |
cheap Germany football shirts  |