How to find the size / rows of Magento database & tables?

February 17, 2013  |  1 Comments  |  by MagePsycho  |  Latest, Magento, Mysql

Introduction

Magento is a giant e-commerce application having more than 300 tables. It uses an eav model concept and provides different complex features which makes the database huge.

Sometimes you may wonder what’s the database size of your Magento database or individual tables so that you can work on some optimization task or freeing some of your server space.
Here we are going to discuss some SQL queries which seems to be helpful.

SQL Snippets

1. Find size & rows of Magento database

SELECT
  TABLE_SCHEMA AS "Database",
  SUM(TABLE_ROWS) AS "Rows #",
  ROUND(
    SUM(DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024,
    2
  ) AS "Size (MB)"
FROM
  information_schema.TABLES
WHERE information_schema.TABLES.TABLE_SCHEMA = 'database-name'
 GROUP BY TABLE_SCHEMA;

2. Find size & rows of Magento database tables

SELECT
  TABLE_NAME AS "Table",
  TABLE_ROWS AS "Rows #",
  ROUND(
    (DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024,
    2
  ) AS "Size (MB)"
FROM
  information_schema.TABLES
WHERE information_schema.TABLES.TABLE_SCHEMA = 'database-name'

3. Find size & rows of Magento log tables

SELECT
  TABLE_NAME AS "Table",
  TABLE_ROWS AS "Rows #",
  ROUND(
    (DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024,
    2
  ) AS "Size (MB)"
FROM
  information_schema.TABLES
WHERE information_schema.TABLES.TABLE_SCHEMA = 'database-name'
  AND (
    TABLE_NAME LIKE 'log_%'
    OR TABLE_NAME LIKE 'report_%'
    OR TABLE_NAME LIKE 'dataflow_%'
    OR TABLE_NAME = 'catalog_compare_item'
  )
ORDER BY TABLE_ROWS DESC

Magento log tables info

These queries can be useful for optimizing your database. Suppose say if log tables are huge with large no of data then you can optimize the log tables by truncating them using following SQL:

TRUNCATE dataflow_batch_export;
TRUNCATE dataflow_batch_import;
TRUNCATE log_customer;
TRUNCATE log_quote;
TRUNCATE log_summary;
TRUNCATE log_summary_type;
TRUNCATE log_url;
TRUNCATE log_url_info;
TRUNCATE log_visitor;
TRUNCATE log_visitor_info;
TRUNCATE log_visitor_online;
TRUNCATE report_viewed_product_index;
TRUNCATE report_compared_product_index;
TRUNCATE report_event;
TRUNCATE index_event;
TRUNCATE catalog_compare_item;

Caution: Always take a DB backup before performing truncate operation.

Hope you found this article useful.
Thanks for reading!

How to filter payment method in onepage checkout

January 9, 2013  |  3 Comments  |  by MagePsycho  |  Latest, Magento

Introduction

Q: How will you filter the payment method in onepage checkout based on some conditions?
A: There are different ways to do so. Some of them are:
#1 By overriding template: app/design/frontend/[interface]/[theme]/template/checkout/onepage/payment/methods.phtml
#2 By overriding method: Mage_Checkout_Block_Onepage_Payment_Methods::_canUseMethod()
#3 By observing event: payment_method_is_active
#4 etc.

Among above methods obviously using event-observer technique is the best way to go (#2).
And here I will be discussing about how to enable the PayPal (Website Standard) method only when current currency is USD.

Steps

Suppose a skeleton module(MagePsycho_Paymentfilter) has already been created.
1> Register the event: ‘payment_method_is_active’ in config.xml.
Add the following xml code in app/code/local/MagePsycho/Paymentfilter/etc/config.xml:

...
<frontend>
	...
	<events>
		<payment_method_is_active>
			<observers>
				<paymentfilter_payment_method_is_active>
					<type>singleton</type>
					<class>paymentfilter/observer</class>
					<method>paymentMethodIsActive</method>
				</paymentfilter_payment_method_is_active>
			</observers>
		</payment_method_is_active>
	</events>
	...
</frontend>
...

2> Implement the observer model
Create observer file: app/code/local/MagePsycho/Paymentfilter/Model/Observer.php and paste the following code:

<?php
/**
 * @category   MagePsycho
 * @package    MagePsycho_Paymentfilter
 * @author     magepsycho@gmail.com
 * @website    http://www.magepsycho.com
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 	*/
class MagePsycho_Paymentfilter_Model_Observer {

	public function paymentMethodIsActive(Varien_Event_Observer $observer) {
		$event			 = $observer->getEvent();
		$method			 = $event->getMethodInstance();
		$result			 = $event->getResult();
		$currencyCode	 = Mage::app()->getStore()->getCurrentCurrencyCode();

		if( $currencyCode == 'USD'){
			if($method->getCode() == 'paypal_standard' ){
				$result->isAvailable = true;
			}else{
				$result->isAvailable = false;
			}
		}
	}

}

3> Go ahead for testing.

Happy E-Commerce!

Using Netbeans macros to speed up Magento templating

December 8, 2012  |  No Comments  |  by MagePsycho  |  Latest, Magento

Introduction

Netbeans is my favorite IDE for PHP/Magento development. And one of the great feature provided by Netbeans is Macros

Here I will share some tips on how to leverage the power of Macros for Magento templating.

Importing Macros

1. Download the Macros zip file from [here]
2. Open Netbeans IDE. Go to menu:
Tools > Options > Editor > Macros > press ‘Import’ button located at the bottom > Locate the zip file downloaded from above > Check all checkboxes > press ‘OK’ > restart application
3. That’s all
[Related Snapshots]

Import Macros - Step 1


Import Macros - Step 2

Netbeans Macros

Using Macros

After importing Macros in Netbeans, you can use it for following cases:
1. Text/Label Translation:
When you are using label/text in template(.phtml) files, it is always recommended to wrap up label/text string as:

<?php echo $this->__('Label or Text goes here...') ?>

in order to make it multi-lingual friendly.

In order to use Macro for this case:
Select the label/text which you want to translate and press: [Alt] + T.
This shortcut will auto prepend: <?php echo $this->__(‘ and append: ‘) ?> code for you and hence reducing the no of codes. Isn’t that cool?

2. Output PHP Variables:
In order to output variable in template file, you need to add php opening & closing tags which makes a simple echo code a bit lengthier. For example:

<?php echo $someVariable ?>

In order to use Macro for this case:
Select the variable which you want to echo and press: [Alt] + E.
It will auto prepend: <?php echo and append: ?> code for you.

3. Commenting div blocks:
When you want to remove the unwanted html divs from template files, it is better to use php block comment (<?php /* … */ ?>) instead of html comment(<!– … –>)

In order to use Macro for this case:
Select the div block which you want to comment and press: [Alt] + C.
It will auto prepend: <?php /* and append: */ ?> and hence div block content will be commented out.

Notes: You can edit the shortcut by going to: Tools > Options > Editor > Macros > Select Macro > click ‘Set Shortcut’

These were some Tips & Tricks on using Netbeans Macros effectively in order to reduce the amount of code and making your Magento templating life bit easier.
I request my beloved readers to share their favorite Macros which can help others to automate the coding to some extent.

Thanks for reading & sharing!

Creating fancy FAQ page in Magento – an easier approach

November 11, 2012  |  5 Comments  |  by MagePsycho  |  Latest, Magento

Introduction

Just keep reading this tutorial which will teach how to create a fancy FAQ with expandable/collapsible feature in an easier approach.

In short, creating a fancy FAQ section can be easily achieved in Magento by using CMS page & jQuery.

Steps

Go to Admin > CMS Pages > Add New Page and implement the following steps:
1. Add FAQ contents
Add the following content in the ‘Content’ > ‘Content’ section of CMS page:

<div class="expand_wrapper">
	<h2 class="expand_heading"><a href="#">1. WordPress Theme Development</a></h2>
	<div class="toggle_container">
		<div class="box">
			<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
		</div>
	</div>
	<h2 class="expand_heading"><a href="#">2. Magento E-commerce</a></h2>
	<div class="toggle_container">
		<div class="box">
			<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
			<p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
		</div>
	</div>
	<h2 class="expand_heading"><a href="#">3. Website Development</a></h2>
	<div class="toggle_container">
		<div class="box">
			<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
			<p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
		</div>
	</div>
	<h2 class="expand_heading"><a href="#">4. PHP MySql Development</a></h2>
	<div class="toggle_container">
		<div class="box">
			<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
			<p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
		</div>
	</div>
</div>

2. Inject jQuery code
Add the following xml code in ‘Design’ > ‘Layout Update XML’ field of CMS page:

<reference name="head">
	<block type="core/text" name="google.cdn.jquery">
		<action method="setText">
			<text><![CDATA[
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">jQuery.noConflict();</script>
<script type="text/javascript">
	jQuery(document).ready(function(){
		jQuery(".toggle_container").slice(1).hide();//expands first FAQ content
		jQuery(".expand_heading:first").addClass("active");//add active class to first FAQ title
		jQuery("h2.expand_heading").click(function(event){
			event.preventDefault()
			jQuery(this).toggleClass("active");
			jQuery(this).next(".toggle_container").slideToggle("slow");
		});
	});
</script>

			]]></text>
		</action>
	</block>
</reference>

3. You’re done
Go to the frontend and open the FAQ page, you will see as:

FAQ Page With Expand/Collapse

Happy E-Commerce!

How to convert an array to a collection object in magento?

November 6, 2012  |  2 Comments  |  by MagePsycho  |  Latest, Magento

Scenario

Suppose say we have an array of data fetched from database.
And we want to merge it with Magento collection object or want to provide the data as collection object to the view(template) file.

Solution

<?php
$resource		= Mage::getModel('core/resource');
$connection		= $resource->getConnection('core_read');
$sql			= "SELECT * FROM custom_table WHERE some_field = ?";
$rows			= $connection->fetchAll($sql, array($someFieldValue));//this row will return an array

$collection = new Varien_Db_Collection();
foreach($rows as $row){
	$rowObj = new Varien_Object();
	$rowObj->setData($row);
	$collection->addItem($rowObj);
}

//now you can get the data using collection way
foreach($collection as $_data){
	print_r($_data->getData());
}

Notes:
In order to create a collection object
1> Create an instance of Varien_Db_Collection

$collection = new Varien_Db_Collection();

2> Create an instance of Varien_Object and set the array of data

$rowObj = new Varien_Object();
$rowObj->setData($row);

3> Finally add the Varien_Object to Collection instance

$collection->addItem($rowObj);

Now you can play with the magic getters and setters of collection class.

In order to have depth knowledge on Magento Collection you can refer to the Alan Storm’s article:
Varien Data Collections