Magento Interview Questions and 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();

 21-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 andconfiguration-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’).

For diagramatic view: click here (courtsey: Alan Storm)

22 =How Magento ORM works?

ORM stands for Object Relational Mapping. It’s a programming technique used to convert different types of data to Objects and vice versa.

In Magento, ORM is shown as Model (based on Zend Framework’s Zend_Db_Adapter), which further breaks down to two types of Models.

– First is the “simple” i.e. Regular Models which is nothing but flat table or our regular table structure.
– Second Model is EAV (Entity Attribute Value), which is quite complicated and expensive to query.

All Magento Models interacting with database are inherited from Mage_Core_Model_Abstract class, which is further inherited from Varien_Object.

Difference between two Models is, Simple Model is inherited from Mage_Core_Model_Resource_Db_Abstract class,
while EAV is inherited from Mage_Eav_Model_Entity_Abstract.

For those who don’t know what EAV is, please read my 3rd answer below.

So, to end up this question,
when you want to get some data in Magento, you call it like this:

Mage::getModel(‘module/model’)>load(1);

where 1 is the primary key id for some Regular/Simple table, while in EAV so many tables are joined to fetch just single row of data.

23. What is EAV in Magento?

EAV, stands for Entity Attribute Value, is a technique which allows you to add unlimited columns to your table virtually. Means, the fields which is represented in “column” way in a regular table, is represented in a “row” (records) way in EAV. In EAV, you have one table which holds all the “attribute” (table field names) data, and other tables which hold the “entity” (id or primary id) and value (value for that id) against each attribute.

In Magento, there is one table to hold attribute values called eav_attribute and 5-6 tables which holds entity and data in fully normalized form,

– eav_entity, eav_entity_int (for holding Integer values),
– eav_entity_varchar (for holding Varchar values),
– eav_entity_datetime (for holding Datetime values),
– eav_entity_decimal (for holding Decimal/float values),
– eav_entity_text (for holding text (mysql Text type) values).

EAV is expensive and should only be used when you are not sure about number of fields in a table which can vary in future. To just get one single record, Magento joins 4-5 tables to get data in EAV. But this doesn’t mean that EAV only has drawbacks. The main advantage of EAV is when you may want to add table field in future, when there are thousands or millions of records already present in your table. In regular table, if you add table field with these amount of data, it will screw up your table, as for each empty row also some bytes will be allocated as per data type you select. While in EAV, adding the table column will not affect the previously saved records (also the extra space will not get allocated!) and all the new records will seamlessly have data in these columns without any problem.

24. Difference between Mage::getSingleton() and Mage::getModel()

The difference between Mage:getSingleton() and Mage::getModel() is that the former one does not create an object if the object for same class is already created, while the later creates new objects every time for the class when it’s called.

Mage::getSingleton() uses the “singleton design pattern” of PHP. If the object is not created, it will create it.

Mage::getSingleton() is mostly used when you want to create an object once, modify it and later fetch from it. Popular example is session, you first create a session object, and then add/remove values from session across different pages, so that it retains your values (e.g. cart values, logged in customer details, etc.) and doesn’t create new session object losing your last changes.

Mage::getModel() is used when you want to have the fresh data from the database. Example is when you want to show records from database.

0

Fresher Question & Answer4

Fresher Quesition & Answer4

Explain Normalization concept?

The normalization process involves getting our data to conform to three progressive normal forms, and a higher level of normalization cannot be achieved until the previous levels have been achieved (there are actually five normal forms, but the last two are mainly academic and will not be discussed).First Normal FormThe First Normal Form (or 1NF) involves removal of redundant data from horizontal rows. We want to ensure that there is no duplication of data in a given row, and that every column stores the least amount of information possible (making the field atomic).Second Normal FormWhere the First Normal Form deals with redundancy of data across a horizontal row, Second Normal Form (or 2NF) deals with redundancy of data in vertical columns. As stated earlier, the normal forms are progressive, so to achieve Second Normal Form, your tables must already be in First Normal Form.Third Normal Form
I have a confession to make; I do not often use Third Normal Form. In Third Normal Form we are looking for data in our tables that is not fully dependant on the primary key, but dependant on another value in the table.

How can we find the number of rows in a table using MySQL?

Use this for mysql
>SELECT COUNT(*) FROM table_name;

How can we find the number of rows in a result set using PHP?

$result = mysql_query($sql, $db_link);
$num_rows = mysql_num_rows($result);
echo “$num_rows rows found”;

