Active Menu

Active Menu

Java Script

<script>
function selected(obj){
var lilist = document.getElementById(‘menu’);
var alist = lilist.getElementsByTagName(‘a’);
for (i=0; i<alist.length; i++ )
{
alist[i].className=””;
}
obj.className=”red”;
}
</script>

Style
<style>
.red {
color:red;
background:#F39;
width:150px;
}

HTML
<ul id=”menu”>
<li><a href=”#” onClick=”selected(this)”>Home</a></li>
<li><a href=”#”  onClick=”selected(this)”>About Us</a></li>
<li><a href=”#”  onClick=”selected(this)”>Our Products</a></li>
<li><a href=”#” onClick=”selected(this)”>Trade Offers</a></li>
<li><a href=”#”  onClick=”selected(this)”>Contact Us</a></li>
</ul>

How to change shipping rate in Percent

How to change shipping rate in Percent

app/code/core/Mage/Shipping/Model/Carrier/Flatrate.php

find line

$method->setPrice($shippingPrice);

and put following code above that line

 

   $session        = Mage::getSingleton(‘checkout/session’);

            $quote_id       = $session->getQuoteId();

            $item_quote     = Mage::getModel(‘sales/quote’)->load($quote_id);

            $shippingPrice  = $item_quote->getSubtotal()*($this->getConfigData(‘price’)/100);

 

To Show Custom Option , configuration option , quantity in list page.

To Show Custom Option , configuration option , quantity in list page.

Put the code in place of where add to cart is now:

<?php echo $this->helper(‘checkout’)->formatPrice($_product->getFinalPrice()) ?>
<form action=”<?php echo Mage::getBaseUrl(); ?>checkout/cart/add/” method=”post” style=”display:block; clear:both;”>

<?php

$product = Mage::getModel(‘catalog/product’);
$product->load($_product->getId());

//print_r($product);
//exit();

$xml = “”;
$hasAtts = 0;

// configurable products
$productType = $product->getTypeId();

