November 26, 2014

Apache service Start, Stop and Restart

To start Apache server
sudo service apache2 start
           ( or )
sudo /etc/init.d/apache2 start


 To stop Apache server
sudo service apache2 stop
           (or)
sudo /etc/init.d/apache2 stop

 To restart Apache server
sudo service apache2 restart
           (or)
sudo /etc/init.d/apache2 restart

MySQL service Start, Stop and Restart

MySQL service

To start MySQL server
sudo service mysql start
           ( or )
sudo /etc/init.d/mysql start

 To stop MySQL server
sudo service mysql stop
           (or)
sudo /etc/init.d/mysql stop

 To restart MySQL server
sudo service mysql restart
           (or)
sudo /etc/init.d/mysql restart




November 25, 2014

Find the Array key in Nested Array

In nested array find the array key for matched value

function recursive_array_search($needle, $haystack) {
    foreach($haystack as $key=>$value) {
        $current_key = $key;
        if($needle === $value
  || (is_array($value) && recursive_array_search($needle,$value) !== false)) {
            return $current_key;
        }
    }
    return false;
}
 
Find the key of the matched element in nested array.

$needle
- String which has to find.

$haystack
- Array elements $needle has to search in this array.

PHP MySQL Connection

MySQLI Connection - I for Improved

Connect the database from php throug MySQLI
 
/*hostname - localhost, user - user, password - null, database - test*/

$db = new mysqli('localhost', 'user', '', 'test');

if($db->connect_errno > 0){
    die('Error in connecting database (' . $db->connect_error . ')');
}

Now doing the simple query to get records from employee table
 
/* Do Query */

$sql = "SELECT * FROM `employee`;

if(!$result = $db->query($sql)){
    die('Query error ' . $db->error);
}

Display the output by fethcing the table records
 
/* Fetching records */

while($row = $result->fetch_assoc()){
    echo $row['username'];
}

Magento Display Categories and Subcategories


Display categories and subcategories in Magento page

    /*Display current store categories*/

    $_helper = Mage::helper('catalog/category');
    $_categories = $_helper->getStoreCategories();

    /*Parent categories*/

    foreach($_categories as $_category) {

      if(!$_category->getIsActive()){
        continue;
      }

      echo $_category->getName();
      echo render_child($_category->getId());
    }
    
    /*Render child categories*/

    function render_child($cid) {
 
     $html = '';
     $_subCategory = Mage::getModel('catalog/category')->load($cid);

     $_subCategories = $_subCategory->getChildrenCategories();

     if (count($_subCategories) > 0){

       $html .= '<ul>';

       foreach($_subCategories as $_subCat){

         if(!$_subCat->getIsActive()){
           continue;
         }
    
         $html .= '<li>';
 
         /*Display first level sub categories*/

         $catUrl = Mage::helper('catalog/category')
                            ->getCategoryUrl($_subCat);

         $html .= "<a href='".$catUrl."'>".$_subCat->getName()."</a>";
  
         /*Display first level sub categories*/

         /*If needed display next level sub categories*/

         $html .= render_child($_subCat->getId()); 
  
         /*If needed display next level sub categories*/

         $html .= '</li>';
      }
   
      $html .= '</ul>';
     }  
     return $html;
  }


Displaying the category and subcategories from the current store. After getting the store categories, check the category is active and output the parent category name.

With the help of
 render_child 
function, check the active subcategories then display first level child elements in list format.

Would like to display all subcategories then call
 render_child 
function, with argument as current category id.
    

Magento List Categories and Subcategories which has Include in Navigation Menu as yes


List all categories and subcategories which has Include in Navigation Menu as yes

$collection = Mage::getResourceModel('catalog/category_collection')
    //only active categories
    ->addAttributeToFilter('is_active', 1) 
    //categories included in menu
    ->addAttributeToFilter('include_in_menu', 1) 
    ->addAttributeToSelect('*');

foreach ($collection as $category) {
    //do something with $category

     echo $category->getSku();
}

November 21, 2014

Magento Debugging Log Files

Create log file


In developing magento module its necessary to know how to log the file.
If you want to log the variables in object, array and strings.

Refer the code below to log the variable.

Mage::log($myVariable, NULL, '[nameOfFile].log');

This log file will create in magento log folder i.e [magento_root_path]/var/log

Magento Template Hints

 

Magento Template and Block Hints


In Magento Admin, look into developer option in left side bottom under System -> Configuration.

Choose the website or store you would like to see the template hints by

Enabling the template hint path and block path

This give the Block class name and corresponding template file which it displays output.

Get a Configurable Products Associated or Related Simple Product

Output the configurable related products.

/* Get all products */

$collection  = Mage::getModel ('catalog/product')
                 ->getCollection(); 

foreach($collection as $product) {
   
   /* If product is not configurable move to next item in loop */

   if($product->getTypeId() != "configurable"):
 continue;
   endif;

   /* Assign configurable related products in collection  */

   $conf = Mage::getModel('catalog/product_type_configurable')
        ->setProduct($product);


   $simpleCollection = $conf->getUsedProductCollection()
    ->addAttributeToSelect('*')    
    ->addFilterByRequiredOptions();

   /* Get all configurable related product ids */

   $simpleIds = $simpleCollection->getAllIds();

   /* Loop all related products and output the product name */

   foreach($simpleCollection as $simpleProduct){
      echo $simpleProduct->getName(). "<br/>";
   }
}

November 10, 2014

What happen when Browser Cookie will Removed, Session retains as its ?


When webpage was loaded, unique session id will generated and that stored in cookie. If cookie will removed then session cant retain.

PHP Session and Cookie


The main difference between sessions and cookies is that cookies are stored in the user's browsers, and session are stored in server.

A cookie is small file that store in user's computer. Cookie data expiry depend on expiration date where session retain until browser run.

PHP List of array sort functions

sort().

rsort().

natsort().

natcasesort().

ksort().

krsort(). 

asort().

arsort().


Use of array_map Function in Real Time ?

It will apply for many things. For example want to do php function for set of elements will use that
Example

If have like below

$first_name = trim($_POST['firstname']);


$lastname = trim($_POST['lastname']);

but instead of above

$_POST = array_map("trim", $_POST);


$array = array_map("trim", $array);


It will remove the spaces for the set of elements.



How to Add the Element to the array First & Last, how to remove the same ?


array_push - Adding elemen to the last

array_unshift - First element to prepend

array_pop - Remove the first element of the array

array_shift - Remove the last element

How to determine PHP version in Servers ?

PHPINFO gives various detail scripting running system, Apache built-in modules, PHP working directory, PHP modules, PERL information and third party system information that are used in server.

phpinfo();

Type of Magento Sessions

Core/Session:

Mage::getSingelton('core/session')

Handles information about end user ip address, messages, cookies

Customer/Session:

Mage::getSingleton('customer/session')

Handles information about the customer.

Checkout/Session:

Mage::getSingleton('checkout/session')

Handles information about the checkout, cart and details of guest account user