How to find out magento versions

To find out currently running magento version check function getVersionInfo() inside Mage.php file

For example:

 public static function getVersionInfo() { return array( 'major' => '1', 'minor' => '9', 'revision' => '2', 'patch' => '1', 'stability' => '', 'number' => '', ); }

To find out latest security patch applied check app/etc/applied.patches.list

Update Customer name and surname and customer address name and surname

<pre lang="sql">
-- Firstname --
 
SELECT * FROM  customer_entity_varchar c2
INNER JOIN customer_entity c1 ON c1.entity_id = c2.entity_id AND c2.entity_type_id = 1 AND c2.attribute_id = 
(SELECT attribute_id FROM eav_attribute WHERE attribute_code='firstname' AND entity_type_id=1)
INNER JOIN mytable m1 ON m1.magento_id = c2.entity_id AND firstname='First name' AND lastname='Last name' AND migrated=1
AND c2.VALUE='First Name';
 
 
UPDATE customer_entity_varchar c2
INNER JOIN customer_entity c1 ON c1.entity_id = c2.entity_id AND c2.entity_type_id = 1 AND c2.attribute_id = 
(SELECT attribute_id FROM eav_attribute WHERE attribute_code='firstname' AND entity_type_id=1)
INNER JOIN mytable m1 ON m1.magento_id = c2.entity_id AND firstname='First name' AND lastname='Last name' AND migrated=1
AND c2.VALUE='First Name'
SET c2.VALUE=m1.shipping_firstname;
 
SELECT * FROM  customer_address_entity_varchar c2
INNER JOIN customer_address_entity c1 ON c1.entity_id = c2.entity_id AND c2.entity_type_id = 2 AND c2.attribute_id = 
(SELECT attribute_id FROM eav_attribute WHERE attribute_code='firstname' AND entity_type_id=2)
INNER JOIN mytable m1 ON m1.magento_id = c1.parent_id AND m1.firstname='First name' AND m1.lastname='Last name' AND migrated=1
AND c2.VALUE='First Name';
 
 
UPDATE customer_address_entity_varchar c2
INNER JOIN customer_address_entity c1 ON c1.entity_id = c2.entity_id AND c2.entity_type_id = 2 AND c2.attribute_id = 
(SELECT attribute_id FROM eav_attribute WHERE attribute_code='firstname' AND entity_type_id=2)
INNER JOIN mytable m1 ON m1.magento_id = c1.parent_id AND m1.firstname='First name' AND m1.lastname='Last name' AND migrated=1
AND c2.VALUE='First Name'
SET c2.VALUE=m1.shipping_firstname;
 
-- Lastname --
 
SELECT * FROM  customer_entity_varchar c2
INNER JOIN customer_entity c1 ON c1.entity_id = c2.entity_id AND c2.entity_type_id = 1 AND c2.attribute_id = 
(SELECT attribute_id FROM eav_attribute WHERE attribute_code='lastname' AND entity_type_id=1)
INNER JOIN mytable m1 ON m1.magento_id = c2.entity_id AND firstname='First name' AND lastname='Last name' AND migrated=1
AND c2.VALUE='Last Name';
 
 
UPDATE customer_entity_varchar c2
INNER JOIN customer_entity c1 ON c1.entity_id = c2.entity_id AND c2.entity_type_id = 1 AND c2.attribute_id = 
(SELECT attribute_id FROM eav_attribute WHERE attribute_code='lastname' AND entity_type_id=1)
INNER JOIN mytable m1 ON m1.magento_id = c2.entity_id AND firstname='First name' AND lastname='Last name' AND migrated=1
AND c2.VALUE='Last Name'
SET c2.VALUE=m1.shipping_lastname;
 
 
SELECT * FROM  customer_address_entity_varchar c2
INNER JOIN customer_address_entity c1 ON c1.entity_id = c2.entity_id AND c2.entity_type_id = 2 AND c2.attribute_id = 
(SELECT attribute_id FROM eav_attribute WHERE attribute_code='lastname' AND entity_type_id=2)
INNER JOIN mytable m1 ON m1.magento_id = c1.parent_id AND m1.firstname='First name' AND m1.lastname='Last name' AND migrated=1
AND c2.VALUE='Last Name';
 
 
UPDATE customer_address_entity_varchar c2
INNER JOIN customer_address_entity c1 ON c1.entity_id = c2.entity_id AND c2.entity_type_id = 2 AND c2.attribute_id = 
(SELECT attribute_id FROM eav_attribute WHERE attribute_code='lastname' AND entity_type_id=2)
INNER JOIN mytable m1 ON m1.magento_id = c1.parent_id AND m1.firstname='First name' AND m1.lastname='Last name' AND migrated=1
AND c2.VALUE='Last Name'
SET c2.VALUE=m1.shipping_lastname;