How many ways we can we find the current date using MySQL?

SELECT CURDATE();
CURRENT_DATE() = CURDATE()
for time use
SELECT CURTIME();
CURRENT_TIME() = CURTIME()

What are the advantages and disadvantages of Cascading Style Sheets?

External Style SheetsAdvantagesCan control styles for multiple documents at once. Classes can be created for use on multiple HTML element types in many documents.Selector and grouping methods can be used to apply styles under complex
contextsDisadvantagesAn extra download is required to import style information for each document The rendering of the document may be delayed until the external style sheet is loaded Becomes slightly unwieldy for small quantities of
style definitionsEmbedded Style Sheets
Advantages
Classes can be created for use on multiple tag types in the document. Selector and grouping methods can be used to apply styles under complex contexts. No additional downloads necessary to receive style information
Disadvantages
This method can not control styles for multiple documents at once
Inline Styles
Advantages
Useful for small quantities of style definitions. Can override other style specification methods at the local level so only exceptions need to be listed in conjunction with other style methods
Disadvantages
Does not distance style information from content (a main goal of SGML/HTML). Can not control styles for multiple documents at once. Author can not create or control classes of elements to control multiple element types within the document. Selector grouping methods can not be used to create complex element addressing scenarios.

What type of inheritance that PHP supports?

In PHP an extended class is always dependent on a single base class, that is, multiple inheritance is not supported. Classes are extended using the keyword ‘extends’.

What is the difference between Primary Key and Unique key?

Primary Key: A column in a table whose values uniquely identify the rows in the table. A primary key value cannot be NULL.

Unique Key: Unique Keys are used to uniquely identify each row in the table. There can be one and only one row for each unique key value. So NULL can be a unique key.There can be only one primary key for a table but there can be more than one unique for a table.

what is garbage collection? default time ? refresh time?

Garbage Collection is an automated part of PHP , If the Garbage Collection process runs, it then analyzes any files in the /tmp for any session files that have not been accessed in a certain amount of time and physically deletes them. Garbage Collection process only runs in the default session save directory, which is /tmp. If you opt to save your sessions in a different directory, the Garbage Collection process will ignore it. the Garbage Collection process does not differentiate between which sessions belong to whom when run. This is especially important note on shared web servers. If the process is run, it deletes ALL files that have not been accessed in the directory. There are 3 PHP.ini variables, which deal with the garbage collector: PHP ini value name default session.gc_maxlifetime 1440 seconds or 24 minutes session.gc_probability 1 session.gc_divisor 100

What are the advantages/disadvantages of MySQL and PHP?

Both of them are open source software (so free of cost), support cross platform. php is faster then ASP and JSP.

What is the difference between GROUP BY and ORDER BY in Sql?

ORDER BY [col1],[col2],¦,[coln]; Tels DBMS according to what columns it should sort the result. If two rows will hawe the same value in col1 it will try to sort them according to col2 and so on.GROUP BY [col1],[col2],¦,[coln]; Tels DBMS to group results with same value of column col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, if
you want to count all items in group, sum all values or view average

What is the difference between char and varchar data types?

Set char to occupy n bytes and it will take n bytes even if u r storing a value of n-m bytes Set varchar to occupy n bytes and it will take only the required space and will not use the n bytes eg. name char(15) will waste 10 bytes if we store ‘romharshan’, if each char takes a byte eg. name varchar(15) will just use 5 bytes if we store ‘romharshan’, if each char takes a byte. rest 10 bytes will be free.

What is the functionality of md5 function in PHP?

Calculate the md5 hash of a string. The hash is a 32-character hexadecimal number. I use it to generate keys which I use to identify users etc. If I add random no techniques to it the md5 generated now will be totally different for the same string I am using.

How can I load data from a text file into a table?

you can use LOAD DATA INFILE file_name; syntax to load data from a text file. but you have to make sure thata) data is delimited b) columns and data matched correctly

How can we know the number of days between two given dates using MySQL?

SELECT DATEDIFF(“2007-03-07″,”2005-01-01”);

How can we know the number of days between two given dates using PHP?

$date1 = date(“Y-m-d”);
$date2 = “2006-08-15”;
$days = (strtotime($date1) – strtotime($date2)) / (60 * 60 * 24);

How we load all classes that placed in different directory in one PHP File , means how to do auto load classes