if($productType == “configurable”) {

// configurable products
$attValConfig = $product->getTypeInstance()->getConfigurableAttributesAsArray();

if(sizeof($attValConfig)) {

$hasAtts++;

foreach($attValConfig as $attValConfigSingle) {

$xml .= “<div class=’floatoption1′>”.$attValConfigSingle[‘frontend_label’].”: “;

$xml .= “<select style=’display:block; clear:both; margin-bottom:10px;’ name=’super_attribute[“.$attValConfigSingle[‘attribute_id’].”]’><option selected=’selected’>Choose an option</option>”;

foreach($attValConfigSingle[‘values’] as $attValConfigSingleVal) {

$baseprice = $this->getPriceHtml($product, true);
$strippedprice = str_replace(“£”, “”, $baseprice);
$numprice = strip_tags($strippedprice);
$numpricea = (float)$numprice;
$optionprice = $attValConfigSingleVal[‘pricing_value’];
$numpriceb = (float)$optionprice;
$catprice = $numpricea + $numpriceb;
$catpricea = number_format($catprice,2);

if (is_numeric($numpriceb)) {
$xml .= “<option value='”.$attValConfigSingleVal[‘value_index’].”‘>”.$attValConfigSingleVal[‘label’].” £”.$catpricea.”</option>”;
}   else { $xml .= “<option value='”.$attValConfigSingleVal[‘value_index’].”‘>Not Mumeric</option>”; }
}
$xml .= “</select></div>”;

}

}

}
// end configurable products

$attVal = $product->getOptions();

if(sizeof($attVal)) {

$hasAtts++;

foreach($attVal as $optionVal) {

$xml .= “<div class=’floatoption1′>Size:<select style=’display:block; clear:both; margin-bottom:10px;’ name=’options[“.$optionVal->getId().”]’><option selected=’selected’>Choose an option</option>”;

foreach($optionVal->getValues() as $valuesKey => $valuesVal) {
$xml .= “<option value='”.$valuesVal->getId().”‘>”.$valuesVal->getTitle().” +”.Mage::helper(‘core’)->currency($valuesVal->getPrice()).”</option>”;
}

$xml .= “</select></div>”;

}

}

$xml .= “<div class=’floatoption2′>Qty: <input style=’display:block; clear:both; margin-bottom:20px;’ id=’qty’ class=’input-text qty’ type=’text’ value=’1′ maxlength=’12’ name=’qty’/></div>”;

echo($xml);

?>

<input type=”hidden” name=”product” value=”<?php echo($_product->getId()); ?>” />
<div>
<button type=”submit”><span><span><?php echo $this->__(‘Add to Cart’) ?></span></span></button></div>

</form>
<script type=”text/javascript”>
var productAddToCartForm_<?php echo $_product->getId(); ?> = new VarienForm(‘product_addtocart_form_<?php echo $_product->getId(); ?>’);
productAddToCartForm_<?php echo $_product->getId(); ?>.submit = function(){
if (this.validator.validate()) {
this.form.submit();
}
}.bind(productAddToCartForm_<?php echo $_product->getId(); ?>);
</script>

Making default of product attributes like is_active,tax class, weight,status,stock,qty in magento

UPDATE `eav_attribute` SET `default_value` = ‘container1′ WHERE `eav_attribute`.`attribute_code`=’options_container’;
UPDATE `eav_attribute` SET `default_value` = ‘1’ WHERE `eav_attribute`.`attribute_code`=’is_active’;
UPDATE `eav_attribute` SET `default_value` = ‘1’ WHERE `eav_attribute`.`attribute_code`=’is_anchor’;
UPDATE `eav_attribute` SET `default_value` = ‘1’ WHERE `eav_attribute`.`attribute_code`=’status’;
UPDATE `eav_attribute` SET `default_value` = ‘0’ WHERE `eav_attribute`.`attribute_code`=’weight’;
UPDATE `eav_attribute` SET `default_value` = ‘2’ WHERE `eav_attribute`.`attribute_code`=’tax_class_id’;
insert into core_config_data values ( null, ‘default’, 0, ‘cataloginventory/item_options/is_in_stock’, 1 );
insert into core_config_data values ( null, ‘default’, 0, ‘cataloginventory/item_options/qty’, 10 );
Pre-populate the incremented new SKU to the SKU field by JavaScript.

How To Get Special Price in magento Product

How To Get Special Price in magento Product

<?php
Mage::app();
Mage::getSingleton(‘core/session’, array(
‘name’ => ‘frontend’
));
$_productCollection = Mage::getResourceModel(‘catalogsearch/advanced_collection’)-> addAttributeToSelect(Mage::getSingleton(‘catalog/config’)-> getProductAttributes())->addMinimalPrice()->setPageSize(1)->addStoreFilter();
Mage::getSingleton(‘catalog/product_status’)->addVisibleFilterToCollection ($_productCollection);
Mage::getSingleton(‘catalog/product_visibility’)->addVisibleInSearchFilterToCollection ($_productCollection);
$todayDate    = date(‘m/d/y’);
$tomorrow     = mktime(0, 0, 0, date(‘m’), date(‘d’) + 1, date(‘y’));
$tomorrowDate = date(‘m/d/y’, $tomorrow);
$_productCollection->addAttributeToFilter(‘special_from_date’, array(
‘date’ => true,
‘to’ => $todayDate
))->addAttributeToFilter(‘special_to_date’, array(
‘or’ => array(
0 => array(
‘date’ => true,
‘from’ => $tomorrowDate
),
1 => array(
‘is’ => new Zend_Db_Expr(‘null’)
)
)
), ‘left’)->addAttributeToSort(‘special_from_date’, ‘desc’);
?>
<?php
$i = 0;
if ($i++ % 3 == 0)
?>
<ul>
<?php
$x = 2;
?>
<?php
foreach ($_productCollection as $_product) {
if ($_product->getData(‘special_price’) != null) {
?>
<li>
<h2><?php
if ($locale == en_US) {
echo $this->__(‘Special Offers’);
} else if ($locale == el_GR) {
echo $this->__(‘Προσφορές’);
} else {
echo $this->__(‘Special Offers’);
}
?></h2>

<img src=”<?php
echo $this->helper(‘catalog/image’)->init($_product, ‘thumbnail’)->resize(135);
?>” alt=”<?php
echo $_product->getName();
?>” width=”135″ height=”135″ />
<?php
$specialPrice = $_product->getData(‘special_price’);
$orignalPrice = $_product->getData(‘price’);
?>

<?php
}
}
?>

Custom Menu In Magento

Custom Menu In Magento

<?php

        $root_category = Mage::getModel(‘catalog/category’)->load(3); // Put your root category ID here.

        $subcategories = $root_category->getChildren();

  foreach(explode(‘,’,$subcategories) as $subcategory) {

        $category = Mage::getModel(‘catalog/category’)->load($subcategory);

        echo ‘<a href=”‘.$category->getURL() .'” />’.$category->getName().'</a><br/>’;

  }

  ?>

Add Page In Navigation Menu

Add Page In Navigation Menu

1 Go To CatalogèManage Categories=> Add Sub Categories====note the categories ID

2 Go to CMS èPage => add New Page=====note the the url  key

3 Got To CatalogèURL Rewrite Management=> find Category Id and open store ==note the Request Path and delete this category

4Go toè add url Rewrite => select custom=>ID path– categories ID(1 step path)

Request Path=> Request Path(3 step path)

Target Path =>url Key(2 step path)

How To Disable Right Click and Ctrl Key

<script type=”text/javascript”>
var isNS = (navigator.appName == “Netscape”) ? 1 : 0;

if(navigator.appName == “Netscape”) document.captureEvents(Event.MOUSEDOWN||Event.MOUSEUP);

function mischandler(){
return false;
}

function mousehandler(e){
var myevent = (isNS) ? e : event;
var eventbutton = (isNS) ? myevent.which : myevent.button;
if((eventbutton==2)||(eventbutton==3)) return false;
}
document.oncontextmenu = mischandler;
document.onmousedown = mousehandler;
document.onmouseup = mousehandler;
var isCtrl = false;
document.onkeyup=function(e)
{
if(e.which == 17)
isCtrl=false;
}

document.onkeydown=function(e)
{
if(e.which == 17)
isCtrl=true;
if(((e.which == 85) || (e.which == 117) || (e.which == 65) || (e.which == 97) || (e.which == 67) || (e.which == 99) || (e.which == 112) ) && isCtrl == true)
{
// alert(‘Keyboard shortcuts are cool!’);
return false;
}
}
</script>

Upload Image & Compress Image Size

Upload Image & Compress Image Size

HTML Code For File Uploading

<form action=”upload.php” method=”post” name=”video_upload” enctype=”multipart/form-data”>
<input name=”new_image” id=”new_image” size=”30″ type=”file” multiple=”true” />
<input type=”submit” value=”submit” name=”submit” />
</form>

 

File Name upload.php
<?php

if (isset ($_FILES[‘new_image’])){
$imagename = $_FILES[‘new_image’][‘name’];
$source = $_FILES[‘new_image’][‘tmp_name’];
$type=$_FILES[‘new_image’][‘type’];

$idate=$_REQUEST[‘idate’];

if(($_FILES[‘new_image’][‘type’]==’image/jpeg’) ||
($_FILES[‘new_image’][‘type’]==’image/png’)||
($_FILES[‘new_image’][‘type’]==’image/bmp’)||
($_FILES[‘new_image’][‘type’]==’image/tiff’)||
($_FILES[‘new_image’][‘type’]==’image/gif’))
{
$target = “../upload/”.$imagename;
move_uploaded_file($source, $target);

$imagepath = $imagename;
$save = “../upload/” . $imagepath; //This is the new file you saving
$file = “../upload/” . $imagepath; //This is the original file

list($width, $height) = getimagesize($file) ;

$tn = imagecreatetruecolor($width, $height) ;
$image = imagecreatefromjpeg($file) ;
imagecopyresampled($tn, $image, 0, 0, 0, 0, $width, $height, $width, $height) ;

imagejpeg($tn, $save, 75) ;

$save = “../upload/sml_” . $thumbfile=$imagepath; //This is the new file you saving
$file = “../upload/” . $fullimage=$imagepath; //This is the original file

list($width, $height) = getimagesize($file) ;

$modwidth = 155;

$diff = $width / $modwidth;

$modheight = 130;
$tn = imagecreatetruecolor($modwidth, $modheight) ;
$image = imagecreatefromjpeg($file) ;
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;

imagejpeg($tn, $save, 100) ;
“Large image: <img src=’images/”.$imagepath.”‘><br>”;
“Thumbnail: <img src=’images/sml_”.$imagepath.”‘>”;

}
}
else
{
echo “Please upolad .jpg, .png image file”;
}
?>

PHP Interview Quesition & Answer

1.Explain how to submit form without a submit button in PHP?

A form can be submitted in various ways without using submit button.

  • Submitting a form by selecting an option from drop down box with the invocation of onChange event
  • Using java script : document.form.submit();
  • Using header(“location:page.php”);

2.How can we increase the execution time of a php script?

Default time allowed for the PHP scripts to execute is 30s defined in the php.ini file. The function used is set_time_limit(int seconds). If the value passed is ‘0’, it takes unlimited time. It should be noted that if the default timer is set to 30 sec and 20 sec is specified in set_time_limit(), the script will run for 45 secs.

How can we increase the execution time of a php script?

The script execution time can be increased by

– Using sleep() function in PHP script

– Using set_time_limit() function

– The default limit is 30 seconds. The time limit can be set to zero to impose no time limit to pause.

3.What are the functions for IMAP?

IMAP is used for communicate with mail servers. It has a number of functions. Few of them are listed below:

  • Imap_alerts – Returns all the imap errors occurred
  • Imap_body – Reads the message body
  • Imap_check – Reads the current mail box
  • Imap_clearflag_full – Clears all flags
  • Imap_close – close and IMAP stream
  • Imap_delete – Delete message from current mailbox
  • Imap_delete_mailbox – Deletes a mailbox
  • Imap_fetchbody – Fetches body of message
  • Imap_fetchheader – Fetches header of message
  • Imap_headers – Returns headers for ALL messages
  • Imap_mail : send a mail
  • Imap_sort- Sorts imap messages

4.What is Type juggle in php?

Type Juggling means dealing with a variable type. In PHP a variables type is determined by the context in which it is used. If an integer value is assigned to a variable, it becomes an integer.
E.g. $var3= $var1 + $var2

Here, if $var1 is an integer. $var2 and $var3 will also be treated as integers.

5.What is the difference between mysql_fetch_object and mysql_fetch_array?

Mysql_fetch_object returns the result from the database as objects while mysql_fetch_array returns result as an array. This will allow access to the data by the field names. E.g. using mysql_fetch_object field can be accessed as $result->name and using mysql_fetch_array field can be accessed as $result->[name]

6.Explain the ways to retrieve the data in the result set of MySQL using PHP?

Ways to retrieve the data in the result set of MySQL using PHP

1. mysql_fetch_row($result):- where $result is the result resource returned from a successful query executed using the mysql_query() function.

$result = mysql_query(“SELECT * from students);
while($row = mysql_fetch_row($result))
{
Some statement;
}

2. mysql_fetch_array($result):- Return the current row with both associative and numeric indexes where each column can either be accessed by 0, 1, 2, etc., or the column name.

$row = mysql_fetch_array($result)

3. mysql_fetch_assoc($result): Return the current row as an associative array, where the name of each column is a key in the array.

$row = mysql_fetch_assoc($result)
$row[‘column_name’]

7.What is the difference between the functions unlink and unset in PHP?

The function unlink() is to remove a file, where as unset() is used for destroying a variable that was declared earlier.

8.What is Joomla in PHP?

Joomla is a content management system. Powerful online applications and web sites are build using Joomla. Joomla is an open source CMS tool. Clients can easily manage their web sites with minimal amount of instructions. It is highly extensible. Joomla runs off PHP or MySQL. Joomla is used to create, maintain a structured, flexible portal, add or edit content, changes the look and feel of the site. PHP scripting is used and persisted most of its data / information in MySQL database.unset() empties a variable or contents of file.

9.What is zend engine in PHP?

Zend engine is like a virtual machine and is an open source, and is known for its role in automating the web using PHP. Zend is named after its developers Zeev and Aandi. Its reliability, performance and extensibility has a significant role in increasing the PHP’s popularity. The Zend Engine II is the heart of PHP 5. It is an open source project and freely available under BSD style license.

10.What is the difference between Split and Explode in PHP?

The split() function splits the string into an array using a regular expression and returns an array.
Ex: split(:India:Pakistan:Srilanka); returns an array that contains India, Pakistan, Srilanka.

The explode() function splits the string by string.
Ex: explode(and India and Pakistan and Srilanka); returns an array that contains India, Pakistan, Srilanka.

11.What is the difference between echo and print statement in PHP?

Multiple expressions can be given in echo statement, where as print cannot take multiple expressions.
Echo does not have a return value, where as print returns a value indicating successful execution.
Echo is faster when compared with print.

12.What is CAPTCHA in PHP?

Captcha are images with some characters/ digits on it. One need to type the characters or digits in the text box for the purpose of submitting. This avoids automatic submitting by an operation by other programs or a robot.

13.What is difference between developing website using Java and PHP?

Both technologies are used for dynamic websites development.

PHP is an interpreter based technology where as java is compiler based(usually JSP).

PHP is open source where as JSP is not.

Web sites developed in PHP are much more faster compared to Java technology

Java is a distributed technology, which means N tier application can be developed, where as PHP is used only for web development.

14.How do you create sub domains using PHP?

Wild card domains can be used. Sub domains can be created by first creating a sub directory in the /htdocs folder. E.g. /htdocs/mydomain. Then, the host file needs to be modified to define the sub domain. If the sub domains are not configured explicitly, all requests should be thrown to the main domain.

15.How to upload files using PHP?

– Select a file from the form using <inupt type=”file”>

– Specify the path into which the file is to be stored.

– Insert the following code in php script to upload the file.

move_uploaded_file($_FILES[“file”][“tmp_name”], “myfolder/” . $_FILES[“file”][“name”]);