Magento Design Patterns : Magento Uses 12 Design patterns

 

1. Model View Controller Pattern

Model View Controller, MVC for short, is a design pattern where business, presentation and coupling logic are separated. Magento heavily utilizes XML as templating-logic and HTML mixed with PHP files for its views. Models are backed by Varien’s ORM. Most business logic happens in the models whereas the controllers map the model-data to the views.

Because Magento its views are “fat” – they often contain a lot of logic – its not rare that views have an additional PHP class (the Block system) which will help with rendering.

2. Front Controller Pattern

The front controller pattern makes sure that there is one and only one point of entry. All requests are investigated, routed to the designated controller and then processed accordingly to the specification. The front controller is responsible of initializing the environment and routing requests to designated controllers.

Magento has only one point of entry ( index.php) which will initialize the application environment ( Mage::app()) and route the request to the correct controller.

3. Factory Pattern

As implied by the name, the factory pattern is responsible of factorizing (instantiating) classes. It’s widely used through the Magento code base and leverages the autoloading system in Magento. By defining an alias in a module its config.xml you are letting the factory know where it can find classes.

There are various factory-helper methods in the Mage core class and one of them is getModel(). It accepts an alias for a class and will then return an instance of it. Instead of having include calls scattered through the code base, the factory pattern will instantiate classes in an uniform way.

4. Singleton Pattern

Another way to retrieve an instance of a class, is to call Mage::getSingleton(). It accepts a class alias and before returning an instance, it checks the internal registry whether this class has already been instantiated before – this results in a shared instance. An example of where this is mandatory, is the session storage which should be shared through the code base instead of creating it anew every time.

5. Registry Pattern

All the singletons are stored in the internal registry: a global scoped container for storing data. It is not only for internal use. The Mage::register($key, $value), ::registry($key) and ::unregister($key) methods can be respectively used for storing, retrieving and removing data from the registry. The registry is often used for transferring data between scopes when they cannot be passed on, otherwise.

6. Prototype Pattern