Db set default billing and shipping address

-- start default_billing --
 
/** CREATE DEFAULT BILLING INSERTS CHUNK */
 
CREATE TEMPORARY TABLE my_default_billing_customer_entity_int
SELECT 1 AS entity_type_id,
(SELECT attribute_id FROM eav_attribute WHERE attribute_code='default_billing' AND entity_type_id=1) AS attribute_id,
my.magento_id AS entity_id, 
a1.entity_id AS VALUE
FROM mytable my 
INNER JOIN customer_entity c1 ON my.magento_id = c1.entity_id 
INNER JOIN customer_address_entity a1 ON c1.entity_id = a1.parent_id
LEFT JOIN customer_entity_int c2 ON c2.entity_id = c1.entity_id AND c2.entity_type_id = 1 AND c2.attribute_id = 
(SELECT attribute_id FROM eav_attribute WHERE attribute_code='default_billing' AND entity_type_id=1)
WHERE c2.VALUE IS NULL 
GROUP BY entity_id HAVING COUNT(a1.entity_id)=1;
 
 
/** CHECK **/
SELECT * FROM customer_entity_int a
INNER JOIN my_default_billing_customer_entity_int b ON a.entity_id = b.entity_id AND a.attribute_id= 13 AND a.entity_type_id = 1;
 
/** INSERT **/
 
INSERT INTO customer_entity_int (entity_type_id, attribute_id, entity_id, VALUE) 
SELECT * FROM my_default_billing_customer_entity_int;
 
-- end default_billing --
 
 
-- start default_shipping --
 
 
/** CREATE DEFAULT SHIPPING INSERTS CHUNK */
 
CREATE TEMPORARY TABLE my_default_shipping_customer_entity_int
SELECT 1 AS entity_type_id,
(SELECT attribute_id FROM eav_attribute WHERE attribute_code='default_shipping' AND entity_type_id=1) AS attribute_id,
my.magento_id AS entity_id, 
a1.entity_id AS VALUE
FROM mytable my 
INNER JOIN customer_entity c1 ON my.magento_id = c1.entity_id 
INNER JOIN customer_address_entity a1 ON c1.entity_id = a1.parent_id
LEFT JOIN customer_entity_int c2 ON c2.entity_id = c1.entity_id AND c2.entity_type_id = 1 AND c2.attribute_id = 
(SELECT attribute_id FROM eav_attribute WHERE attribute_code='default_shipping' AND entity_type_id=1)
WHERE c2.VALUE IS NULL 
GROUP BY entity_id HAVING COUNT(a1.entity_id)=1;
 
 
/** CHECK **/
SELECT * FROM customer_entity_int a
INNER JOIN my_default_shipping_customer_entity_int b ON a.entity_id = b.entity_id 
AND a.attribute_id = (SELECT attribute_id FROM eav_attribute WHERE attribute_code='default_shipping' AND entity_type_id=1) 
AND a.entity_type_id = 1;
 
/** INSERT **/
INSERT INTO customer_entity_int (entity_type_id, attribute_id, entity_id, VALUE) 
SELECT * FROM my_default_shipping_customer_entity_int;
 
-- end default_shipping --

Update region id in magento customer address

 
/* STEP 1 :: UPDATE ONLY ADDRESSES WHICH HAVE TURKEY AS A COUNTRY IN MAGENTO DB */
UPDATE mytable my
INNER JOIN customer_address_entity c1 ON my.magento_id = c1.parent_id
INNER JOIN customer_address_entity_varchar c3 ON c1.entity_id = c3.entity_id AND c3.entity_type_id = 2 AND c3.attribute_id = 
(SELECT attribute_id FROM eav_attribute WHERE attribute_code='country_id' AND entity_type_id=2) 
INNER JOIN customer_address_entity_int c2 ON c1.entity_id = c2.entity_id AND c2.entity_type_id = 2 AND c2.attribute_id = 
(SELECT attribute_id FROM eav_attribute WHERE attribute_code='region_id' AND entity_type_id=2)
INNER JOIN directory_country_region b ON m.shipping_region = b.code AND b.country_id = 'US'
SET my.shipping_region_id = b.region_id
WHERE c3.VALUE='US' AND my.shipping_country_id='US' AND c2.VALUE=0;
 