by using spl_autoload_register(‘autoloader::funtion’);
Like below
class autoloader
{
public static function moduleautoloader($class)
{
$path = $_SERVER[‘DOCUMENT_ROOT’] . “/modules/{$class}.php”;
if (is_readable($path)) require $path;
}
public static function daoautoloader($class)
{
$path = $_SERVER[‘DOCUMENT_ROOT’] . “/dataobjects/{$class}.php”;
if (is_readable($path)) require $path;
}
public static function includesautoloader($class)
{
$path = $_SERVER[‘DOCUMENT_ROOT’] . “/includes/{$class}.php”;
if (is_readable($path)) require $path;
}
}
spl_autoload_register(‘autoloader::includesautoloader’);
spl_autoload_register(‘autoloader::daoautoloader’);
spl_autoload_register(‘autoloader::moduleautoloader’);

How many types of Inheritances used in PHP and how we achieve it

As far PHP concern it only support single Inheritance in scripting. we can also use interface to achieve multiple inheritance.

PHP how to know user has read the email?

Using Disposition-Notification-To: in mailheader we can get read receipt.
Add the possibility to define a read receipt when sending an email.
It quite straightforward, just edit email.php, and add this at vars definitions:
var $readReceipt = null;
And then, at createHeader function add:
if (!empty($this->readReceipt)) {
$this->__header .= ‘Disposition-Notification-To: ‘ . $this->__formatAddress($this->readReceipt) . $this->_newLine;
}

What are default session time and path?

default session time in PHP is 1440 seconds or 24 minutes Default session save path id temporary folder /tmp

how to track user logged out or not? when user is idle ?

By checking the session variable exist or not while loading th page. As the session will exist longer as till browser closes. The default behaviour for sessions is to keep a session open indefinitely and only to expire a session when the browser is closed. This behaviour can be changed in the php.ini file by altering the line session.cookie_lifetime = 0 to a value in seconds. If you wanted the session to finish in 5 minutes you would set this to session.cookie_lifetime = 300 and restart your httpd server.

how to track no of user logged in ?

whenever a user logs in track the IP, userID etc..and store it in a DB with a active flag while log out or sesion expire make it inactive. At any time by counting the no: of active records we can get the no: of visitors.

in PHP for pdf which library used?

The PDF functions in PHP can create PDF files using the PDFlib library With version 6, PDFlib offers an object-oriented API for PHP 5 in addition to the function-oriented API for PHP 4. There is also the » Panda module. FPDF is a PHP class which allows to generate PDF files with pure PHP, that is to say without using the PDFlib library. F from FPDF stands for Free: you may use it for any kind of usage and modify it to suit your needs. FPDF requires no extension (except zlib to activate compression and GD for GIF support) and works with PHP4 and PHP5.

for image work which library?

we will need to compile PHP with the GD library of image functions for this to work. GD and PHP may also require other libraries, depending on which image formats you want to work with.

what is design pattern? singleton pattern?

A design pattern is a general reusable solution to a commonly occurring problem in software design.
The Singleton design pattern allows many parts of a program to share a single resource without having to work out the details of the sharing themselves.

what are magic methods?

Magic methods are the members functions that is available to all the instance of class Magic methods always starts with “__”. Eg. __construct All magic methods needs to be declared as public To use magic method they should be defined within the class or program scope Various Magic Methods used in PHP 5 are: __construct() __destruct() __set() __get() __call() __toString() __sleep() __wakeup() __isset() __unset() __autoload() __clone()

what is magic quotes?

Magic Quotes is a process that automagically escapes ncoming data to the PHP script. It’s preferred to code with magic quotes off and to instead escape the data at runtime, as needed. This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.

what is cross site scripting? SQL injection?

Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications which allow code injection by malicious web users into the web pages viewed by other users. Examples of such code include HTML code and client-side scripts. SQL injection is a code injection technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed

what is URL rewriting?

Using URL rewriting we can convert dynamic URl to static URL Static URLs are known to be better than Dynamic URLs because of a number of reasons 1. Static URLs typically Rank better in Search Engines. 2. Search Engines are known to index the content of dynamic pages a lot slower compared to static pages. 3. Static URLs are always more friendlier looking to the End Users. along with this we can use URL rewriting in adding variables [cookies] to the URL to handle the sessions.

what is the major php security hole? how to avoid?

1. Never include, require, or otherwise open a file with a filename based on user input, without thoroughly checking it first.
2. Be careful with eval() Placing user-inputted values into the eval() function can be extremely dangerous. You essentially give the malicious user the ability to execute any command he or she wishes!
3. Be careful when using register_globals = ON It was originally designed to make programming in PHP easier (and that it did), but misuse of it often led to security holes
4. Never run unescaped queries
5. For protected areas, use sessions or validate the login every time.
6. If you don’t want the file contents to be seen, give the file a .php extension.