Where the factory pattern (#3 on our list) stops, is where the prototype pattern continues. It defines that instances of classes can retrieve a specific other class instance depending on its parent class (the prototype). A notable example is the Mage_Catalog_Model_Product class which has a getTypeInstance method to retrieve the specific Mage_Catalog_Model_Product_Type with a specific subset of methods and properties not applicable to all products.

For example, the Mage_Downloadable_Model_Product_Type ultimately extends the Mage_Catalog_Model_Product_Type. If you are iterating over an order and want to call a specific method of a downloadable product, you will need to factorize it first with the getTypeInstance method of the original product.

7. Object Pool Pattern

The object pool pattern is simply a box with objects so that they do not have to be allocated and destroyed over and over again. It’s not used a lot in Magento other than for heavy tasks where resources can get limited soon, like importing products. The object pool (managed by Varien_Object_Cache) can be accessed with Mage::objects().

8. Iterator Pattern

The iterator pattern defines that there is a shared way to iterate over a container with objects. In Magento, this is handled by the Varien_Data_Collection which on its turn uses various baked-in PHP classes (like ArrayIterator) for having a more OO-interface to arrays. This ensures that model-collections will always have a common API to iterate over without being dependent of the actual models.

9. Lazy Loading Pattern

Lazy loading ensures that loading data is delayed until the point when it is actually needed. This results in less resources being used. One of the lazy loading behaviors of Magento is that of collections. If you were to retrieve a collection of products with Mage::getModel(‘catalog/product’)->getCollection(), the database will only be touched when you actually access the collection by, for example, iterating over it or retrieving the count of models found.

10. Service Locator Pattern

The service locator pattern abstracts away the retrieval of a certain service. This allows for changing the service without breaking anything (as it adheres to its abstract foundation) but also fetching the service as seen fit for its purpose.

Ryan exemplifies this with database connections. Another example is that of Magento its caching mechanism where Mage::getCache() is a service locator by-proxy for the cache storage supplied by Zend or other vendors.

11. Module Pattern

Anyone familiar with Magento development has stumbled upon the module pattern. It basically defines that different domains are grouped into separate modules which function independent of each other and can be plugged-in to the main system as deemed appropriate. In an ideal situation, an implementation of the module pattern would make sure that each element can be removed or swapped. One of the protagonists of the module pattern in PHP is the Composer package manager.

Though Magento heavily relies on a modular architecture, its not modular to the bone. Certain functionality is heavily tied to the core and can not be easily changed. There is also the heavy usage of the super-global Mage core-class which introduces all sorts of system-wide dependencies not easily overseen.

12. Observer Pattern

Magento its event-driven architecture is a result of an implementation of the observer pattern. By defining observers (or listeners), extra code can be hooked which will be called upon as the observed event fires. Magento uses its XML-data storage to define observers. If an event is fired with Mage::dispatchEvent($eventName, $data), the data storage will be consulted and the appropriate observers for $event will be fired.

 

Difference between Mage::getModel() and Mage::getSingleton() in Magento

Mage::getModel()

Mage::getModel() will create a new instance of an object each time even such object exists in configuration.

Example

1
2
$prod1 = Mage::getModel('catalog/product');
$prod2 = Mage::getModel('catalog/product');

$prod1 and $prod2 both have different instant of same object and also occupy different memory .

Mage::getSingleton()

Mage::getSingleton() will first check the same class instance is exits or not in memory. If the instance is created then it will return the same object from memory. So Mage::getSingleton() faster then Mage::getModel().

1
2
$prod1 = Mage::getSingleton('catalog/product');
$prod2 = Mage::getSingleton('catalog/product');

$prod1 and $prod2 both will share same memory of OS and return only one instance each time.

If you want to protect your Magento backend against attackers, you can follow below mentioned steps to change your admin url/path.

Follow these steps to change the admin URL/path.

Step1 :

First, open the local.xml configuration file in your favorite text editor, or use the Text Editor in the cPanel File Manager. The file is usually located in the app/etc/ directory under your Magento installation. Locate the following code segment:

<admin>
<routers>
<adminhtml>
<args>
<frontName><![CDATA[admin]]></frontName>
</args>
</adminhtml>
</routers>
</admin>

 

Now, replace admin with your new admin path. This should be something personal which is hard to guess, use only letters or numbers – no special characters, then save the file.

Step 2 – Refresh Cache

The final step is to refresh your cache. Use an FTP client to delete the content of the var/cache/ directory, or use the following SSH command.

rm -rf var/cache/*

Step 3

The change is now complete and you should try to log in via the new admin url – http://domain/adminpath/, replacing ‘adminpath’ with the path you chose in the step above. If everything went fine, you should now be presented with the Admin Panel login screen at the new URL. The old admin login URL should return a 404 error message.

1. Explain Magento’s MVC architecture

First of all, what is MVC?
MVC stands for Model-View-Controller. Any application that separates it’s data access, business logicand user interface is called MVC. There can be two types of MVC: convention-based and configuration-based. Example, cakePHP is convention-based, i.e. you just need to follow the instructions of the core system to get your module ready in just few lines. Magento is configuration-based, i.e. you need to specify each and every thing to your module’s config file in order to get it work. Magento has Controller (for Routing), Block (for Business Logic), Model (for DB access, sql) and Template file (for Presentation i.e. View).

How Magento’s MVC works:
1. When you enter the URL (something like http://mysite.com/frontname/controller/method/param1/value1/param2/value2), this URL is intercepted by one PHP file called index.php which instantiates Magento application
2. Magento application instantiates Front Controller object
3. Further, front controller instantiates Router objects (specified in module’s config.xml, global tag)
4. Now, Router is responsible to “match” the frontname which is in our URL
5. If “match” is found, it sees controller name and method name in the URL, which is finally called.
6. Now depending on what is written in action name (method name), it is executed. If any models are called in it, the controller method will instantiate that model and call the method in it which is requested.
7. Then the controller action (method) instantiate the Layout object, which calls Block specified for this action (method) name (Each controller action name have block and template file associated with it, which can be found at app/design/frontend or adminhtml/namespace/module/layout/module.xml file, name of layout file (module.xml) can be found in config.xml of that module, in layout updates tag).
8. Template file (.phtml) now calls the corresponding block for any method request. So, if you write $this->methodName in .phtml file, it will check “methodName” in the block file which is associated in module.xml file.
9. Block contains PHP logic. It references Models for any data from DB.
10. If either Block, Template file or Controller need to get/set some data from/to database, they can call Model directly like Mage::getModel(‘modulename/modelname’).

More Magento Questions with answers

Q 1. What is Magento?
Ans. Magento is a feature-rich eCommerce platform built on open-source technology that provides online merchants with unprecedented flexibility and control over the look, content and functionality of their eCommerce store. Magentos intuitive administration interface features powerful marketing, search engine optimization and catalog-management tools to give merchants the power to create sites that are tailored to their unique business needs. Designed to be completely scalable and backed by Variens support network, Magento offers companies the ultimate eCommerce solution.

Q 2. What is the difference between Mage::getSingletone() andMage::getModel() in Magento
Ans. Mage::getSingletone() always finds for an existing object if not then create that a newobject but Mage::getModel() always creates a new object.

Q 3. Why Magento use EAV database model ?
Ans. In EAV database model, data are stored in different smaller tables rather than storing in asingle table.product name is stored in catalog_product_entity_varchar tableproduct id is stored in catalog_product_entity_int tableproduct price is stored in catalog_product_entity_decimal tableMagento Use EAV database model for easy upgrade and development as this model givesmore flexibility to play with data and attributes.

Q 4. How to upgrade to the latest version using Magento Connect?
Ans. Upgrading Magento to the latest version is a fairly simple task. Copy and Paste this key magento-core/Mage_All_Latest VIA Magento Connect where it states Paste extension key to install:. This will upgrade Magento to the newest version.

Q 5. Explain about the Modules of Magento?
Ans. Magento supports installation of modules through a web-based interface accessible through the administration area of a Magento installation. Modules are hosted on the Magento eCommerce website as a PEAR server. Any community member can upload a module through the website and is made available once confirmed by a member of the Magento team. Modules are installed by entering a module key, available on the module page, into the web based interface.

There are three categories of modules hosted on Magento Connect:

Core Modules
Community Modules
Commercial Modules
Core and Community modules can be installed via the administration area. Commercial module pages provide price information and a link to an external website.

Q 6. What technology used by Magento?
Ans. Magento uses PHP as a web server scripting language and the MySQL Database. The data model is based on the Entity-attribute-value model that stores data objects in tree structures, thus allowing a change to a data structure without changing the database definition.

Q 7. What is MVC structure in Magento?
Ans. The Model-View-Controller (MVC) architecture traces its
origins back to the Smalltalk Programming language and Xerox
Parc. Since then, there have been many systems that describe
their architecture as MVC. Each system is slightly
different, but all have the goal of separating data access,
business logic, and user-interface code from one another.

Q 8. What is benefit of namespace (package) in magento?
Ans. We can have more than one module with same name but they should be placed in different namespaces. All magento core modules are contained in mage namespace.
core/Mage/Catalog

and all custom modules are placed in

local/CustomModule

Q 9. How to include CMS block in template file(.phtml)?
Ans. Access block’s content from .phtml template file by :

echo $this->getLayout()->createBlock(‘cms/block’)->setBlockId(‘static_block_id’)->toHTML();

Q 10. How to add an external javascript/css file to Magento?
Ans.
css/yourstyle.css
or
skin_jsjs/ yourfile.js
skin_csscss/yourstyle. css

Q 11. What are handles in magento (layout)?
Ans. Handles are basically used for controlling the structure of the page like which block will be displayed and where. First level child elements of the node are called layout handles. Every page request can have several unique Handles. The handle is called for every page. handle for products belongs to virtual product type, PRODUCT_TYPE_simple is called for product details page of simple product type and PRODUCT_TYPE_virtual is called for the virtual product detail page and customer_logged_in handle is called only if customer is logged in. The muster_index_index handle is created by combining the frontName (muster), Action Controller (index), and Action Controller Action Method (index) into a single string and this handle will be called only when /zag/index/index url is accessed.

Q 12. What is in magento?
Ans. The routers tag allow us to decide frontname for each module. The tag is defined in config.xml file of module. For Namespace_MyModule frontname is moduleurl so the url will be like :
websiteurl.com/moduleurl/controllername/actionname

standard
Namespace_MyModule
moduleurl

Q 13. Which factors affect performance of magento?

Ans.
1. EAV structure of magento database, even for retrieving single entity the query becomes very complex .
2. Magento’s template system involves a lot of recursive rendering
3. Huge XML trees built up for layout configuration, application configuration settings

Q 14. How to improve magento performance?
Ans.

Enabled magento caching
MySQL Query caching
Enable Gzip Compression
Disable any unused modules
Disable the Magento log
Optimise your images
Combine external CSS/JS into one file
Enable Apache KeepAlives: Make sure your Apache configuration has KeepAlives enabled.

Q 15. How to get the Total Price of items currently in the Cart?
helper(‘checkout’)->formatPrice(Mage::getSingleton(‘checkout/cart’)->getQuote()->getGrandTotal()); ?>

Q 16. How to set different themes for logged in users?
if(Mage::getSingleton(‘customer/session’)->isLoggedIn()):
Mage::getDesign()->setPackageName(‘package_name’)->setTheme(‘themename’);
endif;

Q 17. How to create magento custom module?
Ans. Steps to create custom magento module:
Namespace : Zag
Module Name : Mymodule
1. Create directory Mymodule in app/code/local/Zag
2. Create Block, controllers, etc, Module directories. Create controller, block and module file as required.
3. Create module configuration file (app/code/local/Zag/Mymodule/etc/config.xml).
4. Create xml file (app/etc/modules/Zag_ Mymodule.xml)to enable/disable module and tell magento system from which code pool that module will be taken.

Q 18. How to set different themes for each store?
Ans. Go to : System>Designs
Then, add new design change or edit existing. You can select Store and Custom Design.

Q 19. How to make product’s custom attribute searchable in adavance search?
Ans. Go to : Catalog > Attribues > Manage Attribues
Edit the attribute and select “Yes” for Use in Advanced Search.

Q 20. How to fetch 5 bestsellers products programmatically?
Ans.
Mage::getResourceModel(‘reports/product_collection’)
->addOrderedQty()
->addAttributeToSelect(‘*’)
->setPage(1, 5)
->load();

What is JavaScript?
A1: JavaScript is a general-purpose programming language designed to let programmers of all skill levels control the behavior of software objects. The language is used most widely today in Web browsers whose software objects tend to represent a variety of HTML elements in a document and the document itself. But the language can be–and is–used with other kinds of objects in other environments. For example, Adobe Acrobat Forms uses JavaScript as its underlying scripting language to glue together objects that are unique to the forms generated by Adobe Acrobat. Therefore, it is important to distinguish JavaScript, the language, from the objects it can communicate with in any particular environment. When used for Web documents, the scripts go directly inside the HTML documents and are downloaded to the browser with the rest of the HTML tags and content.

A2:JavaScript is a platform-independent,event-driven, interpreted client-side scripting and programming language developed by Netscape Communications Corp. and Sun Microsystems.

How is JavaScript different from Java?
JavaScript was developed by Brendan Eich of Netscape; Java was developed at Sun Microsystems. While the two languages share some common syntax, they were developed independently of each other and for different audiences. Java is a full-fledged programming language tailored for network computing; it includes hundreds of its own objects, including objects for creating user interfaces that appear in Java applets (in Web browsers) or standalone Java applications. In contrast, JavaScript relies on whatever environment it’s operating in for the user interface, such as a Web document’s form elements.
JavaScript was initially called LiveScript at Netscape while it was under development. A licensing deal between Netscape and Sun at the last minute let Netscape plug the “Java” name into the name of its scripting language. Programmers use entirely different tools for Java and JavaScript. It is also not uncommon for a programmer of one language to be ignorant of the other. The two languages don’t rely on each other and are intended for different purposes. In some ways, the “Java” name on JavaScript has confused the world’s understanding of the differences between the two. On the other hand, JavaScript is much easier to learn than Java and can offer a gentle introduction for newcomers who want to graduate to Java and the kinds of applications you can develop with it.

What’s relationship between JavaScript and ECMAScript?
ECMAScript is yet another name for JavaScript (other names include LiveScript). The current JavaScript that you see supported in browsers is ECMAScript revision 3.
How do you submit a form using Javascript?
Use document.forms[0].submit();
(0 refers to the index of the form – if you have more than one form in a page, then the first one has the index 0, second has index 1 and so on).

How do we get JavaScript onto a web page?
You can use several different methods of placing javascript in you pages.
You can directly add a script element inside the body of page.
1. For example, to add the “last updated line” to your pages, In your page text, add the following:

blah, blah, blah, blah, blah.

yada, yada, yada.

(Note: the first comment, “<--" hides the content of the script from browsers that don't understand javascript. The "// -->” finishes the comment. The “//” tells javascript that this is a comment so javascript doesn’t try to interpret the “–>”. If your audience has much older browsers, you should put this comments inside your javascript. If most of your audience has newer browsers, the comments can be omitted. For brevity, in most examples here the comments are not shown. )
The above code will look like this on Javascript enabled browsers,
2. Javascript can be placed inside the element
Functions and global variables typically reside inside the element.

Default Test Page

Javascript can be referenced from a separate file
Javascript may also a placed in a separate file on the server and referenced from an HTML page. (Don’t use the shorthand ending “

How to read and write a file using javascript?
I/O operations like reading or writing a file is not possible with client-side javascript. However , this can be done by coding a Java applet that reads files for the script.

How to detect the operating system on the client machine?
In order to detect the operating system on the client machine, the navigator.appVersion
string (property) should be used.

How can JavaScript make a Web site easier to use? That is, are there certain JavaScript techniques that make it easier for people to use a Web site?
JavaScript's greatest potential gift to a Web site is that scripts can make the page more immediately interactive, that is, interactive without having to submit every little thing to the server for a server program to re-render the page and send it back to the client. For example, consider a top-level navigation panel that has, say, six primary image map links into subsections of the Web site. With only a little bit of scripting, each map area can be instructed to pop up a more detailed list of links to the contents within a subsection whenever the user rolls the cursor atop a map area. With the help of that popup list of links, the user with a scriptable browser can bypass one intermediate menu page. The user without a scriptable browser (or who has disabled JavaScript) will have to drill down through a more traditional and time-consuming path to the desired content.

What are JavaScript types?
Number, String, Boolean, Function, Object, Null, Undefined.

How do you convert numbers between different bases in JavaScript?
Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt ("3F", 16);

How to create arrays in JavaScript?
We can declare an array like this
var scripts = new Array();
We can add elements to this array like this

scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";

Now our array scrips has 4 elements inside it and we can print or access them by using their index number. Note that index number starts from 0. To get the third element of the array we have to use the index number 2 . Here is the way to get the third element of an array.
document.write(scripts[2]);
We also can create an array like this
var no_array = new Array(21, 22, 23, 24, 25);

How do you target a specific frame from a hyperlink?
Include the name of the frame in the target attribute of the hyperlink. >My Page

What is a fixed-width table and its advantages?

Fixed width tables are rendered by the browser based on the widths of the columns in the first row, resulting in a faster display in case of large tables. Use the CSS style table-layout:fixed to specify a fixed width table.
If the table is not specified to be of fixed width, the browser has to wait till all data is downloaded and then infer the best width for each of the columns. This process can be very slow for large tables.

Example of using Regular Expressions for syntax checking in JavaScript

...
var re = new RegExp("^(&[A-Za-z_0-9]{1,}=[A-Za-z_0-9]{1,})*$");
var text = myWidget.value;
var OK = re.test(text);
if( ! OK ) {
alert("The extra parameters need some work.\r\n Should be something like: \"&a=1&c=4\"");
}

Q: What is the difference between .call() and .apply()?

The JavaScript Function prototype has two very powerful functions that are at the core of Javascript’s “everything is an object” mentality, including functions, Kubasik says.

“The really important part of this discussion is not that they remember which is which, but more that the interviewee understands that the “this” keyword is not as predictable as in other languages, and that functions can be applied to other objects, and generally be treated as data,” he says.

Q: Can you explain how inheritance works in JavaScript?

JavaScript has a somewhat unique inheritance model and a good understanding of it is crucial to using JavasScript in larger applications, Kubasik says. “We are looking for the applicant to discuss not only prototypes, and how that affects inheritance, but in what ways this can be more flexible than classical inheritance models seen in Java and C#.”

1- What is jQuery ?

It’s very simple but most valuable Question on jQuery means jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, animating, event handling, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript. Jquery is build library for javascript no need to write your own functions or script jquery all ready done for you

2- How you will use Jquery means requirement needed for using jquery?

Nothing more need to do just olny download jquery library(.js file) from any of the jquery site Download jquery and just linked with your html pages like all other javascript file

like below :

Code:

< script src=”jquery.js” language=”javascript” type=”text/javascript”>

3- what the use of $ symbol in Jquery?
$ Symbol is just replacement of jquery means at the place of $ you may use jquery hence $ symbol is used for indication that this line used for jquery

4- How do you select an item using css class or ID and get the value by use of jquery?
If an element of html like < div> , < p> or any tag have ID MyId and class used MyClass then we select the element by below jquery code
Code:
$(‘#MyId’) for ID and for classs $(‘.MyClass’)
and for value

Code:
var myValue = $(‘#MyId’).val();
// get the value in var Myvalue by id
Or for set the value in selected item

Code:
$(‘#MyId’).val(“print me”);
// set the value of a form input

5- How to get the server response from an AJAX request using Jquery?

When invoking functions that have asynchronous behavior We must provide a callback function to capture the desired result. This is especially important with AJAX in the browser because when a remote request is made, it is indeterminate when the response will be received.
Below an example of making an AJAX call and alerting the response (or error):

Code:
$.ajax({
url: ‘swtEmpRecords.php’,
success: function(response) {
alert(response);
},
error: function(xhr) {
alert(‘Error! Status = ‘ + xhr.status);
}
});

6- How do you update ajax response with id ” resilts”?
By using below code we can update div content where id ‘results’ with ajax response

Code:
function updateStatus() {
$.ajax({
url: ‘swtEmpRecords.php’,
success: function(response) {
// update div id Results
$(‘#results’).html(response);
}
});
}

7- How do You disable or enable a form element?
There are two ways to disable or enable form elements.
Set the ‘disabled’ attribute to true or false:

Code:
// Disable #swt
$(‘#swt’).attr(‘disabled’, true);
// Enable #swt
$(‘#swt’).attr(‘disabled’, false);
Add or remove the ‘disabled’ attribute:
// Disable #swt
$(“#swt”).attr(‘disabled’, ‘disabled’);
// Enable #x
$(“#swt”).removeAttr(‘disabled’);

8- How do you check or uncheck a checkbox input or radio button?
There are two ways to check or uncheck a checkbox or radio button.
Set the ‘checked’ attribute to true or false.

Code:
// Check #swt
$(‘#swt’).attr(‘checked’, true);
// Uncheck #swt
$(‘#swt’).attr(‘checked’, false);
Add or remove the ‘checked’ attribute:
// Check #swt
$(“#swt”).attr(‘checked’, ‘checked’);
// Uncheck #swt
$(“#swt”).removeAttr(‘checked’);

9- How do you get the text value of a selected option?
Select elements typically have two values that you want to access. First there’s the value to be sent to the server, which is easy:

Code:
$(“#swtselect”).val();
// => 1
The second is the text value of the select. For example, using the following select box:

Code:
<select id=”swtselect”>
<option value=”1″>Mr</option>
<option value=”2″>Mrs</option>
<option value=”3″>Ms</option>
<option value=”4″>Dr</option>
<option value=”5″>Prof</option>
</select>
If you wanted to get the string “Mr” if the first option was selected (instead of just “1”), you would do that in the following way:

Code:
$(“#mswtselect option:selected”).text();
// => “Mr”

 
10) What is difference between $(this) and ‘this’ in jQuery?

Refer the following example

$(document).ready(function(){
$(‘#clickme’).click(function(){
alert($(this).text());
alert(this.innerText);
});
});

-this and $(this) references the same element but the difference is that “this” is used in traditional way but when “this” is used with $() then it becomes a jQuery object on which we can use the functions of jQuery.
-In the example given, when only “this” keyword is used then we can use the jQuery text() function to get the text of the element, because it is not jQuery object. Once the “this” keyword is wrapped in $() then we can use the jQuery function text() to get the text of the element.

11) What is the use of param() method.

The param() method is used to represent an array or an object in serialize manner.
While making an ajax request we can use these serialize values in the query strings of URL.
Syntax: $.param(object | array, boolValue)
“object | array” specifies an array or an object to be serialized.
“boolValue” specifies whether to use the traditional style of param serialization or not.
For example:

personObj=new Object();
empObject.name=”Arpit”;
empObject.age=”24″;
empObject.dept=”IT”;
$(“#clickme”).click(function(){
$(“span”).text($.param(empObject));
});
It will set the text of span to “name=Arpit&age=24&dep=IT”

12) What is jQuery.holdReady() function?

-By using jQuery.holdReady() function we can hold or release the execution of jQuery’s ready event.
-This method should be call before we run ready event.
-To delay the ready event, we have to call

jQuery.holdReady(true);

-When we want to release the ready event then we have to call
jQuery.holdReady(false);
-This function is helpful when we want to load any jQuery plugins before the execution of ready event.

For example

$.holdReady(true);
$.getScript(“xyzplugin.js”, function() {
$.holdReady(false);
});

13) Explain .empty() vs .remove() vs .detach().

-.empty() method is used to remove all the child elements from matched elements.
-.remove() method is used to remove all the matched element. This method will remove all the jQuery data associated with the matched element.
-.detach() method is same as .remove() method except that the .detach() method doesn’t remove jQuery data associated with the matched elements.
-.remove() is faster than .empty() or .detach() method.

Syntax:

$(selector).empty();
$(selector).remove();
$(selector).detach();

14) How to read, write and delete cookies in jQuery?

-To deal with cookies in jQuery we have to use the Dough cookie plugin.
-Dough is easy to use and having powerful features.
-Create cookie

$.dough(“cookie_name”, “cookie_value”);

Read Cookie
$.dough(“cookie_name”);
Delete cookie
$.dough(“cookie_name”, “remove”);

15) Is window.onload is different from document.ready()?

– The window.onload() is Java script function and document.ready() is jQuery event which are called when page is loaded.
– The difference is that document.ready() is called after the DOM is loaded without waiting for all the contents to get loaded. While window.onload() function waits until the contents of page is loaded.
– Suppose there is very large image on a page, at that time window.onload() will wait until that image is loaded totally.
– So while using the window.onlaod() function the execution will be slow, but the document.ready() will not wait until the image is loaded.

16) What is Chaining in jQuery?

– Chaining is very powerful feature of jQuery.
– Chaining means specifying multiple function and/or selectors to an element.
– Examine the below example

$(document).ready(function(){
$(‘#mydiv’).css(‘color’, ‘blue’);
$(‘#mydiv’).addClass(‘myclass’);
$(‘#mydiv’).fadeIn(‘fast’);
}

By using chaining we can write above code as follows

$(document).ready(function(){
$(‘#mydiv’).css(‘color’, ‘blue’).addClass(‘myclass’).fadeIn(‘fast’);
});

-Advantage of chaining is that it makes your code simple and simple to manage.
-The execution becomes faster because the code search for the element only once.

17) What is difference between sorting string array and sorting numerical array in jQuery?

The sort method is used to sort any array elements. It sorts the string elements alphabetically.

For example

$(document).ready(function(){
var mylist = [ “Apple”,”Orange”,”Banana”];
mylist = mylist.sort();
$(“#mydiv”).html(list.join(“”));
});

It will give following output
Apple
Banana
Orange

Now we declare a numerical array and use sort() method to sort its elements.

$(document).ready(function(){
var mylist = [ “20”,”3″”100″,”50″];
mylist = mylist.sort();
$(“#mydiv”).html(list.join(“”));
});

It will give following output
100
20
3
50

18) What is difference between prop and attr?

In jQuery both prop() and attr() function is used to set/get the value of specified property of an element.
The difference in both the function is that attr() returns the default value of the property while the prop() returns the current value of the property.
For example

<input value=”My Value” type=”text”/>

$(‘input’).prop(‘value’, ‘Changed Value’);

-.attr(‘value’) will return ‘My Value’
-.prop(‘value’) will return ‘Changed Value’

19) How to always reference latest version of jQuery?

When you reference the jQuery on your web page, you have to specify the version number also.

<script type=”text/javascript”
src=”http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js”>
</script>

Above code will always load the 1.5.1 version of jQuery. If you reference the latest jQuery then you don’t need to change the code every time the new version of jQuery is released.

To achieve this you have to use following code
<script type=”text/javascript”
src=”http://code.jquery.com/jquery-latest.min.js”>
</script>

This code will always reference the latest version of jQuery in your page.

20) What is resize() function in jQuery?

The resize() function is called whenever the browser size is changed. This event can be only used with $(window).

Syntax:

.resize([event_data], handler(event_object))

-The “event_data” is the data to be sent to the handler.
-The “handler(event_object)” is a function to be called each time when the window is resized.

For example

$(window).resize(function() {
$(‘#message).text(‘window is resized to ‘ + $(window).width() + ‘x’ + $(window).height());
});

Here we will discuss the basics of HTML5 document. Today HTML5 is one of the most exciting buzz in web circles. Actaully HTML5 is the new standard for HTML.

it is still a work in progress. However, the major browsers support many of the new HTML5 elements and APIs but not all.

Rules for HTML5:
New features of HTML5 should be based on HTML, CSS, DOM, and JavaScript
Reduce the need for external plugins (like Flash)
Better error handling
More markup to replace scripting
HTML5 should be device independent
The development process should be visible to the public

The HTML5 <!DOCTYPE>:
In HTML5 there is only one <!DOCTYPE> declaration:

<!DOCTYPE html>
HTML5 required tags:
There is This is a HTML5 document with required tags:

<!DOCTYPE html>
<html>
<head>
<title>Here Title of the document</title>
</head>
<body>
Here The content of the document……
</body>
</html>
HTML5 – New Features:
HTML5 has few very exciting and interesting features. below is the few major features are given…

The <canvas> element for 2D drawing
The <video> and <audio> elements for media playback
Support for local storage
New content-specific elements, like <article>, <footer>, <header>, <nav>, <section>
New form controls, like calendar, date, time, email, url, search
Browser Support for HTML5

HTML5 is not officialy accepted by all browsers as it is not official standard for all brpwsers.

But all major browsers like (Safari, Chrome, Firefox, Opera, Internet Explorer) continue to add new HTML5 features to their latest versions.
Q 1- What is the difference between HTML and HTML5 ?
Ans: HTML5 is nothing more then upgraded version of HTML where in HTML5 Lot of new future like Video, Audio/mp3, date select function , placeholder , Canvas, 2D/3D Graphics, Local SQL Database added so that no need to do external plugin like Flash player or other library

Q 2- What is the <!DOCTYPE> ? Is it necessary to use in HTML5 ?
Ans: The <!DOCTYPE> is an instruction to the web browser about what version of HTML the page is written in. AND The <!DOCTYPE> tag does not have an end tag and It is not case sensitive.

The <!DOCTYPE> declaration must be the very first thing in HTML5 document, before the <html> tag. As In HTML 4.01, all <! DOCTYPE > declarations require a reference to a Document Type Definition (DTD), because HTML 4.01 was based on Standard Generalized Markup Language (SGML). WHERE AS HTML5 is not based on SGML, and therefore does not require a reference to a Document Type Definition (DTD).

Q 3- How many New Markup Elements you know in HTML5
Ans: Below are the New Markup Elements added in HTML5

Tag Description
<article> Specifies independent, self-contained content, could be a news-article, blog post, forum post,
or other articles which can be distributed independently from the rest of the site.
<aside> For content aside from the content it is placed in. The aside content should
be related to the surrounding content
<bdi> For text that should not be bound to the text-direction of its parent elements
<command> A button, or a radiobutton, or a checkbox
<details> For describing details about a document, or parts of a document
<summary> A caption, or summary, inside the details element
<figure> For grouping a section of
stand-alone content, could be a video
<figcaption> The caption of the figure section
<footer> For a footer of a document or section, could include the name of the author, the
date of the document, contact information, or copyright information
<header> For an introduction of a document or section, could include navigation
<hgroup> For a section of headings, using <h1> to <h6>, where the largest is the main
heading of the section, and the others are sub-headings
<mark> For text that should be highlighted
<meter> For a measurement, used only if the maximum and minimum values are known
<nav> For a section of navigation
<progress> The state of a work in progress
<ruby> For ruby annotation (Chinese notes or characters)
<rt> For explanation of the ruby annotation
<rp> What to show browsers that do not support the ruby element
<section> For a section in a document. Such as chapters, headers, footers, or any
other sections of the document
<time> For defining a time or a date, or both
<wbr> Word break. For defining a line-break opportunity.
Q 4- What are the New Media Elements in HTML5? is canvas element used in HTML5
Ans: Below are the New Media Elements have added in HTML5

Tag Description
<audio> For multimedia content, sounds, music or other audio streams
<video> For video content, such as a movie clip or other video streams
<source> For media resources for media elements, defined inside video or audio
elements
<embed> For embedded content, such as a plug-in
<track> For text tracks used in mediaplayers
yes we can use Canvas element in html5 like <canvas></canvas>

Q 5- Do you know New Input Type Attribute in HTML5

Ans: Yes we can use below new input type Attribute in HTML5

Type Value
tel The input is of type telephone number
search The input field is a search field
url a URL
email One or more email addresses
datetime A date and/or time
date A date
month A month
week A week
time The input value is of type time
datetime-local A local date/time
number A number
range A number in a given range
color A hexadecimal color, like #82345c
placeholder Specifies a short hint that describes the expected value of an input field
Q 6- How to add video and audio in HTML5
Ans: The canvas element is used to draw graphics images on a web page by using javascript like below

Like below we can add video in html5

<video width=“320? height=“240? controls=“controls”>
<source src=“mysong.mp4? type=“video/mp4? />
<source src=“mysong.ogg” type=“video/ogg” />
</video>
And audio like this

<audio controls=“controls”>
<source src=“mysong.ogg” type=“audio/ogg” />
<source src=“mysong.mp3? type=“audio/mpeg” />
</audio>
Q 7- What is the use of localStorage in HTML5?
Ans: Before HTML5 LocalStores was done with cookies. Cookies are not very good for large amounts of data, because they are passed on by every request to the server, so it was very slow and in-effective.

In HTML5, the data is NOT passed on by every server request, but used ONLY when asked for. It is possible to store large amounts of data without affecting the website’s performance.and The data is stored in different areas for different websites, and a website can only access data stored by itself.

And for creating localstores just need to call localStorage object like below we are storing name and address

<script type=“text/javascript”>
localStorage.name=“PHPZAG”;
document.write(localStorage.name);
</script>
<script type=“text/javascript”>
localStorage.address=“Newyork USA”;
document.write(localStorage.address);
</script>
Q 8- What is the sessionStorage Object in html5 ? How to create and access?
Ans: The sessionStorage object stores the data for one session. The data is deleted when the user closes the browser window. like below we can create and access a sessionStorage here we created “name” as session

<script type=“text/javascript”>
sessionStorage.name=SMARTWEBTUT;
document.write(sessionStorage.name);
</script>
Q 9- What the use of Canvas Element in HTML5?
Ans: The canvas element is used to draw graphics images on a web page by using javascript like below

<canvas id=“smartCanvas” width=“500? height=“400?>
</canvas>
<script type=“text/javascript”>
var smartCanvas=document.getElementById(“smartwebCanvas”);
var smartText=smartCanvas.getContext(“2d”);
pcdsText.fillStyle=“#82345c”;
pcdsText.fillRect(0,0,150,75);
</script>
Q 10- What purpose does HTML5 serve?
Ans: HTML5 is the proposed next standard for HTML 4.01, XHTML 1.0 and DOM Level 2 HTML. It aims to reduce the need for proprietary plug-in-based rich internet application (RIA) technologies such as Adobe Flash, Microsoft Silverlight, Apache Pivot, and Sun JavaFX.

Q 11- What is the difference between HTMl5 Application cache and regular HTML browser cache?
Ans: HTML5 specification allows browsers to prefetch some or all of a website assets such as HTML files, images, CSS, JavaScript, and so on, while the client is connected. It is not necessary for the user to have accessed this content previously, for fetching this content. In other words, application cache can prefetch pages that have not been visited at all and are thereby unavailable in the regular browser cache. Prefetching files can speed up the site’s performance, though you are of course using bandwidth to download those files initially.

Q 12- HOW DO YOU PLAY A AUDIO USING HTML5?
Ans:
We can display audio using the tag as shown below:

<audio controls=“controls”>
<source src=“test.mp3? type=“audio/mp3? />
</audio>
Q 13- WHAT ARE THE DIFFERENT TYPES OF STORAGE IN HTML5?
Ans:

HTML5 offers two new objects for storing data on the client:

LocalStorage – stores data with no time limit

<script type=“text/javascript”>
localStorage.lastname=“ZAG”;
document.write(localStorage.lastname);
</script>
SessionStorage – stores data for one session.The data is deleted when the user closes the browser window.

<script type=“text/javascript”>
sessionStorage.lastname=“ZAG”;
document.write(sessionStorage.lastname);
</script>
Q 14- HOW DO YOU PLAY A VIDEO USING HTML5?
Ans:
We can display video using the tag as shown below:

<video width=“320? height=“240? controls=“controls”>
<source src=“test.mp4? type=“video/mp4? />
</video>
Q 15- WHAT ARE THE NEW APIS PROVIDED BY THE HTML 5 STANDARD? GIVE A BRIEF DESCRIPTION OF EACH?
Ans:
The canvas element: Canvas consists of a drawable region defined in HTML code with height and width attributes. JavaScript code may access the area through a full set of drawing functions similar to other common 2D APIs, thus allowing for dynamically generated graphics. Some anticipated uses of the canvas include building graphs, animations, games, and image composition.

Timed media playback
Offline storage database
Document editing
Drag-and-drop
Cross-document messaging
Browser history management
MIME type and protocol handler registration
Q 16- WHAT OTHER ADVANTAGES DOES HTML5 HAVE?
Ans:
a) Cleaner markup
b) Additional semantics of new elements like <header>, <nav>, and <time>
c) New form input types and attributes that will (and in Opera’s case, do) take the hassle out of scripting forms.

Q 17- GIVE AN EXAMPLE OF NEW ELEMENTS IN HTML5 TO SUPPORT MULTIMEDIA AND GRAPHICS?
Ans: HTML5 introduced many elements such as , instead of to support multimedia.
Q 18- WHAT IS HTML5?
Ans: HTML5 is the latest version of HTML standard supporting multimedia and graphical content.
Q 19- WHAT IS THE DIFFERENCE BETWEEN HTML5 APPLICATION CACHE AND REGULATE HTML BROWSER CACHE?
Ans:
The new HTML5 specification allows browsers to prefetch some or all of a website assets such as HTML files, images, CSS, JavaScript, and so on, while the client is connected. It is not necessary for the user to have accessed this content previously, for fetching this content. In other words, application cache can prefetch pages that have not been visited at all and are thereby unavailable in the regular browser cache. Prefetching files can speed up the site’s performance, though you are of course using bandwidth to download those files initially.

Q 20- WHAT PURPOSE DOES HTML5 SERVE?
Ans:
HTML5 is the proposed next standard for HTML 4.01, XHTML 1.0 and DOM Level 2 HTML. It aims to reduce the need for proprietary plug-in-based rich internet application (RIA) technologies such as Adobe Flash, Microsoft Silver light, Apache Pivot, and Sun JavaFX.

Q 21 – WHAT IS THE STATUS OF THE DEVELOPMENT OF THE HTML 5 STANDARD?
Ans: HTML5 is being developed as the next major revision of HTML (HyperText Markup Language), the core markup language of the World Wide Web. The Web Hypertext Application Technology Working Group (WHATWG) started work on the specification in June 2004 under the name Web Applications 1.0.[1] As of March 2010[update], the specification is in the Draft Standard state at the WHATWG, and in Working Draft state at the W3C.

PHP interview questions and answers on advance and basic PHP and MySql with example for jobs in IT so this page for both freshers and 1 to 3 year experienced condidate it covered file system, PHP email, string fuctions, header functions, pear clasess and library, regular expression , array sorting, PHP date format, CURL, PayPal Integration, Shoping cart, PHP Memcache and php framework like Zend framework, Symfony, CodeIgniter and Yii frameworks from PHP4 to PHP6 etc means all type of PHP questions covered under this page.

Q. Who is the father of PHP ?

A. Rasmus Lerdorf is known as the father of PHP.
Q. What is the difference between $name and $$name?

A. $name is variable where as $$name is reference variable like $name=sonia and $$name=singh so $sonia value is singh.

Q. How can we submit a form without a submit button?
A. Java script submit() function is used for submit form without submit button on click call document.formname.submit()
Q. In how many ways we can retrieve the data in the result set of MySQL using PHP?

A. We can do it by 4 Ways
1. mysql_fetch_row. , 2. mysql_fetch_array , 3. mysql_fetch_object 4. mysql_fetch_assoc
Q. What is the difference between mysql_fetch_object and mysql_fetch_array?

A. mysql_fetch_object() is similar tomysql_fetch_array(), with one difference – an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).
Q. What are the differences between Get and post methods.

A. There are some defference between GET and POST method
1. GET Method have some limit like only 2Kb data able to send for request But in POST method unlimited data can we send
2. when we use GET method requested data show in url but Not in POST method so POST method is good for send sensetive request
Q. How can we extract string “smartwebtutorials.com ” from a string “http://prasanthia1985@smartwebtutorials.com using regular expression of PHP?

A. preg_match(“/^http:\/\/.+@(.+)$/”,”http://prasanthia1985@smartwebtutorials.com”,$matches);
echo $matches[1];
Q. How can we create a database using PHP and MySQL?

A. We can create MySQL database with the use of mysql_create_db(“Database Name”)
Q. What are the differences between require and include?

A. Both include and require used to include a file but when included file not found; Include send Warning where as Require send Fatal Error .
Q. Can we use include (“xyz.PHP”) two times in a PHP page “index.PHP”?

A. Yes we can use include(“xyz.php”) more than one time in any page. but it create a prob when xyz.php file contain some funtions declaration then error will come for already declared function in this file else not a prob like if you want to show same content two time in page then must incude it two time not a prob
Q. What are the different tables(Engine) present in MySQL, which one is default?

A. Following tables (Storage Engine) we can create
1. MyISAM(The default storage engine IN MYSQL Each MyISAM table is stored on disk in three files. The files have names that begin with the table name and have an extension to indicate the file type. An .frm file stores the table format. The data file has an .MYD (MYData) extension. The index file has an .MYI (MYIndex) extension. )
2. InnoDB(InnoDB is a transaction-safe (ACID compliant) storage engine for MySQL that has commit, rollback, and crash-recovery capabilities to protect user data.)
3. Merge
4. Heap (MEMORY)(The MEMORY storage engine creates tables with contents that are stored in memory. Formerly, these were known as HEAP tables. MEMORY is the preferred term, although HEAP remains supported for backward compatibility. )
5. BDB (BerkeleyDB)(Sleepycat Software has provided MySQL with the Berkeley DB transactional storage engine. This storage engine typically is called BDB for short. BDB tables may have a greater chance of surviving crashes and are also capable of COMMIT and ROLLBACK operations on transactions)
6. EXAMPLE
7. FEDERATED (It is a storage engine that accesses data in tables of remote databases rather than in local tables. )
8. ARCHIVE (The ARCHIVE storage engine is used for storing large amounts of data without indexes in a very small footprint. )
9. CSV (The CSV storage engine stores data in text files using comma-separated values format.)
10. BLACKHOLE (The BLACKHOLE storage engine acts as a “black hole” that accepts data but throws it away and does not store it. Retrievals always return an empty result)
Q. What is use of header() function in php ?

A. The header() function sends a raw HTTP header to a client.We can use herder() function for redirection of pages. It is important to notice that header() must be called before any actual output is seen..
Q. How can I execute a PHP script using command line?

A. Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument.
Q. Suppose your Zend engine supports the mode Then how can you configure your PHP Zend engine to support mode ?

A. In php.ini file:
set
short_open_tag=on
to make PHP support
Q. Shopping cart online validation i.e. how can we configure Paypal, etc.?

A. Nothing more we have to do only redirect to the payPal url after submit all information needed by paypal like amount,adresss etc.
Q. What is meant by nl2br()?

A. Inserts HTML line breaks (
) before all newlines in a string.
Q. What is htaccess? Why do we use this and Where?

A. .htaccess files are configuration files of Apache Server which provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all
subdirectories thereof.
Q. How we get IP address of client, previous reference page etc ?

A. By using $_SERVER[‘REMOTE_ADDR’],$_SERVER[‘HTTP_REFERER’] etc.
Q. What are the reasons for selecting lamp (Linux, apache, MySQL, PHP) instead of combination of other software programs, servers and
operating systems?

A. All of those are open source resource. Security of Linux is very very more than windows. Apache is a better server that IIS both in functionality and security. MySQL is world most popular open source database. PHP is more faster that asp or any other scripting language.
Q. How can we encrypt and decrypt a data present in a MySQL table using MySQL?

A. AES_ENCRYPT () and AES_DECRYPT ()
Q. How can we encrypt the username and password using PHP?

A. The functions in this section perform encryption and decryption, and
compression and uncompression:
encryption decryption
AES_ENCRYT() AES_DECRYPT()
ENCODE() DECODE()
DES_ENCRYPT() DES_DECRYPT()
ENCRYPT() Not available
MD5() Not available
OLD_PASSWORD() Not available
PASSWORD() Not available
SHA() or SHA1() Not available
Not available UNCOMPRESSED_LENGTH()
Q. What are the features and advantages of object-oriented programming?

A. One of the main advantages of OO programming is its ease of modification; objects can easily be modified and added to a system there by reducing maintenance costs. OO programming is also considered to be better at modeling the real world than is procedural programming. It allows for more complicated and flexible interactions. OO systems are also easier for non-technical personnel to understand and easier for them to participate in the maintenance and enhancement of a system because it appeals to natural human cognition patterns. For some systems, an OO approach can speed development time since many objects are standard across systems and can be reused. Components that manage dates, shipping, shopping carts, etc. can be purchased and easily modified for a specific system
Q. What are the differences between procedure-oriented languages and object-oriented languages?

A. There are lot of difference between procedure language and object oriented like below
1>Procedure language easy for new developer but complex to understand whole software as compare to object oriented model
2>In Procedure language it is difficult to use design pattern mvc , Singleton pattern etc but in OOP you we able to develop design pattern
3>IN OOP language we able to ree use code like Inheritance ,polymorphism etc but this type of thing not available in procedure language on that our Fonda use COPY and PASTE .
Q. What is the use of friend function?

A. Sometimes a function is best shared among a number of different classes. Such functions can be declared either as member functions of one class or as global functions. In either case they can be set to be friends of other classes, by using a friend specifier in the class that is admitting them. Such functions can use all attributes of the class which names them as a friend, as if they were themselves members of that class. A friend declaration is essentially a prototype for a member function, but instead of requiring an implementation with the name of that class attached by the double colon syntax, a global function or member function of another class provides the match.
Q. What are the differences between public, private, protected, static, transient, final and volatile?

A. Public: Public declared items can be accessed everywhere.
Protected: Protected limits access to inherited and parent classes (and to the class that defines the item).
Private: Private limits visibility only to the class that defines the item.
Static: A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.
Final: Final keyword prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.
transient: A transient variable is a variable that may not be serialized.
volatile: a variable that might be concurrently modified by multiple threads should be declared volatile.
Variables declared to be volatile will not be optimized by the compiler because their value can change at any time.
Q. What are the different types of errors in PHP?

A. Three are three types of errors:
1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all although, as you will see, you can change this default behavior.
2. Warnings: These are more serious errors for example, attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.
3. Fatal errors: These are critical errors for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP’s default behavior is to display them to the user when they take place.
Q. What is the functionality of the function strstr and stristr?

A. strstr Returns part of string from the first occurrence of needle(sub string that we finding out ) to the end of string.
$email= ‘prasanthia1985@gmail.com’;
$domain = strstr($email, ‘@’);
echo $domain; // prints @gmail.com
here @ is the needle
stristr is case-insensitive means able not able to diffrenciate between a and A
Q. What are the differences between PHP 3 and PHP 4 and PHP 5?

A. There are lot of difference among these three version of php
1>Php3 is oldest version after that php4 came and current version is php5 (php5.3) where php6 have to come
2>Difference mean oldest version have less functionality as compare to new one like php5 have all OOPs concept now where as php3 was pure procedural language constructive like C
In PHP5 1. Implementation of exceptions and exception handling
2. Type hinting which allows you to force the type of a specific argument
3. Overloading of methods through the __call function
4. Full constructors and destructors etc through a __constuctor and __destructor function
5. __autoload function for dynamically including certain include files depending on the class you are trying to create.
6 Finality : can now use the final keyword to indicate that a method cannot be overridden by a child. You can also declare an entire class as final which prevents it from having any children at all.
7 Interfaces & Abstract Classes
8 Passed by Reference :
9 An __clone method if you really want to duplicate an object
Q. How can we convert asp pages to PHP pages?

A. there are lots of tools available for asp to PHP conversion. you can search Google for that. the best one is available athttp://asp2php.naken.cc./
Q. What is the functionality of the function htmlentities?

A. 30 Convert all applicable characters to HTML entities This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.
Q. How can we get second of the current time using date function?

A. $second = date(“s”);
Q. How can we convert the time zones using PHP?

A. By using date_default_timezone_get and date_default_timezone_set function on PHP 5.1.0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Discover what 8am in Tokyo relates to on the East Coast of the US

// Set the default timezone to Tokyo time:
date_default_timezone_set(‘Asia/Tokyo’);

// Now generate the timestamp for that particular timezone, on Jan 1st, 2013
$stamp = mktime(8, 0, 0, 1, 1, 2000);

// Now set the timezone back to US/Eastern
date_default_timezone_set(‘US/Eastern’);

// Output the date in a standard format (RFC1123), this will print:
// Mon, 31 Dec 2012 18:00:00 EST
echo ‘<p>’ . date(DATE_RFC1123, $stamp) . ‘</p>’
Q. What is meant by urlencode and urldocode?

A. URLencode returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type. urldecode decodes any %## encoding in the given string.
Q. What is the difference between the functions unlink and unset?

A. unlink() deletes the given file from the file system. unset() makes a variable undefined.
Q. How can we register the variables into a session?

A. $_SESSION[‘name’] = “smart”;
Q. How can we get the properties (size, type, width, height) of an image using PHP image functions?

A. To know the Image type use exif_imagetype () function
To know the Image size use getimagesize () function
To know the image width use imagesx () function
To know the image height use imagesy() function t
Q. How can we get the browser properties using PHP?

A. By using $_SERVER[‘HTTP_USER_AGENT’] variable.
Q. What is the maximum size of a file that can be uploaded using PHP and how can we change this?

A. By default the maximum size is 2MB. and we can change the following setup at php.ini
upload_max_filesize = 2M
Q. How can we increase the execution time of a PHP script?

A. by changing the following setup at php.ini
max_execution_time = 30;
Maximum execution time of each script, in seconds
Q. How can we take a backup of a MySQL table and how can we restore it. ?

A. To backup: BACKUP TABLE tbl_name[,tbl_name…] TO ‘/path/to/backup/directory’ RESTORE TABLE tbl_name[,tbl_name…] FROM ‘/path/to/backup/directory’mysqldump: Dumping Table Structure and DataUtility to dump a database or a collection of database for backup or
for transferring the data to another SQL server (not necessarily a MySQL server). The dump will contain SQL statements to create the table and/or
populate the table. -t, —no-create-info Don’t write table creation information (the CREATE TABLE statement). -d, —no-data Don’t write any row information for the table. This is very useful if you just want to get a dump of the structure for a table!
Q. How can we optimize or increase the speed of a MySQL select query?

A. first of all instead of using select * from table1, use select column1, column2, column3.. from table1 Look for the opportunity to introduce index in the table you are querying. use limit keyword if you are looking for any specific number of rows from the result set.
Q. How many ways can we get the value of current session id?

A. session_id() returns the session id for the current session.
Q. How can we destroy the session, how can we unset the variable of a session?

A. session_unregister – Unregister a global variable from the current session
session_unset – Free all session variables
Q. How can we set and destroy the cookie n php?

A. By using setcookie(name, value, expire, path, domain); function we can set the cookie in php ;
Set the cookies in past for destroy. like
setcookie(“user”, “smart”, time()+3600); for set the cookie
setcookie(“user”, “”, time()-3600); for destroy or delete the cookies;
Q. How many ways we can pass the variable through the navigation between the pages?

A. GET/QueryString, POST
Q. What is the difference between ereg_replace() and eregi_replace()?

A. eregi_replace() function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters.eregi_replace() function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters.
Q. What are the different functions in sorting an array?

A. Sort(), arsort(),
asort(), ksort(),
natsort(), natcasesort(),
rsort(), usort(),
array_multisort(), and
uksort().
Q. How can we know the count/number of elements of an array?

A. 2 ways
a) sizeof($urarray) This function is an alias of count()
b) count($urarray)
Q. what is session_set_save_handler in PHP?

A. session_set_save_handler() sets the user-level session storage functions which are used for storing and retrieving data associated with a session. This is most useful when a storage method other than those supplied by PHP sessions is preferred. i.e. Storing the session data in a local database.
Q. How can I know that a variable is a number or not using a JavaScript?

A. bool is_numeric ( mixed var)
Returns TRUE if var is a number or a numeric string, FALSE otherwise.or use isNaN(mixed var)The isNaN() function is used to check if a value is not a number.

Who is the Father or creater of JSON ?

Douglas Crockford called as the Father of JSON

What the file extension of JSON

The JSON filename extension is .json.

What is The JSON(JavaScript Object Notation) ?

JavaScript Object Notation(JSON) is a lightweight text-based open standard designed for human-readable data interchange. It is derived from the JavaScript programming language for representing simple data structures and associative arrays, called objects. And JSON is language-independent, with parsers available for virtually every programming language. Uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python,php The JSON format is often used for serializing and transmitting structured data over a network connection. When third party data interchane(REST Services) then JSON may used there LIKE SHOP .It is primarily used to transmit data between a server and web application, serving as an alternative to XML.

Do you know JSON Tools for Java Developer

Ya some of JSON tool for java developer is • Parser Parse JSON text files and convert these to a Java model • Renderer Render a Java representation into text • Serializer Serialize plain POJO clusters to a JSON representation • Validator Validate the contents of a JSON file using a JSON schema JSONObject Java Class • A JSONObject is an unordered collection of name/value pairs • The put methods adds a name/value pair to an object • The texts produced by the toString methods strictly conform to the JSON syntax rules myString = new JSONObject().put(“JSON”, “Hello, World!”).toString(); // myString is {“JSON”: “Hello, World”}

Why Use JSON over XML

Lighter and faster than XML as on-the-wire data format • JSON objects are typed while XML data is typeless JSON types: string, number, array, boolean, XML data are all string • Native data form for JavaScript code Data is readily accessible as JSON objects in your JavaScript code vs. XML data needed to be parsed and assigned to variables through tedious DOM APIs Retrieving values is as easy as reading from an object property in your JavaScript code

Explain JSON Structures

A collection of name/value pairs In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array • An ordered list of values In most languages, this is realized as an array, vector, list, or sequence • These are universal data structures supported • A JSON object is an unordered set of name/value pairs • A JSON object begins with { (left brace) and ends with } (right brace) • Each name is followed by : (colon) and the name/value pairs are separated by , (comma)

Compare JSON with JavaScript

JSON is a subset of the object literal notation of JavaScript > JSON can be used in the JavaScript language with no muss or fuss Example: JSON Object var myJSONObject = {“bindings”: [ {“ircEvent”: “PRIVMSG”, “method”: “newURI”, “regex”: “^http://.*”}, {“ircEvent”: “PRIVMSG”, “method”: “deleteURI”, “regex”: “^delete.*”}, {“ircEvent”: “PRIVMSG”, “method”: “randomURI”, “regex”: “^random.*”} ] }; • In this example, a JSON JavaScript object is created containing a single member “bindings”, which contains an array containing three objects, each containing “ircEvent”, “method”, and “regex” members • Members can be retrieved using dot or subscript operators myJSONObject.bindings[0].method // “newURI” Text to Object Conversion in JavaScript code var myObject = eval(‘(‘ + myJSONtext + ‘)’); • To convert a JSON text into an JSON object, use the eval() function > eval() invokes the JavaScript compiler > Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure

what the Security and JSON Parser

Security and JSON Parser to understand by below examples // Include http://www.json.org/json.js var myObject = myJSONtext.parseJSON(); • eval() can compile and execute any JavaScript program, so there can be security issues (cross-site scripting) Use eval() when the source can be trusted • When security is a concern – the source cannot be trusted -, it is better to use a JSON parser A JSON parser will only recognize JSON text and so is much safer Object to Text Conversion var myJSONText = myObject.toJSONString(); • You can convert JSON object into JSON text • JSON does not support cyclic data structure Do not give cyclical structures to the JSON stringifier

How to Generate or Send JSON Data at the Server Side

Create JSONObject Java object • Add name and value pairs using put method • Convert it to String type using toString method and send it to the client with content-type as “text/xml” or “text/plain” myString = new JSONObject().put(“JSON”, “Hello, World!”).toString(); // myString is {“JSON”: “Hello, World”}

How to Receive JSON Data at the Server Side

Read the JSON data as a String type • Create JSONObject Java object from the string String json = readJSONStringFromRequestBody(request); //Use the JSON-Java binding library to create a JSON object in Java JSONObject jsonObject = null; try { jsonObject = new JSONObject(json); } catch(ParseException pe) { }

How to Receive JSON Data at the Client Side

JSON data is received as a string • Calling eval() will generate JSON object in JavaScript code > var JSONdata = eval(req.responseText); • Once you have JSON object, you can use . notation to access its properties > var name = JSONdata.name; > var address = JSONdata.addresses[3]; > var streetname = JSONdata.addresses[3].street;

How to Generate/Send JSON Data at the Client Side

Create JSON JavaScript object • Use “POST” HTTP method in the open method of the XMLHttpRequest object • Pass JSON JavaScript object in the send method of XMLHttpRequest object var carAsJSON = JSON.stringify(car); var url = “JSONExample?timeStamp=” + new Date().getTime(); createXMLHttpRequest(); xmlHttp.open(“POST”, url, true); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”); xmlHttp.send(carAsJSON);

Explain JSON WITH PHP

Json is too much easy with php There is no installation needed to use these functions; they are part of the PHP core. nothing more need to know just only use { ,[ and create json format string and use three php function json_encode() to get JSON representation of a value, json_decode() for Decodes a JSON string, ¦json_last_error() to get the last error occurred in process.

write your desire string in below format and use php funtions :

$string='{ “firstName”: “JSON”,
“lastName”: “Dev”,
“age”: 26,
“address”: {
“streetAddress”: “Thane “,
“city”: “Mumbai”,
“state”: “maharshtra”,
“postalCode”: “401107”
}, “phoneNumber”: [
{ “type”: “home”, “number”: “022 333-1234” },
{ “type”: “fax”, “number”: “022 444-4567” }
] }’;
$decodeString = json_decode($string);
echo ‘First Name – ‘.$decode->{“firstName”};
echo ‘Last Name – ‘.$decode->{“lastName”};
echo ‘Address – ‘.$decode->{“address”}->{“streetAddress”};
Out put : Print below
First Name – JSON
Last Name – PHP
Address – Thane