/* CHECK NUMBER OF RECORDS FOR STEP 2 */
SELECT * FROM customer_address_entity_int c2
INNER JOIN customer_address_entity c1 ON c2.entity_id = c1.entity_id AND c2.entity_type_id = 2 AND c2.attribute_id = 
(SELECT attribute_id FROM eav_attribute WHERE attribute_code='region_id' AND entity_type_id=2)
INNER JOIN customer_address_entity_varchar c3 ON c1.entity_id = c3.entity_id AND c3.entity_type_id = 2 AND c3.attribute_id = 
(SELECT attribute_id FROM eav_attribute WHERE attribute_code='country_id' AND entity_type_id=2) 
INNER JOIN mytable my ON my.magento_id = c1.parent_id
WHERE my.shipping_region_id > 0 AND c3.VALUE='US' AND m.shipping_country_id = 'US';
 
/* STEP 2 */
UPDATE magento01.customer_address_entity_int c2
INNER JOIN customer_address_entity c1 ON c2.entity_id = c1.entity_id AND c2.entity_type_id = 2 AND c2.attribute_id = 
(SELECT attribute_id FROM eav_attribute WHERE attribute_code='region_id' AND entity_type_id=2)
INNER JOIN customer_address_entity_varchar c3 ON c1.entity_id = c3.entity_id AND c3.entity_type_id = 2 AND c3.attribute_id = 
(SELECT attribute_id FROM eav_attribute WHERE attribute_code='country_id' AND entity_type_id=2) 
INNER JOIN mytable my ON my.magento_id = c1.parent_id
SET c2.VALUE = my.shipping_region_id 
WHERE c2.VALUE=0 AND my.shipping_region_id > 0 AND c3.VALUE='US' AND m.shipping_country_id = 'US';

Database join with group

    $limit = 1000;
    $d_collection = Mage::getResourceModel('modulename/tablename_collection')
        ->addFieldToFilter('main_table_field', true)
        ->setOrder('entity_id', 'asc')
        ->setPageSize($limit);
 
    $d_collection->getSelect()->join( array('tablename'=> Mage::getSingleton('core/resource')->getTableName('modulename/tablename')),
        'tablename.entity_id = main_table.entity_id',
        array());
    $d_collection->addFieldToFilter('tablename.table_field', 0);
    $d_collection->getSelect()->group('main_table.entity_id');
    $d_collection->addFieldToSelect('entity_id');

Adding sql script to add column to existing d b table

filename: mysql4-upgrade-1.1.1-1.1.2.php

<?php
 
$installer = $this;
$installer->startSetup();
 
$connection = $installer->getConnection();
 
$tableName = $installer->getTable('your_table_name');
$column = 'newcolumn_id';
$comment = 'Newcolumn ID';
 
if (!$connection->tableColumnExists($tableName, $column)) {
    $connection->addColumn($tableName, $column, array(
        "type" => Varien_Db_Ddl_Table::TYPE_INTEGER,
        "nullable" => true,
        "length" => 10,
        "after" => "customer_id",
        "comment" => $comment
    ));
}
 
$installer->endSetup();

Adding sql script to create database table

filename: mysql4-install-1.1.1.php

<?php
 
$installer = $this;
$installer->startSetup();
 
$tableName = $installer->getTable('your_table_name');
 
// Check if the table already exists
if ($installer->getConnection()->isTableExists($tableName) != true) {
 
    $table = $installer->getConnection()
        ->newTable($installer->getTable($tableName))
        ->addColumn('column_id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(
            'identity'  => true,
            'unsigned'  => true,
            'nullable'  => false,
            'primary'   => true,
        ), 'Email Stats Id')
        ->addColumn('customer_id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(
            'identity'  => false,
            'unsigned'  => true,
            'nullable'  => false,
        ), 'Customer Id')
        ->addColumn('timestamp', Varien_Db_Ddl_Table::TYPE_DATETIME, null,
            array(
                'nullable' => false
        ), 'Timestamp')
    ;
    $installer->getConnection()->createTable($table);
}
 
$installer->endSetup();

Magento create Creditmemo to refund online or offline