whether PHP supports Microsoft SQL server ?

The SQL Server Driver for PHP v1.0 is designed to enable reliable, scalable integration with SQL Server for PHP applications deployed on the Windows platform. The Driver for PHP is a PHP 5 extension that allows the reading and writing of SQL Server data from within PHP scripts. using MSSQL or ODBC modules we can access Microsoft SQL server.

what is MVC? why its been used?

Model-view-controller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages the communication of data and the business rules used to manipulate the data to and from the model. WHY ITS NEEDED IS 1 Modular separation of function 2 Easier to maintain 3 View-Controller separation means:
A Tweaking design (HTML) without altering code B — Web design staff can modify UI without understanding code

what is framework? how it works? what is advantage?

In general, a framework is a real or conceptual structure intended to serve as a support or guide for the building of something that expands the structure into something useful. Advantages : Consistent Programming Model Direct Support for Security Simplified Development Efforts Easy Application Deployment and Maintenance

what is CURL?

CURL means Client URL Library
curl is a command line tool for transferring files with URL syntax, supporting FTP, FTPS, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS and FILE. curl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate, kerberos…), file transfer resume, proxy tunneling and a busload of other useful tricks.
CURL allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP’s ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.

what is PDO ?

The PDO ( PHP Data Objects ) extension defines a lightweight, consistent interface for accessing databases in PHP. if you are using the PDO API, you could switch the database server you used, from say PgSQL to MySQL, and only need to make minor changes to your PHP code.

While PDO has its advantages, such as a clean, simple, portable API but its main disadvantage is that it doesn’t allow you to use all of the advanced features that are available in the latest versions of MySQL server. For example, PDO does not allow you to use MySQL’s support for Multiple Statements.
Just need to use below code for connect mysql using PDO
try {
$dbh = new PDO(“mysql:host=$hostname;dbname=databasename”, $username, $password);
$sql = “SELECT * FROM employee”;
foreach ($dbh->query($sql) as $row)
{
print $row[’employee_name’] .’ – ‘. $row[’employee_age’] ;
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}

What is PHP’s mysqli Extension?

The mysqli extension, or as it is sometimes known, the MySQL improved extension, was developed to take advantage of new features found in MySQL systems versions 4.1.3 and newer. The mysqli extension is included with PHP versions 5 and later.
The mysqli extension has a number of benefits, the key enhancements over the mysql extension being:
=>Object-oriented interface
=>Support for Prepared Statements
=>Support for Multiple Statements
=>Support for Transactions
=>Enhanced debugging capabilities
=>Embedded server support

0

Fresher Question & Answer3

Fresher Quesition & Answer3

How can we optimize or increase the speed of a MySQL select query?

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.

How many ways can we get the value of current session id?

session_id() returns the session id for the current session.

How can we destroy the session, how can we unset the variable of a session?

session_unregister Unregister a global variable from the current
session
session_unset Free all session variables

How can we set and destroy the cookie n php?

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”, “sonia”, time()+3600); for set the cookie
setcookie(“user”, “”, time()-3600); for destroy or delete the cookies;

How many ways we can pass the variable through the navigation

between the pages?
GET/QueryString
POST

What is the difference between ereg_replace() and eregi_replace()?

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.

What are the different functions in sorting an array?

Sort(), arsort(),
asort(), ksort(),
natsort(), natcasesort(),
rsort(), usort(),
array_multisort(), and
uksort().

How can we know the count/number of elements of an array?

2 ways
a) sizeof($urarray) This function is an alias of count()
b) count($urarray)

what is session_set_save_handler in PHP?

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.

How can I know that a variable is a number or not using a JavaScript?

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.

List out the predefined classes in PHP?

Directory
stdClass
__PHP_Incomplete_Class
exception
php_user_filter

How can I make a script that can be bi-language (supports English, German)?

You can maintain two separate language file for each of the language. all the labels are putted in both language files as variables and assign those variables in the PHP source. on runtime choose the required language option.

What are the difference between abstract class and interface?

Abstract class: abstract classes are the class where one or more methods are abstract but not necessarily all method has to be abstract. Abstract methods are the methods, which are declare in its class but not
define. The definition of those methods must be in its extending class.Interface: Interfaces are one type of class where all the methods are
abstract. That means all the methods only declared but not defined. All the methods must be define by its implemented class.