<?php
 
        $orderId ='123456789';
        $invoiceId = '1234';
 
        $data = array(
            'items' => array(
                '12345' => array('qty' => '1'),
                '12346' => array('qty' => '2')
            ),
            'comment_text' => null,
            'do_offline' => 1,
            'shipping_amount' => 0,
            'adjustment_positive' => '0',
            'adjustment_negative' => '0',
            'refund_customerbalance_return_enable' => 1,
            'refund_customerbalance_return' => 39.9
        );
 
        // load order and invoice
        $order  = Mage::getModel('sales/order')->load($orderId);
        $invoice = Mage::getModel('sales/order_invoice')
                ->load($invoiceId)
                ->setOrder($order);
 
        // if can credit memo
        if (!$order->getId() && !$order->canCreditmemo()) {
            Mage::throwException(
                $this->__('Cannot create credit memo for the order.')
            );
        }
 
        // Initialize items
        $savedData = $data['items'];
 
        $qtys = array();
        $backToStock = array();
        foreach ($savedData as $orderItemId =>$itemData) {
            if (isset($itemData['qty'])) {
                $qtys[$orderItemId] = $itemData['qty'];
            }
            if (isset($itemData['back_to_stock'])) {
                $backToStock[$orderItemId] = true;
            }
        }
        $data['qtys'] = $qtys;
 
        // Create credit memo if invoice then prepareInvoiceCreditmemo(), otherwise prepareCreditmemo()
        $service = Mage::getModel('sales/service_order', $order);
        if ($invoice) {
            $creditmemo = $service->prepareInvoiceCreditmemo($invoice, $data);
        } else {
            $creditmemo = $service->prepareCreditmemo($data);
        }
 
 
        /**
         * Process back to stock flags
         */
        foreach ($creditmemo->getAllItems() as $creditmemoItem) {
            $orderItem = $creditmemoItem->getOrderItem();
            $parentId = $orderItem->getParentItemId();
            if (isset($backToStock[$orderItem->getId()])) {
                $creditmemoItem->setBackToStock(true);
            } elseif ($orderItem->getParentItem() && isset($backToStock[$parentId]) && $backToStock[$parentId]) {
                $creditmemoItem->setBackToStock(true);
            } elseif (empty($savedData)) {
                $creditmemoItem->setBackToStock(Mage::helper('cataloginventory')->isAutoReturnEnabled());
            } else {
                $creditmemoItem->setBackToStock(false);
            }
        }
 
        // A workaround regarding refund to customer balance
        $param = Mage::app()->getRequest()->getParams();
 
        $param['creditmemo']['refund_customerbalance_return_enable'] = true;
        $param['creditmemo']['refund_customerbalance_return']        = $order->getData('base_total_paid');
 
        Mage::app()->getRequest()->setParams($param);
 
        $args = array('creditmemo' => $creditmemo, 'request' => Mage::app()->getRequest());
        Mage::dispatchEvent('adminhtml_sales_order_creditmemo_register_before', $args);
 
        if ($creditmemo) {
            if (($creditmemo->getGrandTotal() <= 0) && (!$creditmemo->getAllowZeroGrandTotal())) {
                Mage::throwException(
                    $this->__('Credit memo\'s total must be positive.')
                );
            }
 
            // Comment text if exist
            $creditmemo->addComment('our comment',false,false);
 
            // Flag for online refund
            if (isset($data['do_refund'])) {
                $creditmemo->setRefundRequested(true);
            }
 
            // Flag for offline refund
            if (isset($data['do_offline'])) {
                $creditmemo->setOfflineRequested((bool)(int)$data['do_offline']);
            }
 
            // saving creditmemo
            $creditmemo->register();
 
            // Database update
            $transactionSave = Mage::getModel('core/resource_transaction')
                ->addObject($creditmemo)
                ->addObject($creditmemo->getOrder());
            if ($creditmemo->getInvoice()) {
                $transactionSave->addObject($creditmemo->getInvoice());
            }
            $transactionSave->save();
        }

Magento get order invoice id and order items

<?php
        $orderId = '1234567890';
        $order  = Mage::getModel('sales/order')->load($orderId);
 
        if ($order->hasInvoices()) {
        $invoiceIds = $order->getInvoiceCollection()->getAllIds();
        $invoiceId = $invoiceIds[0];
        echo 'invoiceId: '.$invoiceId."\n";
        }
 
        foreach ($order->getAllItems() as $item) {
        echo $item->getId().'->'.$item->getQtyOrdered()."\n";
        }

Images media folder

Magento keeps images under media/catalog/product/ folder, full path to the file in adminhtml can be for example media/catalog/product/[1st_letter_of_filename]/[2nd_letter_of_filename]/filename.jpg
In frontend images loaded from media/catalog/product/cache/ folder, full path to cache file in frontend can be for example media/catalog/product/cache/image/*, media/catalog/product/cache/small_image/* and media/catalog/product/cache/thumbnail/*
When we do System -> Cache Management -> Flush Catalog Images Cache it deleted entire media/catalog/product/cache folder