How can we send mail using JavaScript?

JavaScript does not have any networking capabilities as it is designed to work on client site. As a result we can not send mails using JavaScript. But we can call the client side mail protocol mailto via JavaScript to prompt for an email to send. this requires the client to approve it.

How can we repair a MySQL table?

The syntex for repairing a MySQL table is REPAIR TABLENAME, [TABLENAME, ], [Quick],[Extended] This command will repair the table specified if the quick is given the MySQL will do a repair of only the index tree if the extended is given it will create index row by row

What are the advantages of stored procedures, triggers, indexes?

A stored procedure is a set of SQL commands that can be compiled and stored in the server. Once this has been done, clients don’t need to keep re-issuing the entire query but can refer to the stored procedure.
This provides better overall performance because the query has to be parsed only once, and less information needs to be sent between the server and the client. You can also raise the conceptual level by having libraries of functions in the server. However, stored procedures of course do increase the load on the database server system, as more of
the work is done on the server side and less on the client (application) side.Triggers will also be implemented. A trigger is effectively a type of stored procedure, one that is invoked when a particular event occurs.
For example, you can install a stored procedure that is triggered each time a record is deleted from a transaction table and that stored procedure automatically deletes the corresponding customer from a customer table when all his transactions are deleted.Indexes are used to find rows with specific column values quickly.
Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows. The larger the table, the more this costs. If the table has an index for the columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data. If a
table has 1,000 rows, this is at least 100 times faster than reading sequentially. If you need to access most of the rows, it is faster to read sequentially, because this minimizes disk seeks.

What is the maximum length of a table name, database name, and fieldname in MySQL?

The following table describes the maximum length for each type of identifier.

Identifier Maximum Length
(bytes)
Database 64
Table 64
Column 64
Index 64
Alias 255

There are some restrictions on the characters that may appear in
identifiers:

How many values can the SET function of MySQL take?

MySQL set can take zero or more values but at the maximum it can take 64 values

What are the other commands to know the structure of table using MySQL commands except explain command?

describe Table-Name;

How many tables will create when we create table, what are they?

The ‘.frm’ file stores the table definition.
The data file has a ‘.MYD’ (MYData) extension.
The index file has a ‘.MYI’ (MYIndex) extension,

What is the purpose of the following files having extensions 1) .frm 2) .myd 3) .myi? What do these files contain?

In MySql, the default table type is MyISAM.
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.
The ‘.frm’ file stores the table definition.
The data file has a ‘.MYD’ (MYData) extension.
The index file has a ‘.MYI’ (MYIndex) extension,

What is maximum size of a database in MySQL?

If the operating system or filesystem places a limit on the number of files in a directory, MySQL is bound by that constraint.The efficiency of the operating system in handling large numbers of files in a directory can place a practical limit on the number of tables in a database. If the time required to open a file in the directory
increases significantly as the number of files increases, database performance can be adversely affected.
The amount of available disk space limits the number of tables.
MySQL 3.22 had a 4GB (4 gigabyte) limit on table size. With the MyISAM storage engine in MySQL 3.23, the maximum table size was increased to 65536 terabytes (2567 1 bytes). With this larger allowed table size, the maximum effective table size for MySQL databases is usually determined by operating system constraints on file sizes, not by MySQL internal limits.The InnoDB storage engine maintains InnoDB tables within a tablespace that can be created from several files. This allows a table to exceed the maximum individual file size. The tablespace can include raw disk
partitions, which allows extremely large tables. The maximum tablespace size is 64TB.
The following table lists some examples of operating system file-size limits. This is only a rough guide and is not intended to be definitive. For the most up-to-date information, be sure to check the documentation specific to your operating system.
Operating System File-size LimitLinux 2.2-Intel 32-bit 2GB (LFS: 4GB)
Linux 2.4+ (using ext3 filesystem) 4TB
Solaris 9/10 16TB
NetWare w/NSS filesystem 8TB
Win32 w/ FAT/FAT32 2GB/4GB
Win32 w/ NTFS 2TB (possibly larger)
MacOS X w/ HFS+ 2TB

Give the syntax of Grant and Revoke commands?

The generic syntax for grant is as following
> GRANT [rights] on [database/s] TO [username@hostname] IDENTIFIED BY [password]
now rights can be
a) All privileges
b) combination of create, drop, select, insert, update and delete etc.We can grant rights on all databse by using *.* or some specific
database by database.* or a specific table by database.table_name username@hotsname can be either username@localhost, username@hostname and username@% where hostname is any valid hostname and % represents any name, the *.*
any condition password is simply the password of userThe generic syntax for revoke is as following
> REVOKE [rights] on [database/s] FROM [username@hostname] now rights can be as explained above
a) All privileges
b) combination of create, drop, select, insert, update and delete etc. username@hotsname can be either username@localhost, username@hostname
and username@% where hostname is any valid hostname and % represents any name, the *.* any condition

0

Fresher Question & Answer2

PHP Interview Quesition & Answer2

What are the features and advantages of object-oriented programming?

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

What are the differences between procedure-oriented languages and object-oriented languages?

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 .

What is the use of friend function?

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.

What are the differences between public, private, protected, static, transient, final and volatile?

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.

What is the functionality of the function strstr and stristr?

strstr Returns part of string from the first occurrence of needle(sub string that we finding out ) to the end of string.
$email= ‘sonialouder@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

What are the differences between PHP 3 and PHP 4 and PHP 5?

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

What is the functionality of the function htmlentities?

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.

How can we get second of the current time using date function?

<?php $second = date(“s”); ?>

How can we convert the time zones using PHP?

<?php By using date_default_timezone_get and
date_default_timezone_set function on PHP 5.1.0

// 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, 2000
$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:
// Fri, 31 Dec 1999 18:00:00 EST
echo ‘

‘, date(DATE_RFC1123, $stamp) ,’

‘;?>

What is meant by urlencode and urldocode?

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.

What is the difference between the functions unlink and unset?

unlink() deletes the given file from the file system.
unset() makes a variable undefined.

How can we register the variables into a session?

$_SESSION[‘name’] = “girdhari”;

How can we get the properties (size, type, width, height) of an image using PHP image functions?

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

How can we get the browser properties using PHP?

By using $_SERVER[‘HTTP_USER_AGENT’] variable.

What is the maximum size of a file that can be uploaded using PHP and how can we change this?

By default the maximum size is 2MB. and we can change the following
setup at php.iniupload_max_filesize = 2M

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

by changing the following setup at php.inimax_execution_time = 30; Maximum execution time of each script, in seconds

How can we take a backup of a MySQL table and how can we restore it. ?

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!

0

Fresher Question & Answer5

Fresher Quesition & Answer

What’s PHP ?

The PHP Hypertext Preprocessor is a programming language that allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web based software applications.

What Is a Session?

A session is a logical object created by the PHP engine to allow you to preserve data across subsequent HTTP requests.
There is only one session object available to your PHP scripts at any time. Data saved to the session by a script can be retrieved by the same script or another script when requested from the same visitor.
Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor.

How can we know the number of days between two given dates using PHP?

Simple arithmetic:
$date1 = date(‘Y-m-d’);
$date2 = ‘2006-07-01’;
$days = (strtotime() – strtotime()) / (60 * 60 * 24);
echo “Number of days since ‘2006-07-01’: $days”;

What is the difference between $message and $$message?

Anwser 1:
$message is a simple variable whereas $$message is a reference variable. Example:
$user = ‘bob’
is equivalent to
$holder = ‘user’;
$$holder = ‘bob’;

Anwser 2:
They are both variables. But $message is a variable with a fixed name. $$message is a variable who’s name is stored in $message. For example, if $message contains “var”, $$message is the same as $var.

What Is a Persistent Cookie?

A persistent cookie is a cookie which is stored in a cookie file permanently on the browser’s computer. By default, cookies are created as temporary cookies which stored only in the browser’s memory. When the browser is closed, temporary cookies will be erased. You should decide when to use temporary cookies and when to use persistent cookies based on their differences:
*Temporary cookies can not be used for tracking long-term information.
*Persistent cookies can be used for tracking long-term information.
*Temporary cookies are safer because no programs other than the browser can access them.
*Persistent cookies are less secure because users can open cookie files see the cookie values.

Who is the father of PHP ?

Rasmus Lerdorf is known as the father of PHP.

In how many ways we can retrieve the data in the result set of MySQL using PHP?

We can do it by 4 Ways
1. mysql_fetch_row. , 2. mysql_fetch_array , 3. mysql_fetch_object 4. mysql_fetch_assoc

What is the difference between mysql_fetch_object and mysql_fetch_array?

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).

What are the differences between Get and post methods.

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

How can we create a database using PHP and MySQL?

We can create MySQL database with the use of
mysql_create_db(“Database Name”)

What are the differences between require and include?

Both include and require used to include a file but when included file not found
Include send Warning where as Require send Fatal Error .

What is use of header() function in php ?

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.

How can I execute a PHP script using command line?

Just run the PHP CLI (Command Line Interface) program and
provide the PHP script file name as the command line argument.

Suppose your Zend engine supports the mode Then how can u configure your PHP Zend engine to support mode ?

In php.ini file:
set short_open_tag=on to make PHP support

Shopping cart online validation i.e. how can we configure Paypal, etc.?

Nothing more we have to do only redirect to the payPal url after
submit all information needed by paypal like amount,adresss etc.

What is meant by nl2br()?

Inserts HTML line breaks (
) before all newlines in a string.

What is htaccess? Why do we use this and Where?

.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.

How we get IP address of client, previous reference page etc ?

Answers : 18 By using $_SERVER[‘REMOTE_ADDR’],$_SERVER[‘HTTP_REFERER’] etc.

What are the reasons for selecting lamp (Linux, apache, MySQL,PHP) instead of combination of other software programs, servers and operating systems?

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.

How can we encrypt and decrypt a data present in a MySQL table using MySQL?

AES_ENCRYPT () and AES_DECRYPT ()

How can we encrypt the username and password using PHP?

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()
0

PHP Interview Question & Answer 3

PHP Interview Quesition & Answer 3

31.What are the different types of statements that are present in PHP?

There are four kinds of PHP statements that are present. They are as follows:
• Simple statement- these are the echo statements and end with a semicolon (;). PHP ignores white spaces between simple statements. Until it finds a semicolon it reads the statement.
• Complex/Conditional statements: these are the statements which deal with certain conditions that have to be executed to meet certain specific requirements. These are if and else block or switch statements. PHP reads the complete statement and doesn’t stop at the first semicolon it encounters. It looks for starting and ending braces to end the execution.
• Looping statements: statements that are repeated in a block. The feature that enables you to execute the statements repeatedly is called as loop. For example: for loop, while loop, do..while loop.

32.What is the use of $_Server and $_Env?

$_SERVER and $_ENV arrays contain different information. The information depends on the server and operating system being used. Most of the information can be seen of an array for a particular server and operating system. The syntax is as follows:
foreach($_SERVER as $key =>$value)
{ echo “Key=$key, Value=$value\n”; }

33.What are the disadvantages of MySQL?

MySQL does not support a very large database size as efficiently
MySQL does not support ROLE, COMMIT, and Stored procedures in versions less than 5.0
Transactions are not handled very efficiently.

34.What are the disadvantages of MySQL?

MySQL does not support a very large database size as efficiently
MySQL does not support ROLE, COMMIT, and Stored procedures in versions less than 5.0
Transactions are not handled very efficiently.

35.Explain about MySQL and its features.

MySQL is a relational database management system which is an open source database.

Because of its unique storage engine architecture MySQL performance is very high.
Supports large number of embedded applications which makes MySql very flexible.
Use of Triggers, Stored procedures and views which allows the developer to give a higher productivity.
Allows transactions to be rolled back, commit and crash recovery.

36.What are MyISAM tables?

In MySQL MyISAM is the default storage engine. MyISAM tables store data values with the low byte first. Even though MyISAM tables are very reliable, corrupted tables can be expected if there is a hardware failure, the pc shuts down unexpectedly. MyISAM tables are reliable because any change made to a table is written before the sql statement returns. Even though MyISAM is the default storage engine it is advisable to specify ENGINE= MYISAM

0

PHP Interview Question & Answer2

PHP Interview Quesition & Answer2

16.What is the difference between Notify URL and Return URL?

Notify URL and Return URL is used in Paypal Payment Gateway integration. Notify URL is used by PayPal to post information about the transaction. Return URL is sued by the browser; A url where the user needs to be redirected on completion of the payment process.

17.Describe functions STRSTR() and STRISTR.

Both the functions are used to find the first occurrence of a string. Parameters includes: input String, string whose occurrence needs to be found, TRUE or FALSE (If TRUE, the functions return the string before the first occurrence.
STRISTR is similar to STRSTR. However, it is case-insensitive
E.g. strstr ($input_string, string)

18.What are the different types of errors in PHP?

  • E_ERROR: A fatal error that causes script termination
  • E_WARNING: Run-time warning that does not cause script termination
  • E_PARSE: Compile time parse error.
  • E_NOTICE: Run time notice caused due to error in code
  • E_CORE_ERROR: Fatal errors that occur during PHP’s initial startup (installation)
  • E_CORE_WARNING: Warnings that occur during PHP’s initial startup
  • E_COMPILE_ERROR: Fatal compile-time errors indication problem with script.
  • E_USER_ERROR: User-generated error message.
  • E_USER_WARNING: User-generated warning message.
  • E_USER_NOTICE: User-generated notice message.
  • .E_STRICT: Run-time notices.
  • E_RECOVERABLE_ERROR: Catchable fatal error indicating a dangerous error
  • E_ALL: Catches all errors and warnings

19.What are the different types of Errors in PHP?

There are three basic types of runtime errors in PHP:

1. Notices: These are small, 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 the default behavior can be changed.

2. Warnings: Warnings are more severe errors like 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.

20.How can we know the number of days between two given dates using PHP?

The start date and end date can be first found as shown below:

$date1= strotime($start_date);
$date2= strotime($end_date);
$date_diff = (($date1)- ($date2)) / (60*60*24)

21.How to connect PHP wil MySQL?

<?
mysql_connect(‘db.domain.com:33306′,’root’,’user’);
mysql_connect(‘localhost:/tmp/mysql.sock’);
mysql_connect(‘localhost’,’rasmus’,’foobar’,
true,MYSQL_CLIENT_SSL|MYSQL_CLIENT_COMPRESS);
?>

22.HTTP headers can be used in PHP by redirection which is written as:

<?header(‘Location: http://www.php.net’)?>
The headers can be added to HTTP response in PHP using the header(). The response headers are sent before any actual response being sent. The HTTP headers have to be sent before taking the output of any data. The statement above gets included at the top of the script.

23.Why PHP is also called as Scripting language?

PHP is basically a general purpose language, which is used to write scripts. Scripts are normal computer files that consist of instructions written in PHP language. It tells the computer to execute the file and print the output on the screen. PHP is used for webpages and to create websites, thus included as scripting language.

24.Why many companies are switching their current business language to PHP? Where PHP basically used?

PHP is rapidly gaining the popularity and many companies are switching their current language for this language. PHP is a server side scripting language. PHP executes the instructions on the server itself. Server is a computer where the web site is located. PHP is used to create dynamic pages and provides faster execution of the instructions.

25.What is the use of PEAR in php?

PEAR is known as PHP Extension and Application Repository. It provides structured library to the PHP users and also gives provision for package maintenance.

26.What is the difference between PHP and JavaScript?

The difference lies with the execution of the languages. PHP is server side scripting language, which means that it can’t interact directly with the user. Whereas, JavaScript is client side scripting language, that is used to interact directly with the user

27.What does ODBC do in context with PHP?

PHP supports many databases like dBase, Microsft SQL Server, Oracle, etc. But, it also supports databases like filePro, FrontBase and InterBase with ODBC connectivity. ODBC stands for Open Database connectivity, which is a standard that allows user to communicate with other databases like Access and IBM DB2.

28.Why PHP is sometimes called as embedded scripting language?

PHP is a high level language which is used to allow users to write and understand it in human readable form and also use an interpreter to interpret the code which user write for the computer. PHP is used as an embedded scripting language for the web. PHP is embedded in HTML code. HTML tags are used to enclose the PHP language. HTML is used and PHP is code written in it in the same way as you write JavaScript in HTML.

29.What is the difference between echo, print and printf()?

Echo is the basic type used to print out a string. It just shows the content of the message written using it. It can have multiple parameters as well. print is a construct, it returns TRUE on successful output and FALSE there is no output. It can’t have multiple parameters. Printf() is a function, and not be used as a construct. It allows the string output to be formatted. It is the slowest medium to print the data out.

30.Why IDE is recommended for use while programming with PHP?

IDE stands for Integrated Development environment; it is a framework for developing applications. It includes programming editor where you can edit and write the development programs. The features of IDE are as follows:

  • 1. Debugging: this is the feature which is used to debug or find the bugs in a program.
  • 2. Preview: this is the feature which allow instant preview of the program you are writing.
  • 3. Testing: this is the features that includes built in testing features through which you can check your scripts.
  • 4. FTP: through this you can upload and download the file while connecting to the server.
  • 5. Project management: it organizes scripts into projects; manages the files in the project; includes file checkout and check-in features.
  • 6. Backups: it creates backups automatically of your Web site at periodic intervals.
0

PHP Interview Question & 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”]);

0