Interview questions on RESTFul Api


Q-1. Explain REST?

Ans. REST stands for Representational State Transfer. REST is an architectural style of developing web services which take advantage of the ubiquity of HTTP protocol and leverages HTTP method to define actions. It revolves around resource where every component is a resource which can be accessed by a common interface using HTTP standard methods.

In REST architecture, a REST Server provides access to resources and REST client accesses and presents those resources. Here each resource is identified by URIs or global IDs. REST uses different ways to represent a resource like text, JSON, and XML.XML and JSON are the most popular representations of resources these days.

Q-2. Explain The RESTFul Web Service?
Ans. Mostly, there are two kinds of Web Services which are quite popular.

1. SOAP (Simple Object Access Protocol) which is an XML-based way to expose web services.

2. Web services developed using REST style are known as RESTful web services. These web services use HTTP methods to implement the concept of REST architecture. A RESTful web service usually defines a URI, Uniform Resource Identifier a service, provides resource representation such as JSON and set of HTTP Methods.

Q-3. Explain What Is A “Resource” In REST?
Ans. REST architecture treats every content as a resource. These resources can be either text files, HTML pages, images, videos or dynamic business data.

REST Server provides access to resources and REST client accesses and modifies these resources. Here each resource is identified by URIs/ global IDs.

Q-4. What Is The Most Popular Way To Represent A Resource In REST?
Ans. REST uses different representations to define a resource like text, JSON, and XML.

XML and JSON are the most popular representations of resources.

Q-5. Which Protocol Is Used By RESTful Web Services?
Ans. RESTful web services make use of HTTP protocol as a medium of communication between client and server.

Q-6. What Is Messaging In RESTful Web Services?
Ans. RESTful web services make use of HTTP protocol as a medium of communication between client and server. The client sends a message in the form of an HTTP Request.

In response, the server transmits the HTTP Response. This technique is called Messaging. These messages contain message data and metadata, i.e., information about itself.

Q-7. State The Core Components Of An HTTP Request?
Ans. Each HTTP request includes five key elements.

1. The Verb which indicates HTTP methods such as GET, PUT, POST, DELETE.
2. URI stands for Uniform Resource Identifier (URI). It is the identifier for the resource on the server.
3. HTTP Version which indicates HTTP version, for example-HTTP v1.1.
4. Request Header carries metadata (as key-value pairs) for the HTTP Request message. Metadata could be a client (or browser) type, the format that the client supports, message body format, and cache settings.
5. Request Body indicates the message content or resource representation.

Q-8. State The Core Components Of An HTTP Response?

Ans. Every HTTP response includes four key elements.

1. Status/Response Code – Indicates Server status for the resource present in the HTTP request. For example, 404 means resource not found, and 200 means response is ok.
2. HTTP Version – Indicates HTTP version, for example-HTTP v1.1.
3. Response Header – Contains metadata for the HTTP response message stored in the form of key-value pairs. For example, content length, content type, response date, and server type.
4. Response Body – Indicates response message content or resource representation.

 

Q-9. Name The Most Commonly Used HTTP Methods Supported By REST?

Ans. There are a few HTTP methods in REST which are more popular.

1. GET -It requests a resource at the request-URL. It should not contain a request body as it will get discarded. Maybe it can be cached locally or on the server.
2. POST – It submits information to the service for processing; it should typically return the modified or new resource.
3. PUT – At the request URL it updates the resource.
4. DELETE – It removes the resource at the request-URL.
5. OPTIONS -It indicates the supported techniques.
6. HEAD – It returns meta information about the request URL.

 

Q-10. Mention, Whether You Can Use GET Request Instead Of PUT, To Create A Resource?

Ans. No, you shouldn’t use a PUT or POST method. Instead, apply the GET operation which has view-only rights.

 

Q-11. Is There Any Difference Between PUT And POST Operations? Explain It.

Ans. PUT and POST operation are almost the same. The only difference between the two is in terms of the result generated by them.

A PUT operation is idempotent while the POST operation can give a different result.

Let’s take an example.

1. PUT puts a file or resource at a particular URI and precisely at that URI. If the resource already exists, then PUT updates it. If it’s a first-time request, then PUT creates one.

2. POST sends data to a particular URI and expects the resource at that URI to deal with the request. The web server at this point can decide what to do with the data in the context of the specified resource.

 

Q-12. What Purpose Does The OPTIONS Method Serve For The RESTful Web Services?

Ans. This method lists down all the operations a web service supports. It makes read-only requests to the server.

 

Q-13. What Is URI? Explain Its Purpose In REST-Based Web Services. What Is Its Format?

Ans. URI stands for Uniform Resource Identifier. URI is the identifier for the resource in REST architecture.

The purpose of a URI is to locate a resource(s) on the server hosting the web service. A URI is of the following format-

<protocol>://<service-name>/<ResourceType>/<ResourceID>

 

Q-14. What Do You Understand By Payload In RESTFul Web Service?

Ans. Request body of every HTTP message includes request data called as Payload. This part of the message is of interest to the recipient.

We can say that we send the payload in the POST method but not in <GET> and <DELTE> methods.

 

Q-15. What Is The Upper Limit For A Payload To Pass In The POST Method?

Ans. <GET> appends data to the service URL. But, its size shouldn’t exceed the maximum URL length. However, <POST> doesn’t have any such limit.

So, theoretically, a user can pass unlimited data as the payload to the POST method. But, if we consider a real use case, then sending a POST with large payload will consume more bandwidth. It’ll take more time, and present performance challenges to your server. Hence, a user should take action accordingly.

 

Q-16. Explain The Caching Mechanism?

Ans. Caching is a process of storing server response at the client end. It makes the server save significant time from serving the same resource again and again.

The server response holds information which leads a client to perform the caching. It helps the client to decide how long to archive the response or not to store it at all.

 

Q-17. List The Main Differences Between SOAP And REST?

Ans.

                        SOAP                       REST

1. SOAP is a protocol through which two computer communicates by sharing the XML document.

1. Rest is a service architecture and design for network-based software architecture.

2. SOAP supports the only XML format.

2. It supports many different data formats.

3. SOAP does not support caching.

3. It supports caching.

4. SOAP is like a custom desktop application, closely connected to the server.

4. A REST client is just like a browser and uses standard methods. An application has to fit inside it.

5. SOAP is slower than the REST.

5. It is faster than SOAP.

6. It runs on HTTP but envelopes the message.

6. It uses the HTTP headers to hold meta information.

 

Q-18. What Are The Tools Available For Testing Web Services?

Ans. Following tools can help in testing the SOAP and RESTful web services.

1. SOAP UI tool.
2. Poster for Firefox browser.
3. The Postman extension for Chrome.

 

Q-19. Explain The Factors That Help To Decide About The Style Of Web Service To Use? SOAP Or REST?

Ans. In general, using REST-based web service is preferred due to its simplicity, performance, scalability, and support for multiple data formats.

However, SOAP is favorable to use where service requires an advanced level of security and transactional reliability.

But you can read the following facts before opting for any of the styles.

1. Does the service expose data or business logic? To expose data REST will be a better choice and SOAP for logic.
2. If the consumer or the service providers require a formal contract, then SOAP can provide such a contract via WSDL.
3. Need to support multiple data formats. REST supports this.
4. Support for AJAX calls. REST can use the XMLHttpRequest.
5. Synchronous and asynchronous calls – SOAP enables both synchronous/asynchronous operations whereas REST has built-in support for synchronous.
6. Stateless or Stateful calls -REST is suited for stateless operations.

Here are some of the advanced-level facts that you can consider as well.

1. Security requirement – SOAP provides a high level of security.
2. Transaction support – SOAP has good support for transaction management.
3. Limited bandwidth – SOAP has a lot of overhead when sending/receiving packets since it’s XML based, requires a SOAP header. However, the REST requires less bandwidth to send requests to the server. Its messages are mostly built using JSON.
4. Ease of use – It is easy to implement, test, and maintain REST-based application.

 

PHP, MySql Experienced Interview Questions and Answers.


Q. What are magic functions or methods in php?

The function names __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state() and __clone() are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.

__sleep()   and __wakeup()

serialize() checks if your class has a function with the magic name __sleep(). If so, that function is executed prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn’t return anything then NULL is serialized and E_NOTICE is issued.

Note:

It is not possible for __sleep() to return names of private properties in parent classes. Doing this will result in an E_NOTICE level error. Instead you may use the Serializable interface.

The intended use of __sleep() is to commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which do not need to be saved completely.

Conversely, unserialize() checks for the presence of a function with the magic name __wakeup(). If present, this function can reconstruct any resources that the object may have.

The intended use of __wakeup() is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.

Differentiate the LIKE and REGEXP operators?
SELECT * FROM pet WHERE name REGEXP “^b”;
SELECT * FROM pet WHERE name LIKE “%b”;
What are the String types are available for a column?
The string types are CHAR, VARCHAR, BLOB, TEXT, ENUM, and SET.

An ENUM is a string object with a value chosen from a list of permitted values that are enumerated explicitly in the column specification at table creation time.

An enumeration value must be a quoted string literal; it may not be an expression, even one that evaluates to a string value. For example, you can create a table with an ENUM column like this:

CREATE TABLE sizes (
    name ENUM('small', 'medium', 'large')
); 

Get total record count with LIMIT in a single MYSQL query.

SELECT SQL_CALC_FOUND_ROWS userid, username FROM users WHERE userid >= 1 LIMIT 2

SELECT FOUND_ROWS()


What is the REGEXP?
A REGEXP pattern match succeed if the pattern matches anywhere in the value being tested.
What is the difference between CHAR AND VARCHAR?
The CHAR and VARCHAR types are similar, but differ in the way they are stored and retrieved.
The length of a CHAR column is fixed to the length that you declare when you create the table.
The length can be any value between 1 and 255. When CHAR values are stored, they are right-padded with spaces to the specified length. When CHAR values are retrieved, trailing spaces are removed.
How quoting and escaping work in SELECT QUERY?
SELECT ‘hello’, ‘hello’,‘hello’, ‘hel‘‘lo’, ‘\‘hello’.
What is the difference between BLOB AND TEXT?
A BLOB is a binary large object that can hold a variable amount of data. The four BLOB types TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB differ only in the maximum length of the values they can hold.
The four TEXT types TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT correspond to the four BLOB types and have the same maximum lengths and storage requirements. The only difference between BLOB and TEXT types is that sorting and comparison is performed in case-sensitive fashion for BLOB values and case-insensitive fashion for TEXT values. In other words, a TEXT is a case-insensitive BLOB.

How do you get current user in mysql?
SELECT USER();
How would you change a table to InnoDB?
ALTER TABLE name_file ENGINE innodb;
How do you concatenate strings in MySQL?
CONCAT (string1, string2, string3)
what is difference between primary key and candidate key?
Primary Key
– are used to uniquely identify each row of the table. A table can have only one primary Key.
Candidate Key
– primary key is a candidate key. There is no difference. By common convention one candidate key is designated as a primary one and that key is used for any foreign key references.
How do you get the month from a timestamp?
SELECT MONTH(january_timestamp) from tablename;
What do % and _ mean inside LIKE statement?
% corresponds to 0 or more characters, _ is exactly one character.
If you specify the data type as DECIMAL (5,2), what’s the range of values that can go in this table?
999.99 to -99.99. Note that with the negative number the minus sign is considered one of the digits.
How do you get the current date in Mysql?
SELECT CURRENT_DATE();
What is the difference between mysql_fetch_array and mysql_fetch_object?
mysql_fetch_array(): – returns a result row as a associated array, regular array from database.
mysql_fetch_object: – returns a result row as object from database.
You wrote a search engine that should retrieve 10 results at a time, but at the same time you’d like to know how many rows there’re total. How do you display that to the user?
SELECT SQL_CALC_FOUND_ROWS page_title FROM web_pages LIMIT 1,10; SELECT FOUND_ROWS();
What does this query mean: SELECT user_name, user_isp FROM users LEFT JOIN isps USING (user_id)?
It’s equivalent to saying SELECT user_name, user_isp FROM users LEFT JOIN isps WHERE users.user_id=isps.user_id
How do you display the list of database in mysql?
SHOW DATABASES;
How do you display the structure of the table?
DESCRIBE table_name;
How do you find out which auto increment was assigned on the last insert?
SELECT LAST_INSERT_ID() will return the last value assigned by the auto_increment function. Note that you don’t have to specify the table name.
What does TIMESTAMP ON UPDATE CURRENT_TIMESTAMP data type do?
On initialization places a zero in that column, on future updates puts the current value of the timestamp in.
How many drivers in Mysql?
There are eleven drivers in MYSQL .Six of them from MySQL AB and five by MYSQL Communities.They are
PHP Driver
ODBC Driver
JDBC Driver
ado.net5.mxj
CAPI1PHP DRIVER
PERL DRIVER
PYTHON DRIVER
RUBY DRIVER
C WRAPPER
How do you run batch mode in mysql?
mysql < batch-file >;
mysql < batch-file > mysql.out
What Storage Engines do you use in MySQL?
Storage engines used to be called table types.
Data in MySQL is stored in files (or memory) using a variety of different techniques. Each of these techniques employs different storage mechanisms, indexing facilities, locking levels and ultimately provides a range of different functions and capabilities. By choosing a different technique you can gain additional speed or functionality benefits that will improve the overall functionality of your application.
Where MyISAM table is stored?
Each MyISAM table is stored on disk in three files.
The ‘.frm’ file stores the table definition.
The data file has a ‘.MYD’ (MYData) extension.
The index file has a ‘.MYI’ (MYIndex) extension
Define Primary key?
MYSQL allows only one primary key. A primary key is used to uniquely identify each row in a table. It can either be part of the actual record itself.A primary key can consist of one or more fields on a table. When multiple fields are used as a primary key, they are called a composite key.
If the value in the column is repeatable, how do you find out the unique values?
SELECT DISTINCT user_firstname FROM users;
Explain the difference between FLOAT, DOUBLE and REAL?
FLOATs store floating point numbers with 8 place accuracy and take up 4 bytes. DOUBLEs store floating point numbers with 16 place accuracy and take up 8 bytes. REAL is a synonym of FLOAT for now.
How do you get the current version of mysql?
SELECT VERSION();
Is Mysql query has LETTERCASE?
No.
Ex :
SELECT VERSION(), CURRENT_DATE;
select version(), current_date;
SeLeCt vErSiOn(), current_DATE;
What is the LIKE?
A LIKE pattern match, which succeeds only if the pattern matches the entire value.
What are ENUMs used for in MySQL?
You can limit the possible values that go into the table.
CREATE TABLE months (month ENUM ’January’, ’February’, ’March’,); INSERT months VALUES (’April’).
What are the advantages of Mysql comparing with oracle?
MySql is Open source, which can be available any time. Provides Gui with Command Prompt. Supports the administration using MySQL Admin,MySQL Query Browser.Oracle is best database ever in Software development.
What is the difference between CHAR_LENGTH and LENGTH?
The first is, naturally, the character count. The second is byte count. For the Latin characters the numbers are the same, but they’re not the same for Unicode and other encodings.
How are ENUMs and SETs represented internally?
As unique integers representing the powers of two, due to storage optimizations.
How do you change a password for an existing user via mysqladmin?
mysqladmin -u root -p password “newpassword”
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.
What is meant by PEAR in php?
Answer1:
PEAR is the next revolution in PHP. This repository is bringing higher level programming to PHP. PEAR is a framework and distribution system for reusable PHP components. It eases installation by bringing an automated wizard, and packing the strength and experience of PHP users into a nicely organised OOP library. PEAR also provides a command-line interface that can be used to automatically install packages
Answer2:
PEAR is short for PHP Extension and Application Repository and is pronounced just like the fruit. The purpose of PEAR is to provide:
A structured library of open-sourced code for PHP users
A system for code distribution and package maintenance
A standard style for code written in PHP
The PHP Foundation Classes (PFC),
The PHP Extension Community Library (PECL),
A web site, mailing lists and download mirrors to support the PHP/PEAR community
PEAR is a community-driven project with the PEAR Group as the governing body. The project has been founded by Stig S. Bakken in 1999 and quite a lot of people have joined the project since then.
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;
How can we repair a MySQL table?
The syntex for repairing a mysql table is:
REPAIR TABLE tablename
REPAIR TABLE tablename QUICK
REPAIR TABLE tablename EXTENDED
This command will repair the table specified.
If QUICK is given, MySQL will do a repair of only the index tree.
If EXTENDED is given, it will create index row by row.
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.
What does a special set of tags do in PHP?
What does a special set of tags <?= and ?> do in PHP?
The output is displayed directly to the browser.
How do you define a constant?
Via define() directive, like define (MYCONSTANT, 100);
What are the differences between require and include, include_once?
Anwser 1:
require_once() and include_once() are both the functions to include and evaluate the specified file only once. If the specified file is included previous to the present call occurrence, it will not be done again.
But require() and include() will do it as many times they are asked to do.
Anwser 2:
The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. The major difference between include() and require() is that in failure include() produces a warning message whereas require() produces a fatal errors.
Anwser 3:
All three are used to an include file into the current page.
If the file is not present, require(), calls a fatal error, while in include() does not.
The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. It des not call a fatal error if file not exists. require_once() does the same as include_once(), but it calls a fatal error if file not exists.
Anwser 4:
File will not be included more than once. If we want to include a file once only and further calling of the file will be ignored then we have to use the PHP function include_once(). This will prevent problems with function redefinitions, variable value reassignments, etc.
What is meant by urlencode and urldecode?
Anwser 1:
urlencode() returns the URL encoded version of the given string. URL coding converts special characters into % signs followed by two hex digits. For example: urlencode(10.00%) will return 10%2E00%25?. URL encoded strings are safe to be used as part of URLs.
urldecode() returns the URL decoded version of the given string.
Anwser 2:
string urlencode(str)  Returns the URL encoded version of the input string. String values to be used in URL query string need to be URL encoded. In the URL encoded version:
Alphanumeric characters are maintained as is.
Space characters are converted to + characters.
Other non-alphanumeric characters are converted % followed by two hex digits representing the converted character.
string urldecode(str)  Returns the original string of the input URL encoded string.
For example:
$discount =10.00%;
$url = http://domain.com/submit.php?disc=.urlencode($discount);
echo $url;
You will get http://domain.com/submit.php?disc=10%2E00%25?.
How To Get the Uploaded File Information in the Receiving Script?
Once the Web server received the uploaded file, it will call the PHP script specified in the form action attribute to process them. This receiving PHP script can get the uploaded file information through the predefined array called $_FILES. Uploaded file information is organized in $_FILES as a two-dimensional array as:
$_FILES[$fieldName][‘name’]  The Original file name on the browser system.
$_FILES[$fieldName][‘type’]  The file type determined by the browser.
$_FILES[$fieldName][‘size’]  The Number of bytes of the file content.
$_FILES[$fieldName][‘tmp_name’]  The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES[$fieldName][‘error’]  The error code associated with this file upload.
The $fieldName is the name used in the <INPUT,>.
What is the difference between mysql_fetch_object and mysql_fetch_array?
MySQL fetch object will collect first single matching record where mysql_fetch_array will collect all matching records from the table in an array
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. For example, php myScript.php, assuming php is the command to invoke the CLI program.
Be aware that if your PHP script was written for the Web CGI interface, it may not execute properly in command line environment.

How to get size & type of uploaded image?
list($width, $height, $type) = getimagesize($_FILES[‘photo_file’][‘tmp_name’]);
How can we submit a form without a submit button?

The main idea behind this is to use Java script submit( function in order to submit the form without explicitly clicking any submit button. You can attach the document.formname.submit( method to onclick, onchange events of different inputs and perform the form submission. you
can even built a timer function where you can automatically submit the form after xx seconds once the loading is done (can be seen in online test sites.

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

You can do it by  Ways
. mysql_fetch_row.

. mysql_fetch_array

. mysql_fetch_object

. 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 is the difference between $message and $$message?

It is a classic example of PHP’s variable variables. take the following example.$message = “Mizan”;$$message = “is a moderator of PHPXperts.”;$message is a simple PHP variable that we are used to. But the $$message is not a very familiar face. It creates a variable name $mizan
with the value “is a moderator of PHPXperts.” assigned. break it like this${$message} => $mizanSometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically.

How can we extract string ‘abc.com ‘ from a string ‘http://info@abc.com’
using regular expression of PHP?

preg_match(”/^http:\/\/.+@(.+$/”,’http://info@abc.com’,$found;

echo $found[];

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, include_once and require_once?

The include( statement includes and evaluates the specified file.The documentation below also applies to require(. The two constructs are identical in every way except how they handlefailure. include( produces a Warning while require( results in a Fatal Error. In other words, use require( if you want a missingfile to halt processing of the page.

include( does not behave this way, the script will continue regardless.

The include_once( statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include( statement, with the only differencebeing that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.include_once( should be used in cases where the same file might be included and evaluated more than once during a particularexecution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.
require_once(
should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.
Can we use include (”abc.PHP” two times in a PHP page “makeit.PHP”?
Yes we can use include( more than one time in any page though it is not a very good practice.
What are the different tables present in MySQL, which type of table is generated when we are creating a table in the following syntax:
create table employee (eno int(,ename varchar(0 ?

Total  types of tables we can create
. MyISAM
. Heap
. Merge
. INNO DB
. ISAM

MyISAM is the default storage engine as of MySQL . and as a result if we do not specify the table name explicitly it will be assigned to the default engine.

0
How can we encrypt the username and password using PHP?
0
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

MD(           Not available

OLD_PASSWORD(  Not available

PASSWORD(      Not available

SHA( or SHA( Not available

Not available   UNCOMPRESSED_LENGTH(

 How are ENUMs and SETs represented internally?
As unique integers representing the powers of two, due to storage optimizations.

 How do you start and stop MySQL on Windows?
net start MySQL, net stop MySQL

 How do you start MySQL on Linux?
/etc/init.d/mysql start

 Explain the difference between mysql and mysql interfaces in PHP?
mysqli is the object-oriented version of mysql library functions.
What’s the default port for MySQL Server?
0

 What does tee command do in MySQL?
tee followed by a filename turns on MySQL logging to a specified file. It can be stopped by command note.

 Can you save your connection settings to a conf file?
Yes, and name it ~/.my.conf. You might want to change the permissions on the file to 00, so that it’s not readable by others.

 How do you change a password for an existing user via mysqladmin?
mysqladmin -u root -p password “newpassword”

 Use mysqldump to create a copy of the database?
mysqldump -h mysqlhost -u username -p mydatabasename > dbdump.sql

 Have you ever used MySQL Administrator and MySQL Query Browser?
Describe the tasks you accomplished with these tools.

0 What are some good ideas regarding user security in MySQL?
There is no user without a password. There is no user without a user name. There is no user whose Host column contains % (which here indicates that the user can log in from anywhere in the network or the Internet. There are as few users as possible (in the ideal case only root who have unrestricted access.

 Explain the difference between MyISAM Static and MyISAM Dynamic. ?
In MyISAM static all the fields have fixed width. The Dynamic MyISAM table would include fields such as TEXT, BLOB, etc. to accommodate the data types with various lengths. MyISAM Static would be easier to restore in case of corruption, since even though you might lose some data, you know exactly where to look for the beginning of the next record.

 What does myisamchk do?
It compressed the MyISAM tables, which reduces their disk usage.

 Explain advantages of InnoDB over MyISAM?
Row-level locking, transactions, foreign key constraints and crash recovery.

 Explain advantages of MyISAM over InnoDB?
Much more conservative approach to disk space management – each MyISAM table is stored in a separate file, which could be compressed then with myisamchk if needed. With InnoDB the tables are stored in tablespace, and not much further optimization is possible. All data except for TEXT and BLOB can occupy ,000 bytes at most. No full text indexing is available for InnoDB. TRhe COUNT(*s execute slower than in MyISAM due to tablespace complexity.

 What are HEAP tables in MySQL?
HEAP tables are in-memory. They are usually used for high-speed temporary storage. No TEXT or BLOB fields are allowed within HEAP tables. You can only use the comparison operators = and. HEAP tables do not support AUTO_INCREMENT. Indexes must be NOT NULL.

 How do you control the max size of a HEAP table?
MySQL config variable max_heap_table_size.

 What are CSV tables?
Those are the special tables, data for which is saved into comma-separated values files. They cannot be indexed.

 Explain federated tables. ?
Introduced in MySQL .0, federated tables allow access to the tables located on other databases on other servers.

 What is SERIAL data type in MySQL?
BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT

0 What happens when the column is set to AUTO INCREMENT and you reach the maximum value for that table?
It stops incrementing. It does not overflow to 0 to prevent data losses, but further inserts are going to produce an error, since the key has been used already.

 Explain the difference between BOOL, TINYINT and BIT. ?
Prior to MySQL .0.: those are all synonyms. After MySQL .0.: BIT data type can store  bytes of data and should be used for binary data.

 Explain the difference between FLOAT, DOUBLE and REAL. ?
FLOATs store floating point numbers with  place accuracy and take up  bytes. DOUBLEs store floating point numbers with  place accuracy and take up  bytes. REAL is a synonym of FLOAT for now.

 If you specify the data type as DECIMAL (,, what’s the range of values that can go in this table?
. to -.. Note that with the negative number the minus sign is considered one of the digits.

 What happens if a table has one column defined as TIMESTAMP?
That field gets the current timestamp whenever the row gets altered.

 But what if you really want to store the timestamp data, such as the publication date of the article?
Create two columns of type TIMESTAMP and use the second one for your real data.
Explain data type TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ?
The column exhibits the same behavior as a single timestamp column in a table with no other timestamp columns.

 What does TIMESTAMP ON UPDATE CURRENT_TIMESTAMP data type do?
On initialization places a zero in that column, on future updates puts the current value of the timestamp in.

 Explain TIMESTAMP DEFAULT ‘00:0:0 ::? ON UPDATE CURRENT_TIMESTAMP. ?
A default value is used on initialization, a current timestamp is inserted on update of the row.

 If I created a column with data type VARCHAR(, what would I expect to see in MySQL table?
CHAR(, since MySQL automatically adjusted the data type.

 General Information About MySQL
MySQL is a very fast, multi-threaded, multi-user, and robust SQL (Structured Query Language database server.

0 MySQL is free software.
It is licensed with the GNU GENERAL PUBLIC LICENSE http://www.gnu.org/.

 What Is MySQL
MySQL, the most popular Open Source SQL database, is provided by MySQL AB. MySQL AB is a commercial company that builds is business providing services around the MySQL database. See section . What Is MySQL AB.

 MySQL is a database management system.
A database is a structured collection of data. It may be anything from a simple shopping list to a picture gallery or the vast amounts of information in a corporate network. To add, access, and process data stored in a computer database, you need a database management system such as MySQL. Since computers are very good at handling large amounts of data, database management plays a central role in computing, as stand-alone utilities, or as parts of other applications.

 MySQL is a relational database management system.
A relational database stores data in separate tables rather than putting all the data in one big storeroom. This adds speed and flexibility. The tables are linked by defined relations making it possible to combine data from several tables on request. The SQL part of MySQL stands for “Structured Query Language” – the most common standardized language used to access databases.

 MySQL is Open Source Software.
Open source means that it is possible for anyone to use and modify. Anybody can download MySQL from the Internet and use it without paying anything. Anybody so inclined can study the source code and change it to fit their needs. MySQL uses the GPL (GNU General Public License http://www.gnu.org, to define what you may and may not do with the software in different situations. If you feel uncomfortable with the GPL or need to embed MySQL into a commercial application you can buy a commercially licensed version from us.

 Why use MySQL?
MySQL is very fast, reliable, and easy to use. If that is what you are looking for, you should give it a try. MySQL also has a very practical set of features developed in very close cooperation with our users. You can find a performance comparison of MySQL to some other database managers on our benchmark page. See section . Using Your Own Benchmarks. MySQL was originally developed to handle very large databases much faster than existing solutions and has been successfully used in highly demanding production environments for several years. Though under constant development, MySQL today offers a rich and very useful set of functions. The connectivity, speed, and security make MySQL highly suited for accessing databases on the Internet.

 The technical features of MySQL
For advanced technical information, see section  MySQL Language Reference. MySQL is a client/server system that consists of a multi-threaded SQL server that supports different backends, several different client programs and libraries, administrative tools, and a programming interface. We also provide MySQL as a multi-threaded library which you can link into your application to get a smaller, faster, easier to manage product. MySQL has a lot of contributed software available.

It is very likely that you will find that your favorite application/language already supports MySQL. The official way to pronounce MySQL is “My Ess Que Ell” (not MY-SEQUEL. But we try to avoid correcting people who say MY-SEQUEL.

Session and cookie

What is the difference between session and cookie ?

flash

How can we call flash banner in dreamweaver..

php swapp two name surmane

why we use @?

Give the ans.

what is the difference between sql and mysql

SQL means “structured query language” which is the syntax of commands you send to database. MYSQL is the database program which accepts the those commands and gives out the data.

Please Help

I have created a php site in dreamweaver but i have not stored the files in www directory of wamp. now i want to move the files to www directory without losing the links that i’ve created… how is it possible??

How i get DPI of uploaded image

Can any one tell me how can i get DPI of uploaded image. Thanx

zend framework

Hi evryone, how do i call stored procedure from zend framework using oracle database and how to echo the data. muzeeb

what is the difference between echo and print in php?

When outputting something with PHP, we use print or echo functions. what exactly is the difference between those functions?

PHP – Drupal Joomla Developer required 2 – 3 Years Experienced – MNC Bangalore

Please send your resumes for the Drupal Joomla Opening – Reputed Company – Bangalore Requirement: 2 – 3 years experience in Joomla / Drupal & PHP Contact on bshibin@gmail.com

difference between superkey candidate and primary keys

Super key is the set of attributes in a table that can uniquely identifies a database tuple(row or record). Candidate key is the minimal set of super key that can uniquely identifies a database record. Primary key is one of the candidate keys. you can select any candidate k

Custom redirect in drupal after the node is created?

Please use the following snippet for the custom redirect. function module_form_alter(&$form,$form_state,$form_id){ if (isset($form[‘#node’]) && $form[‘#node’]->type .’_node_form’ == $form_id) { $form[‘buttons’][‘submit’][‘#submit’][] = ‘module_redirect_handler’; }

How to enable HTML option for Drupal menus?

/* *Enabling HTML option for Drupal menus */ function theme_menu_item_link($link) { $link[‘localized_options’][‘html’] = true; return l($link[‘title’], $link[‘href’], $link[‘localized_options’]); }

Why “pageTracker is not defined” error when using pageTracker._trackPageLoadTime();?

Please try use _gaq.push([‘_trackPageLoadTime’]); instead. It will work !!!

Why mousewheel.js/Jscrollpane.js ( scrolloing using mouse wheel ) not working in Firefox?

It might be because of Jscrollpane.js issue. The Quick solution to solve this issue is to edit the Jscroolpane.js. Go to particular line number ( Mostly:341 ) and change to var dragOffset = $drag.offset(false); currentOffset = { top: dragOffset.top, left:dragOffse

How to create admin settings form in Drupal?

How to extract content between anchor tags using Javascript?

In Jquery we can follow the following to iterate the contents.

Why “#” needs to be encoded in the URLs?

If you are using any “#” in the URLs it should be in the encoded form. Its because of this is used in URLs to mention where the fragment indicators ( eg:bookmarks or anchors in HTML ) begins in URLs.

Checking whether your MySQL server supports partitioning?

Before implementing any user defined partitioning in MySQL we need to make sure whether your mysql server supports partitioning. Finding out the same in your server will be simple. Type SHOW VARIABLES LIKE ‘%partition%’; on the command prompt as shown below. mysql> SHOW

why $_POST is better even though view source of the form gives the details

Plz some one give me the answer

Advantages of MySQL 5.1 compared to MySQL 5

Please find the following features that has been added to the MySQL version 5.1. 1. Partitioning 2. Row Based Replication 3. Plugin API 4. Server log table 5. Upgrade program 6. MySQL Cluster 7. Backup of tablespaces 8. Improvements to INFORMATION_SCHEMA 9. XML functio

disable the drupal cache for a page and for a module in drupal site

There is a contributed module to exclude drupal cache for particular pages in your drupal site. you can find the module in http://drupal.org/project/cacheexclude . for excluding drupal cache for a particular module write the below mentioned code in ur modulename_init() hook

How to send mail using MSSQL Express edition

I need to know the use of MS Sql express edition for sending mails.

Caching – How caching is implemented in Drupal?

For improving the the performance of the Drupal site we can use the caching mechanism. In caching rather than extracting the same data again and again every time, it stores the frequentltay accessed and static data in a convenient place and format. Drawback of caching is that,

Recommend commonly used modules for Drupal?

When an interviewer is asking these question please make sure before recommending any module 1. Whats the use of that module? 2. How well it is supported? 3. Any Vulnerabilities with the module?

Drupal – Overriding style sheets from modules and drupal core

Option 1 To override a core or contributed module style sheet, it must be specified in your theme’s .info file. For example, system-menus.css is located at “modules/system/system-menus.css”. If you place a file with the same name in your theme’s folder and add the following ent

Drupal – Overriding Drupal Core Javascript Files?

cognizant php interview questions?

Do any one have Cognizant/Capgemini interview questions for php/Drupal?

Openings with TCS BPO

Start Career With TCS Walk-in for graduates from the Batch 2010 and 2011 BA/BBA/BBM/B Com/BSc/MSc ( Statistics/Maths ) / M.Com On Saturday 16th April 2011 At TCS, Think Campus,#42, Electronic City, Phase II, Bangalore 100

Why the drupal blocks are disappearing after submitting the form?

Why the drupal blocks are disappearing after submitting the form?

Why the drupal blocks are disappearing after submitting the form?

Do any one have any idea why the blocks are disappearing?

How to create a new region in Drupal 6?

Please follow the following steps to create new regions for Drupal 6 ADD the following region information to you theme.info file: regions[left] = Left sidebar regions[right] = Right sidebar regions[content] = Content regions[header] = Header regions[footer] = Foote

how i can show msg for user when someone try to login

Hello everybody ..! :D i’m working on a E-Bank project , and i need script to show msg for the user when some try to login in at the same username and password at the same time ? Best Regards ..!

Altering form in drupal?

Hook_form_alter Drupal hook function or hook_form_alter(&$form, &$form_state, $form_id) Perform alterations before a form is rendered. One popular use of this hook is to add form elements to the node form. When altering a node form, the node object ca

What is AJAX?

Asynchronous JavaScript and XML, is a web development technique for creating interactive web applications. The intent is to make web pages feel more responsive by exchanging small amounts of data with the server behind the scenes, so that the entire w

What is the difference between constructors in PHP4 & PHP5?

Constructors – PHP4 Constructors are functions in a class that are automatically called when you create a new instance of a class with new. A function becomes a constructor, when it has the same name as the class. If a class has no constructor, the constructor of the base cla

What is meant by Exceptional Handling?

Exceptions PHP 5 has an exception model similar to that of other programming languages. An exception can be thrown, try and caught within PHP. A Try block must include at least one catch block. Multiple catch blocks can be used to catch different classtypes; execution will co

What is meant by Virtual hosting?

Virtual hosting HTTP includes the concept of virtual hosting, where a single HTTP server can represent multiple hosts at the same IP address. A DNS server can allocate several different host names to the same IP address. When an HTTP client ma

What is meant by Session Clustering?

The Session Manager session support allows multiple server instances to share a common pool of sessions, known as a session cluster Session clustering setting up methods :

How does Database handle Sessions?

As you should be aware the HTTP protocol, as used for serving web pages, is completely stateless. This means that after the server has received a request, processed it and sent a response, the process which dealt with that request dies. Anything that

What is the difference between include and include_once?

Include() The include() statement includes and evaluates the specified file. This also applies to require(). The two constructs are identical in every way except how they handle failure. include() produces a Warning while require() results in a Fatal Error.

Tell me some thing about mod_rewrite and url rewriting?

Mod_rewrite *************

What are static methods?

Static Keyword Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static can not be accessed with an instantiated class object (though a static method can). The static declar

What is Phishing?

In computing, phishing is a form of criminal activity using social engineering techniques. It is characterized by attempts to fraudulently acquire sensitive information, such as passwords and credit card details, by masquerading as a trustworthy person or business in an ap

Do you know about Cross site Scripting ?

Cross-site scripting (XSS) is a security exploit in which the attacker inserts malicious coding into an link that appears to be from a trustworthy

What is session hijacking?

Session hijacking, also known as TCP session hijacking, is a method of taking over a Web user session by surreptitiously obtaining the session ID and masquerading as the authorized user. Once the user’s session ID has been accessed (through session prediction), the attacker

Authentication – General Definition

Authentication is the process of determining whether someone or something is, in fact, who or what it is declared to be. In private and public computer networks (including the Internet), authentication is commonly done through the use of logon passwords. Knowledge of the p

What is smarty?

Smarty is a template engine written in PHP. Typically, these templates will include variables —such as {$variable}— and a range of logical and loop operators to allow adaptability within of the template.

What is Model-view-controller (MVC)?

Model-view-controller (MVC) is a design pattern used in software engineering. In complex computer applications that present lots of data to the user, one often wishes to separate data (model) and user interface (view) concerns, so that changes to the user interface do not

What is the difference between mysql_fetch_object and mysql_fetch_array?

Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. mysql_fetch_object() example

How can we submit a form without a submit button?

We can use a simple JavaScript code linked to an event trigger of any form field. In the JavaScript code, we can call the document.form.submit() function to submit the form

What is the difference between GET and POST methods in form submitting? Give the cases where we can use GET and POST methods?

The main difference between GET and POST is how the form data is passing. Both are used for passing form field values. All the values which is submitted by the GET method will be appended to the URL. Where as POST method send the data with out appending the URL(

What is the difference between strstr() and stristr()?

Strstr — Find first occurrence of a string strstr() example stristr — Case-insensitive strstr() stristr() example

What is meant by PEAR in php?

PEAR PHP Extension and Application Repository PEAR is the next revolution in PHP. This repository is bringing higher level programming to PHP. PEAR is a framework and distribution system for reusable PHP components. It eases installation by bringing an automated wiz

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

A) sizeof($urarray) This function is an alias of count() b) count($urarray)

What is the difference between the functions unlink() and unset()?

Unlink is a function for file system handling. It will simply delete the file in context unset will set UNSET the variable

What is meant by urlencode and urldecode?

String urlencode(str) where str contains a string like this “hello world” and the return value will be URL encoded and can be use to append with URLs, normaly used to appned data for GET like someurl.com?var=hello%world string urldocode(str)

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 in

What is the maximum length for database, table & column names?

database- 64 table -64 columns-64 alias-255

What are the commands to find the structure of a MySQL table other than EXPLAIN command?

Describe table_name

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 avalue 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(10) will waste 5 bytes if we store ‘testname&rsqu

What is the functionality of md5 function in PHP?

Calculate the md5 hash of a string. The hash is a 32-character hexadecimal number.

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

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

What is MIME?

MIME is Multipurpose Internet Mail Extensions is an internet standard for the format of e-mail. Howewer browsers also uses MIME standart to transm

Is it possible to pass data from JavaScript to PHP?

A. Yes, but not without sending another HTTP request. B. Yes, because PHP executes before JavaScript. C. No, because JavaScript is ser

what is session_start() ?

When a user first encounters a page in your application that call ssession start(),a sessionis created for the user.PHP generates a random session identifier to identify the user,and then it sends a set-Cookieheader to the client.By default,the name of this cookie is PHPSE

How do you convert an old fashioned 10 digit ISBN to a new 13 digit ISBN using php ?

function isbn10_to_13($isbnold){ if (strlen($isbnold) != 10){ // Make sure we have a 10 digit string to start return ‘Invalid ISBN-10

What’s foreign data in php?

* Anything from a form * Anything from $_GET, $_POST, $_REQUEST * Cookies ($_COOKIES) * Web services data * Files

What is str_split function in php?

According to PHP official manual It is used to converts a string to an array. If the optional split_length parameter is specified, the returned array will be broken down into chunks with each being split_length in length, otherwise each chunk will be one character

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

There are two methods AES_ENCRYPT () and AES_DECRYPT ()

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

SELECT COUNT(*) FROM tb_nme;

Where MyISAM table is stored ?

Each MyISAM table is stored on disk in three files. The ‘.frm&r

How many types of buffers does use MySQL?

Global buffers and per-connection buffers

what is the use of –i-am-a-dummy flag in MySql?

It Makes the MySQL engine refuse UPDATE and DELETE commands where the WHERE clause is not present.

Is MySQL better than MSSQL ?

Mysql is the most popular open source database server right now. It is used by large enteprise level companies and small, single websites. Is mysql actually better? ——————————— Mysql 5.

What is the Use of “WITH ROLLUP” in Mysql?

http://www.w3answers.com

How to determine the number of rows in the full result set and also restrict the number of rows that a query returns….

How to determine the number of rows in the full result set and also restrict the number of rows that a query returns,without running a second query ? Most of the developers using 2 queries to find total numbe

What is the maximum length of a table name, a database name, or a field name in MySQL?

Database name: 64 characters Table name: 64 characters Column name: 64 characters

How many values can the SET function of MySQL take?

MySQL SET function can take zero or more values, but at the maximum it can take 64 values.

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

SELECT CURTIME(); SELECT CURDATE(); SELECT CURRENT_TIME();

What is the difference between CHAR and VARCHAR data types?

Ans: CHAR is a fixed length data type.

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

Using DATEDIFF() SELECT DATEDIFF(NOW(),’2007-07-15’);

what is database testing and what we test in database testing?

Database testing basically include the following. 1)Data validity testing. 2)Data Integritity testing 3)Performance related to data base. 4)Testing of Procedure,triggers and functions. for doing data validity testing you should be good in SQL q

How can we take a backup of mysql table and restore it?

These are the simplest method to backup and restore the MySQl table For taking the bakup of all the databases mysqldump –user {user

Is it possible to set a time expire page in PHP.?

Yes it is Using header(“Expires: Mon, 26 Jul 2007 05:00:00 GMT&qu

How can we save an image from a remote web server to my web server using PHP?

what is the output of 2^2 in php ?

The answer is 0 (Zero) Important note Everyone expected answer would be 4.But answer is zero.How it happened only in php ? The ^ oper

what is the output of below script?

a. echo ‘line 3’; b. echo ‘line 2’; c. Error d. None of the above Ans: b (Answer is line2)

What is the output here?

a. hello sunil b. Parse error c. hello $x d. syntax error ANS: c published by http://www.w3answers.com

Tutoring Online – Cookies and Sessions

Hi my dear friends. Everybody knows what is cookie and session. But let me tell a truth, most of the beginners don’t know properly what is happening in cookies and sessions and what is the real use .I have taken so many Interviews but none of them given a good

What is PHP?

PHP: Hypertext Preprocessor, an open source, server-side, HTML embedded scripting language used to create dynamic Web pages.

What can PHP do?

Anything. PHP is mainly focused on server-side scripting, so you can do anything any other CGI program can do, such as coll

Your first PHP script – “Hello World”

PHP Test

How we can pass data from PHP to ASP,ASP.net?

PHP to ASP Let’s first look at how you can pass data from PHP to ASP using WDDX. You create a WDDX packet by first serializi

How can you block certain IP Addresses from accessing your site?

What Storage Engines do you use in MySQL?

MySQL Engines

What is Apache?

The most widely available HTTP server on the Internet. It supports the PERL and PHP languages.

Installing PHP on your Computer?

You can download apache2triad from

How to convert ASP Arrays to PHP and viceversa ?

ASP Arrays to PHP WDDX also allows more-complicated data structures to be passed between applications. Here we will pass an array from an ASP WDDX script to a PHP script.

Which of the following represents the proper way to set a session variable?

A. $_SESSION[‘foo’] = ‘bar’; B. session_start(); C. session_set_save_handler (‘myopen’, ‘myclose’, ‘myread’, ‘mywrite’, ‘mydelete’, ‘mygarbage&

PHP Functions for WDDX

PHP has a few other functions that can be useful when you’re working with WDDX:

what output do you get here?

a. home b. Array c. test d. httpd ANS: httpd

Which of the following functions is most efficient for substituting fixed patterns in strings?

A. preg_replace() B. str_replace() C. str_ireplace() D. substr_replace()

Which function in PHP gives us absolute path of a file on the server?

Ans: getcwd() Here I have stored my files under httdocs (using php5,i haven’t checked under php4) so I get the output as C:\apache2triad\htdocs you may get your path information while runnings the above code. :)

what is the output here ?

The output : http://www.w3answers.com and warning as below Warning: Unknown: Your script possibly relies on a session side-effect which existed until PHP 4.2.3. Please be advise

what is the output ?

a. ouch b. echo c. none d. Parse error ANS: a

How can we extract string “w3answers.com” from a string mailto:info@w3answers.com using regular expression of PHP ?

Answer:  <?php $w3 = “mailto:info@w3answers.com”; preg_match(‘|.*@([^?]*)|’,$w3,$w3output); echo $w3output[1]; ?>

Why should we use Object oriented concepts in php ?

1. Object oriented PHP code is much more reusable because by its’ very nature, it is modular. 2. Object oriented PHP is easier to update. Again, because PHP code is organised into objects. 3. Object oriented PHP makes team programming much easier

which is faster mysql_unbuffered_query or mysql_query ?

When we do the select queries that retrieve large data sets from MySQL, mysql_unbuffered_query in PHP is likely to give better performance than mysql_query. PHP manual says, it “sends a SQL query query to MySQL, without fetching

How to capture content from the output buffer ? or Give me an example for Output caching in php?

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

$message is a simple variable whereas $$message is a variable’s variable,which means value of the variable. Example: $user = ‘bob’ is equivalent to $message = ‘user’; $$message = ‘bob’;

what is the php solution to dynamic caching ?

PHP offers an extremely simple solution to dynamic caching in the form of output buffering.

what are the most common caching policy approaches ?

1)Time triggered caching (expiry timestamp). 2)Content change triggered caching (sensitive content has changed, so cache must be updated). 3)Manually triggered caching (man

What Are PHP Arrays?

PHP arrays are associative arrays with a little extra machinery thrown in. The associative part means that arrays store element values in association with key values rather than in a strict linear index order. (If y

Are php strings immutable ?

PHP strings can be changed, but the most common practice seems to be to treat strings as immutable.Strings can be changed by treating them as character arrays and assigning directly into them, like this:

What is Memcache?

Memcache is a technology which caches objects in memory where your web application can get to them really fast. It is used by sites such as Digg.com, Facebook.com and NowPublic.com and is widely recognized as an essential ingredient in scaling any LAMP

How do I prevent Web browsers caching a page in php?

What is the process that takes place when you upload a file in php?

There are two basic things covered here. The form that will be used to post the file data to and the actual program that does the uploading. Further we will discuss the method that PHP itself suggests for uploading files. Process 1 HTML PART

Will persistent connection work in the CGI version of php ? mysql_connect() vs mysql_pconnect()?

Persistent database connections work only in the module installation of PHP. If you ask for a persistent connection in the CGI version, you will simply get a regular connection.

What are the ‘function problems’ you have met in php?

1)Call to undefined function we_w3answers() PHP is trying to call the function we_w3answers(), which has not been because you misspelled the name of a function (built-in or use

Explain Parse Errors ? what are the most common causes of parse errors ?

The most common category of error arises from mistyped or syntactically incorrect PHP code, which confuses the PHP parsing engine. 1)The missing semicolon If each PHP instruction is not duly finished off with a semicolon, a parse e

List out some session functions in php?

session_save_path — Get and/or set the current session save path session_is_registered — Find out whether a global variable is registered in a session session_unset — Free all session variables session_cache_expire — Ret

What is meant by Persistent Database Connections?

How many ways your web server can utilize PHP to generate web pages?

Mainly there are three ways

How to opening excel files in windows nad linux using php ?

if you’re using PHP on Windows, you can use the inbuilt COM library $excel = ne

what are the ways to check image mime types in php?

There are a few inbuilt options you can use however, for example getimagesize() can return the mimetype, as does some of the new fileinfo functions. The mime type in getimagesize is stored in ‘mime’, and can be accessed as shown below.

Given a line of text $string, how would you write a regular expression to strip all the HTML tags from it?

$stringOfText = “<p>This is a test</p>”; $expression = “/<

what you should know about cookies before start using in php?

There are a few things you should be aware of: 1. Since cookies are used to record info

what are the database space-saving functions available in php ?

# Use ip2long() and long2ip() to store the IP adresses as Integers instead of storing them as strings, which will reduce the

what are the security tips you should know before developing php/mysql web pages ?

1. Do not trust user input. 2. Validate user input on the server side. 3. Do not use user input directly in your MySQL queries. 4. Don’t put integers in quotes In your MySQL queries. 5. Always escape the output using ph

How to get the contents of a web page using php?

You can achieve this using curl in php see the example below.

what are the advantages of storing sessions in database?

If you store a session in a database you have several advantages:

How many HTTP headers will send to a web page(client side) from server when you use sessions (session_start()) in php ?

There are three HTTP headers included in the response: Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache

php supports following database

A) Solid & oracle b) mysql c) None of the above d) All of the above All of the above

PHP comments will be?

A) // b) /* fgfg */ c) All of the above d) First one ANS: All of the above

What is the output for the following script ?

a) syntax error b) runtime error c) all of the above d) hihihi welcome hihihi ANS: d

what is the output below mentioned?

a) String not matched b) Match found c) All of the above d) None of the above ANS : b (no

what is the output below mentioned ?

a) Error b) APPLE c) Apple d) None of the above ANS : APPLE

what is the output below mentioned?

a) mmer b) mer c) all of the above d) none of the above ANS: none of the above NOTE: if we execute the above code we get the output as ‘m programmer’

what is the output here?

a) false b) true c) error d) declaration error ANS : true

what output do you get here?

Www.w3answers.com w3answers.blogspot.com Ans:Array NOTE: use ‘foreach($r as $v)’ then try to output value ‘echo $v’ or use Print_r($r) so if we make above script as

what is scandir() ?

Www.w3answers.com List files and directories inside the specified path By default files order will be ascending $f = scandir($direct, 1); it will display the files as descending order

What function would you use to redirect the browser to a new page?

1. redir() 2. header() 3. location() 4. redirect() ANS:header()

What function can you use to open a file for reading and writing?

1. fget(); 2. file_open(); 3. fopen(); 4. open_file(); ANS:fopen();

How can you get round the stateless nature of HTTP using PHP?

ANS: using Sessions in PHP

What would the following code print to the browser? Why?

Ans: 10 because,its a call by value.$num is static here. change the above code as

What are the different functions in sorting an array?

Ans:

How can we know the number of elements in an array using php?

Ans:There are two ways: 1) sizeof($myarray) – This function is an alias of count() 2) count($array) – This function returns the number of elements in an array. Note if you just pass a simple variable instead of an array, count() will retur

How can we know the number of elements in an array using php?

Ans: There are two ways: 1) sizeof($myarray) – This function is an alias of count() 2) count($array) – This function returns the number of elements in an array. Note if you just pass a simple variable instead of an array, count() will return 1.

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

What will be the following script output?

A. 2 B. 1 C. Null D. True E. 3 Answer A is correct. Because of operator precedence, the modulus operation is performed first, yielding a result of 2 (the remainder of the division of 5 by 2). Then, the result of this operation is

Which data type will the $a variable have at the end of the following script?

A. (int) 1 B. (string) “1” C. (bool) True D. (float) 1.0 E. (float) 1 Answer B is correct. When a numeric string is assigned to a variable, it remains a string, and it is not converted until needed because of an operation that

What will be the following script output?

A. 2 B. 1 C. 3 D. 0 E. Null Answer B is correct.

what is ajax? when ajax was born?

“AJAX is an acronym for Asynchronous JavaScript and XML. If you think it doesn’t say much, we agree. Simply put, AJAX can be read “empowered JavaScript”, because it essentially offers a technique for client-side JavaScript to make background server calls(such as from PHP,ASP.NET,

What API function provides the connection between the client and server?

ANS:XMLHttpRequest

Should I use an HTTP GET or POST for my AJAX calls?

AJAX requests should use an HTTP GET request when retrieving data where the data will not change for a given request URL. An HTTP POST should be used when state is updated on the server. This is in line with HTTP idem potency recommendations and is highly recommended for a consis

What is MySQL?

MySQL (pronounced “my ess cue el”) is an open source relational database management system (RDBMS) that uses Structured Query Language (SQL), the most popular language for adding, accessing, and processing data in a database. Because it is open source, anyone can download MySQL a

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.

What does a special set of tags do in PHP?

What does a special set of tags <?= and ?> do in PHP?
The output is displayed directly to the browser.

How do you define a constant?

Via define() directive, like define (”MYCONSTANT”, 100);

What are the differences between require and include, include_once?

Anwser 1:
require_once() and include_once() are both the functions to include and evaluate the specified file only once. If the specified file is included previous to the present call occurrence, it will not be done again.

But require() and include() will do it as many times they are asked to do.

Anwser 2:
The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. The major difference between include() and require() is that in failure include() produces a warning message whereas require() produces a fatal errors.

Anwser 3:
All three are used to an include file into the current page.
If the file is not present, require(), calls a fatal error, while in include() does not.

The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. It des not call a fatal error if file not exists. require_once() does the same as include_once(), but it calls a fatal error if file not exists.

Anwser 4:
File will not be included more than once. If we want to include a file once only and further calling of the file will be ignored then we have to use the PHP function include_once(). This will prevent problems with function redefinitions, variable value reassignments, etc.

What is meant by urlencode and urldecode?

Anwser 1:
urlencode() returns the URL encoded version of the given string. URL coding converts special characters into % signs followed by two hex digits. For example: urlencode(”10.00%”) will return “10%2E00%25″. URL encoded strings are safe to be used as part of URLs.
urldecode() returns the URL decoded version of the given string.

Anwser 2:
string urlencode(str) – Returns the URL encoded version of the input string. String values to be used in URL query string need to be URL encoded. In the URL encoded version:

Alphanumeric characters are maintained as is.
Space characters are converted to “+” characters.
Other non-alphanumeric characters are converted “%” followed by two hex digits representing the converted character.

string urldecode(str) – Returns the original string of the input URL encoded string.

For example:

$discount =”10.00%”;
$url = “http://domain.com/submit.php?disc=”.urlencode($discount);
echo $url;

You will get “http://domain.com/submit.php?disc=10%2E00%25″.

How To Get the Uploaded File Information in the Receiving Script?

Once the Web server received the uploaded file, it will call the PHP script specified in the form action attribute to process them. This receiving PHP script can get the uploaded file information through the predefined array called $_FILES. Uploaded file information is organized in $_FILES as a two-dimensional array as:

  • $_FILES[$fieldName][‘name’] – The Original file name on the browser system.
  • $_FILES[$fieldName][‘type’] – The file type determined by the browser.
  • $_FILES[$fieldName][‘size’] – The Number of bytes of the file content.
  • $_FILES[$fieldName][‘tmp_name’] – The temporary filename of the file in which the uploaded file was stored on the server.
  • $_FILES[$fieldName][‘error’] – The error code associated with this file upload.

The $fieldName is the name used in the <INPUT TYPE=FILE, NAME=fieldName>.

What is the difference between mysql_fetch_object and mysql_fetch_array?

MySQL fetch object will collect first single matching record where mysql_fetch_array will collect all matching records from the table in an array

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. For example, “php myScript.php”, assuming “php” is the command to invoke the CLI program.
Be aware that if your PHP script was written for the Web CGI interface, it may not execute properly in command line environment.

I am trying to assign a variable the value of 0123, but it keeps coming up with a different number, what’s the problem?

PHP Interpreter treats numbers beginning with 0 as octal. Look at the similar PHP interview questions for more numeric problems.

Would I use print “$a dollars” or “{$a} dollars” to print out the amount of dollars in this example?

In this example it wouldn’t matter, since the variable is all by itself, but if you were to print something like “{$a},000,000 mln dollars”, then you definitely need to use the braces.

What are the different tables present in MySQL? Which type of table is generated when we are creating a table in the following syntax: create table employee(eno int(2),ename varchar(10))?

Total 5 types of tables we can create
1. MyISAM
2. Heap
3. Merge
4. INNO DB
5. ISAM
MyISAM is the default storage engine as of MySQL 3.23. When you fire the above create query MySQL will create a MyISAM table.

How To Create a Table?

If you want to create a table, you can run the CREATE TABLE statement as shown in the following sample script:

<?php
include “mysql_connection.php”;

$sql = “CREATE TABLE fyi_links (”
. ” id INTEGER NOT NULL”
. “, url VARCHAR(80) NOT NULL”
. “, notes VARCHAR(1024)”
. “, counts INTEGER”
. “, time TIMESTAMP DEFAULT sysdate()”

. “)”;
if (mysql_query($sql, $con)) {
print(”Table fyi_links created.\n”);
} else {
print(”Table creation failed.\n”);
}

mysql_close($con);
?>

Remember that mysql_query() returns TRUE/FALSE on CREATE statements. If you run this script, you will get something like this:

Table fyi_links created.

How can we encrypt the username and password using PHP?

Answer1
You can encrypt a password with the following Mysql>SET PASSWORD=PASSWORD(”Password”);

Answer2
You can use the MySQL PASSWORD() function to encrypt username and password. For example,
INSERT into user (password, …) VALUES (PASSWORD($password”)), …);

How do you pass a variable by value?

Just like in C++, put an ampersand in front of it, like $a = &$b

WHAT IS THE FUNCTIONALITY OF THE FUNCTIONS STRSTR() AND STRISTR()?

string strstr ( string haystack, string needle ) returns part of haystack string from the first occurrence of needle to the end of haystack. This function is case-sensitive.

stristr() is idential to strstr() except that it is case insensitive.

When are you supposed to use endif to end the conditional statement?

When the original if was followed by : and then the code block without braces.

How can we send mail using JavaScript?

No. There is no way to send emails directly using JavaScript.

But you can use JavaScript to execute a client side email program send the email using the “mailto” code. Here is an example:

function myfunction(form)
{
tdata=document.myform.tbox1.value;
location=”mailto:mailid@domain.com?subject=…”;
return true;
}

What is the functionality of the function strstr and stristr?

strstr() returns part of a given string from the first occurrence of a given substring to the end of the string. For example: strstr(”user@example.com”,”@”) will return “@example.com”.
stristr() is idential to strstr() except that it is case insensitive.

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

eregi_replace() function is identical to ereg_replace() except that it ignores case distinction when matching alphabetic characters.

How do I find out the number of parameters passed into function9. ?

func_num_args() function returns the number of parameters passed in.

What is the purpose of the following files having extensions: frm, myd, and myi? What 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,

If the variable $a is equal to 5 and variable $b is equal to character a, what’s the value of $$b?

5, it’s a reference to existing variable.

Write a query for the following question

The table tbl_sites contains the following data:

—————————————

Userid sitename country
—————————————
1 sureshbabu indian
2 PHPprogrammer andhra
3 PHP.net usa
4 PHPtalk.com germany
5 MySQL.com usa
6 sureshbabu canada
7 PHPbuddy.com pakistan

8. PHPtalk.com austria
9. PHPfreaks.com sourthafrica
10. PHPsupport.net russia
11. sureshbabu australia
12. sureshbabu nepal
13. PHPtalk.com italy

Write a select query that will be displayed the duplicated site name and how many times it is duplicated? …

SELECT sitename, COUNT(*) AS NumOccurrences
FROM tbl_sites

GROUP BY sitename HAVING COUNT(*) > 1

How To Protect Special Characters in Query String?

If you want to include special characters like spaces in the query string, you need to protect them by applying the urlencode() translation function. The script below shows how to use urlencode():

<?php
print(”<html>”);
print(”<p>Please click the links below”

.” to submit comments about FYICenter.com:</p>”);
$comment = ‘I want to say: “It\’s a good site! :->”‘;
$comment = urlencode($comment);
print(”<p>”
.”<a href=\”processing_forms.php?name=Guest&comment=$comment\”>”

.”It’s an excellent site!</a></p>”);
$comment = ‘This visitor said: “It\’s an average site! ”‘;
$comment = urlencode($comment);
print(”<p>”
.’<a href=”processing_forms.php?’.$comment.’”>’

.”It’s an average site.</a></p>”);
print(”</html>”);
?>

Are objects passed by value or by reference?

Everything is passed by value.

What are the differences between DROP a table and TRUNCATE a table?

DROP TABLE table_name – This will delete the table and its data.

TRUNCATE TABLE table_name – This will delete the data of the table, but not the table definition.

What are the differences between GET and POST methods in form submitting, give the case where we can use GET and we can use POST methods?

Anwser 1:

When we submit a form, which has the GET method it displays pair of name/value used in the form at the address bar of the browser preceded by url. Post method doesn’t display these values.

Anwser 2:

When you want to send short or small data, not containing ASCII characters, then you can use GET” Method. But for long data sending, say more then 100 character you can use POST method.

Once most important difference is when you are sending the form with GET method. You can see the output which you are sending in the address bar. Whereas if you send the form with POST” method then user can not see that information.

Anwser 3:

What are “GET” and “POST”?

GET and POST are methods used to send data to the server: With the GET method, the browser appends the data onto the URL. With the Post method, the data is sent as “standard input.”

Major Difference

In simple words, in POST method data is sent by standard input (nothing shown in URL when posting while in GET method data is sent through query string.

Ex: Assume we are logging in with username and password.

GET: we are submitting a form to login.php, when we do submit or similar action, values are sent through visible query string (notice ./login.php?username=…&password=… as URL when executing the script login.php) and is retrieved by login.php by $_GET[‘username’] and $_GET[‘password’].

POST: we are submitting a form to login.php, when we do submit or similar action, values are sent through invisible standard input (notice ./login.php) and is retrieved by login.php by $_POST[‘username’] and $_POST[‘password’].

POST is assumed more secure and we can send lot more data than that of GET method is limited (they say Internet Explorer can take care of maximum 2083 character as a query string).

Anwser 4:

In the get method the data made available to the action page ( where data is received ) by the URL so data can be seen in the address bar. Not advisable if you are sending login info like password etc. In the post method the data will be available as data blocks and not as query string in case of get method.

Anwser 5:

When we submit a form, which has the GET method it pass value in the form of query string (set of name/value pair) and display along with URL. With GET we can a small data submit from the form (a set of 255 character) whereas Post method doesn’t display value with URL. It passes value in the form of Object and we can submit large data from the form.

Anwser 6:

On the server side, the main difference between GET and POST is where the submitted is stored. The $_GET array stores data submitted by the GET method. The $_POST array stores data submitted by the POST method.
On the browser side, the difference is that data submitted by the GET method will be displayed in the browser’s address field. Data submitted by the POST method will not be displayed anywhere on the browser.
GET method is mostly used for submitting a small amount and less sensitive data. POST method is mostly used for submitting a large amount or sensitive data.

How do you call a constructor for a parent class?

parent::constructor($value)

WHAT ARE THE DIFFERENT TYPES OF ERRORS IN PHP?

Here are three basic types of runtime errors in PHP:

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

Internally, these variations are represented by twelve different error types

What’s the special meaning of __sleep and __wakeup?

__sleep returns the array of all the variables than need to be saved, while __wakeup retrieves them.

How can we submit a form without a submit button?

If you don’t want to use the Submit button to submit a form, you can use normal hyper links to submit a form. But you need to use some JavaScript code in the URL of the link. For example:

<a href=”javascript: document.myform.submit();”>Submit Me</a>

Why doesn’t the following code print the newline properly? <?php $str = ‘Hello, there.\nHow are you?\nThanks for visiting fyicenter’; print $str; ?>

Because inside the single quotes the \n character is not interpreted as newline, just as a sequence of two characters – \ and n.

Would you initialize your strings with single quotes or double quotes?

Since the data inside the single-quoted string is not parsed for variable substitution, it’s always a better idea speed-wise to initialize a string with single quotes, unless you specifically need variable substitution.

How can we extract string ‘abc.com ‘ from a string http://info@abc.com using regular expression of php?

We can use the preg_match() function with "/.*@(.*)$/" as
the regular expression pattern. For example:
preg_match("/.*@(.*)$/","http://info@abc.com",$data);
echo $data[1];

What is the difference between the functions unlink and unset?

unlink() is a function for file system handling. It will simply delete the file in context.

unset() is a function for variable management. It will make a variable undefined.

How come the code works, but doesn’t for two-dimensional array of mine?

Any time you have an array with more than one dimension, complex parsing syntax is required. print “Contents: {$arr[1][2]}” would’ve worked.

How can we register the variables into a session?

session_register($session_var);

$_SESSION[‘var’] = ‘value’;

What is the difference between characters 23 and \x23?

The first one is octal 23, the second is hex 23.

How can we submit form without a submit button?

We can use a simple JavaScript code linked to an event trigger of any form field. In the JavaScript code, we can call the document.form.submit() function to submit the form. For example: <input type=button value=”Save” onClick=”document.form.submit()”>

How can we create a database using PHP and mysql?

We can create MySQL database with the use of mysql_create_db($databaseName) to create a database.

How many ways we can retrieve the date in result set of mysql using php?

As individual objects so single record or as a set or arrays.

Can we use include (”abc.php”) two times in a php page “makeit.php”?

Yes.

For printing out strings, there are echo, print and printf. Explain the differences.

echo is the most primitive of them, and just outputs the contents following the construct to the screen. print is also a construct (so parentheses are optional when calling it), but it returns TRUE on successful output and FALSE if it was unable to print out the string. However, you can pass multiple parameters to echo, like:

<?php echo ‘Welcome ‘, ‘to’, ‘ ‘, ‘fyicenter!’; ?>

and it will output the string “Welcome to fyicenter!” print does not take multiple parameters. It is also generally argued that echo is faster, but usually the speed advantage is negligible, and might not be there for future versions of PHP. printf is a function, not a construct, and allows such advantages as formatted output, but it’s the slowest way to print out data out of echo, print and printf.

I am writing an application in PHP that outputs a printable version of driving directions. It contains some long sentences, and I am a neat freak, and would like to make sure that no line exceeds 50 characters. How do I accomplish that with PHP?

On large strings that need to be formatted according to some length specifications, use wordwrap() or chunk_split().

What’s the output of the ucwords function in this example?

$formatted = ucwords(”FYICENTER IS COLLECTION OF INTERVIEW QUESTIONS”);
print $formatted;
What will be printed is FYICENTER IS COLLECTION OF INTERVIEW QUESTIONS.
ucwords() makes every first letter of every word capital, but it does not lower-case anything else. To avoid this, and get a properly formatted string, it’s worth using strtolower() first.

What’s the difference between htmlentities() and htmlspecialchars()?

htmlspecialchars only takes care of <, >, single quote ‘, double quote ” and ampersand. htmlentities translates all occurrences of character sequences that have different meaning in HTML.

How can we extract string “abc.com” from a string “mailto:info@abc.com?subject=Feedback” using regular expression of PHP?

$text = “mailto:info@abc.com?subject=Feedback”;
preg_match(’|.*@([^?]*)|’, $text, $output);
echo $output[1];

Note that the second index of $output, $output[1], gives the match, not the first one, $output[0].

So if md5() generates the most secure hash, why would you ever use the less secure crc32() and sha1()?

Crypto usage in PHP is simple, but that doesn’t mean it’s free. First off, depending on the data that you’re encrypting, you might have reasons to store a 32-bit value in the database instead of the 160-bit value to save on space. Second, the more secure the crypto is, the longer is the computation time to deliver the hash value. A high volume site might be significantly slowed down, if frequent md5() generation is required.

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

What are the different functions in sorting an array?

Sorting functions in PHP:
asort()
arsort()
ksort()
krsort()
uksort()
sort()

natsort()
rsort()

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

2 ways:
a) sizeof($array) – This function is an alias of count()
b) count($urarray) – This function returns the number of elements in an array.
Interestingly if you just pass a simple var instead of an array, count() will return 1.

How many ways we can pass the variable through the navigation between the pages?

At least 3 ways:

1. Put the variable into session in the first page, and get it back from session in the next page.
2. Put the variable into cookie in the first page, and get it back from the cookie in the next page.
3. Put the variable into a hidden form field, and get it back from the form in the next page.

What is the maximum length of a table name, a database name, or a field name in MySQL?

Database name: 64 characters
Table name: 64 characters
Column name: 64 characters

How many values can the SET function of MySQL take?

MySQL SET function 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 a table using MySQL commands except EXPLAIN command?

DESCRIBE table_name;

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

Use this for MySQL

SELECT COUNT(*) FROM table_name;

What’s the difference between md5(), crc32() and sha1() crypto on PHP?

The major difference is the length of the hash generated. CRC32 is, evidently, 32 bits, while sha1() returns a 128 bit value, and md5() returns a 160 bit value. This is important when avoiding collisions.

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

Here is how can you find the number of rows in a result set in PHP:

$result = mysql_query($any_valid_sql, $database_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();
SELECT CURRENT_DATE();
SELECT CURTIME();
SELECT CURRENT_TIME();

Give the syntax of GRANT commands?

The generic syntax for GRANT is as following

GRANT [rights] on [database] TO [username@hostname] IDENTIFIED BY [password]

Now rights can be:
a) ALL privilages
b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc.

We can grant rights on all databse by usingh *.* or some specific database by database.* or a specific table by database.table_name.

Give the syntax of REVOKE commands?

The generic syntax for revoke is as following

REVOKE [rights] on [database] FROM [username@hostname]

Now rights can be:
a) ALL privilages
b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc.

We can grant rights on all databse by usingh *.* or some specific database by database.* or a specific table by database.table_name.

Answer the questions with the following assumption

The structure of table view buyers is as follows:

+-------------+-------------+------+-----+---------+----------------+
| Field       | Type        | Null | Key | Default | Extra          |
+-------------+-------------+------+-----+---------+----------------+
| user_pri_id | int(15)     |      | PRI | NULL    | auto_increment |
| userid      | varchar(10) | YES  |     | NULL    |                |
+-------------+-------------+------+-----+---------+----------------+

The value of user_pri_id of the last row is 2345. What will happen in the following conditions?

Condition 1: Delete all the rows and insert another row. What is the starting value for this auto incremented field user_pri_id?

Condition 2: Delete the last row (having the field value 2345) and insert another row. What is the value for this auto incremented field user_pri_id?

In both conditions, the value of this auto incremented field user_pri_id is 2346.

What is the difference between CHAR and VARCHAR data types?

CHAR is a fixed length data type. CHAR(n) will take n characters of storage even if you enter less than n characters to that column. For example, “Hello!” will be stored as “Hello! ” in CHAR(10) column.

VARCHAR is a variable length data type. VARCHAR(n) will take only the required storage for the actual number of characters entered to that column. For example, “Hello!” will be stored as “Hello!” in VARCHAR(10) column.

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

AES_ENCRYPT() and AES_DECRYPT()

Will comparison of string “10″ and integer 11 work in PHP?

Yes, internally PHP will cast everything to the integer type, so numbers 10 and 11 will be compared.

What is the functionality of MD5 function in PHP?

string md5(string)

It calculates the MD5 hash of a string. The hash is a 32-character hexadecimal number.

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

The MySQL provides a LOAD DATA INFILE command. You can load data from a file. Great tool but you need to make sure that:

a) Data must be delimited
b) Data fields must match table columns correctly

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

Use DATEDIFF()

SELECT DATEDIFF(NOW(),’2006-07-01′);

How can we change the name of a column of a table?

This will change the name of column:

ALTER TABLE table_name CHANGE old_colm_name new_colm_name

How can we change the data type of a column of a table?

This will change the data type of a column:

ALTER TABLE table_name CHANGE colm_name same_colm_name [new data type]

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

To sort a result, use an ORDER BY clause.
The most general way to satisfy a GROUP BY clause is to scan the whole table and create a new temporary table where all rows from each group are consecutive, and then use this temporary table to discover groups and apply aggregate functions (if any).
ORDER BY [col1],[col2],…[coln]; Tells 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]; Tells DBMS to group (aggregate) 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 meant by MIME?

Answer 1:
MIME is Multipurpose Internet Mail Extensions is an Internet standard for the format of e-mail. However browsers also uses MIME standard to transmit files. MIME has a header which is added to a beginning of the data. When browser sees such header it shows the data as it would be a file (for example image)

Some examples of MIME types:

audio/x-ms-wmp
image/png
aplication/x-shockwave-flash

Answer 2:
Multipurpose Internet Mail Extensions.
WWW’s ability to recognize and handle files of different types is largely dependent on the use of the MIME (Multipurpose Internet Mail Extensions) standard. The standard provides for a system of registration of file types with information about the applications needed to process them. This information is incorporated into Web server and browser software, and enables the automatic recognition and display of registered file types. …

How can we know that a session is started or not?

A session starts by session_start() function.
This session_start() is always declared in header portion. it always declares first. then we write session_register().

What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?

Answer 1:
mysql_fetch_array() -> Fetch a result row as a combination of associative array and regular array.
mysql_fetch_object() -> Fetch a result row as an object.
mysql_fetch_row() -> Fetch a result set as a regular array().

Answer 2:

The difference between mysql_fetch_row() and mysql_fetch_array() is that the first returns the results in a numeric array ($row[0], $row[1], etc.), while the latter returns a the results an array containing both numeric and associative keys ($row[‘name’], $row[’email’], etc.). mysql_fetch_object() returns an object ($row->name, $row->email, etc.).

If we login more than one browser windows at the same time with same user and after that we close one window, then is the session is exist to other windows or not? And if yes then why? If no then why?

Session depends on browser. If browser is closed then session is lost. The session data will be deleted after session time out. If connection is lost and you recreate connection, then session will continue in the browser.

What are the MySQL database files stored in system ?

Data is stored in name.myd
Table structure is stored in name.frm
Index is stored in name.myi

What is the difference between PHP4 and PHP5?

PHP4 cannot support oops concepts and Zend engine 1 is used.

PHP5 supports oops concepts and Zend engine 2 is used.
Error supporting is increased in PHP5.
XML and SQLLite will is increased in PHP5.

Can we use include(abc.PHP) two times in a PHP page makeit.PHP”?

Yes we can include that many times we want, but here are some things to make sure of:
(including abc.PHP, the file names are case-sensitive)
there shouldn’t be any duplicate function names, means there should not be functions or classes or variables with the same name in abc.PHP and makeit.php

What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?

mysql_fetch_array – Fetch a result row as an associative array and a numeric array.

mysql_fetch_object – Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows

mysql_fetch_row() – Fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

What is meant by nl2br()?

Anwser1:
nl2br() inserts a HTML tag <br> before all new line characters \n in a string.

echo nl2br(”god bless \n you”);

output:
god bless<br>
you

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

You can use functions: AES_ENCRYPT() and AES_DECRYPT() like:

AES_ENCRYPT(str, key_str)
AES_DECRYPT(crypt_str, key_str)

How can I retrieve values from one database server and store them in other database server using PHP?

For this purpose, you can first read the data from one server into session variables. Then connect to other server and simply insert the data into the database.

WHO IS THE FATHER OF PHP AND WHAT IS THE CURRENT VERSION OF PHP AND MYSQL?

Rasmus Lerdorf.
PHP 5.1. Beta
MySQL 5.0

IN HOW MANY WAYS WE CAN RETRIEVE DATA IN THE RESULT SET OF MYSQL USING PHP?

mysql_fetch_array – Fetch a result row as an associative array, a numeric array, or both
mysql_fetch_assoc – Fetch a result row as an associative array
mysql_fetch_object – Fetch a result row as an object

mysql_fetch_row —- Get a result row as an enumerated array

What are the functions for IMAP?

imap_body – Read the message body
imap_check – Check current mailbox
imap_delete – Mark a message for deletion from current mailbox
imap_mail – Send an email message

What are encryption functions in PHP?

CRYPT()
MD5()

What is the difference between htmlentities() and htmlspecialchars()?

htmlspecialchars() – Convert some special characters to HTML entities (Only the most widely used)
htmlentities() – Convert ALL special characters to HTML entities

What is the functionality of the function htmlentities?

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 the properties (size, type, width, height) of an image using php image functions?

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 increase the execution time of a php script?

By the use of void set_time_limit(int seconds)
Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini. If seconds is set to zero, no time limit is imposed.

When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.

HOW CAN WE TAKE A BACKUP OF A MYSQL TABLE AND HOW CAN WE RESTORE IT?

Answer 1:
Create a full backup of your database: shell> mysqldump tab=/path/to/some/dir opt db_name

Or: shell> mysqlhotcopy db_name /path/to/some/dir

The full backup file is just a set of SQL statements, so restoring it is very easy:

shell> mysql “.”Executed”;

Answer 2:
To backup: BACKUP TABLE tbl_name TO /path/to/backup/directory
’ To restore: RESTORE TABLE tbl_name FROM /path/to/backup/directory

mysqldump: Dumping Table Structure and Data

Utility 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!

How to set cookies?

setcookie(’variable’,’value’,’time’)
;
variable – name of the cookie variable

value – value of the cookie variable
time – expiry time
Example: setcookie(’Test’,$i,time()+3600);

Test – cookie variable name
$i – value of the variable ‘Test’
time()+3600 – denotes that the cookie will expire after an one hour

How to reset/destroy a cookie

Reset a cookie by specifying expire time in the past:
Example: setcookie(’Test’,$i,time()-3600); // already expired time

Reset a cookie by specifying its name only
Example: setcookie(’Test’);

WHAT TYPES OF IMAGES THAT PHP SUPPORTS?

Using imagetypes() function to find out what types of images are supported in your PHP engine.
imagetypes() – Returns the image types supported.
This function returns a bit-field corresponding to the image formats supported by the version of GD linked into PHP. The following bits are returned, IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP | IMG_XPM.

CHECK IF A VARIABLE IS AN INTEGER IN JAVASCRIPT

var myValue =9.8;
if(parseInt(myValue)== myValue)

alert(’Integer’);
else
alert(’Not an integer’);

Tools used for drawing ER diagrams.

Case Studio
Smart Draw

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

Answer 1:
bool is_numeric( mixed var)

Returns TRUE if var is a number or a numeric string, FALSE otherwise.

Answer 2:
Definition and Usage
The isNaN() function is used to check if a value is not a number.

Syntax
isNaN(number)

Parameter Description
number Required. The value to be tested

How can we submit from without a submit button?

Trigger the JavaScript code on any event ( like onSelect of drop down list box, onfocus, etc ) document.myform.submit(); This will submit the form.

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 cookie?

Set the cookie with a past expiration time.

What are the current versions of Apache, PHP, and MySQL?

PHP: PHP 5.1.2
MySQL: MySQL 5.1
Apache: Apache 2.1

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.

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 is the use of friend function?

Friend functions
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.
class mylinkage

{
private:
mylinkage * prev;
mylinkage * next;

protected:
friend void set_prev(mylinkage* L, mylinkage* N);
void set_next(mylinkage* L);

public:
mylinkage * succ();

mylinkage * pred();
mylinkage();
};

void mylinkage::set_next(mylinkage* L) { next = L; }

void set_prev(mylinkage * L, mylinkage * N ) { N->prev = L; }

Friends in other classes
It is possible to specify a member function of another class as a friend as follows:
class C

{
friend int B::f1();
};
class B
{
int f1();
};

It is also possible to specify all the functions in another class as friends, by specifying the entire class as a friend.
class A

{
friend class B;
};

Friend functions allow binary operators to be defined which combine private data in a pair of objects. This is particularly powerful when using the operator overloading features of C++. We will return to it when we look at overloading.

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

$second = date(”s”);

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

You can change maximum size of a file set upload_max_filesize variable in php.ini file

How can I make a script that can be bilingual (supports English, German)?

You can change charset variable in above line in the script to support bilanguage.

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.

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.

CREATE PROCEDURE simpleproc (OUT param1 INT)
-> BEGIN
-> SELECT COUNT(*) INTO param1 FROM t;
-> END//

CALL sp_name([parameter[,…]])
CALL sp_name[()]

The CALL statement invokes a stored procedure that was defined previously

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.

CREATE
[DEFINER = { user | CURRENT_USER }]
TRIGGER trigger_name trigger_time trigger_event
ON tbl_name FOR EACH ROW trigger_body

mysql> delimiter //
mysql> CREATE TRIGGER ins_trig BEFORE INSERT ON Emp
-> FOR EACH ROW
-> BEGIN
-> UPDATE Employee SET Salary=Salary-300 WHERE Perks>500;
-> END;
-> //

The general syntax of DROP TRIGGER is :
DROP TRIGGER trigger_name

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.

CREATE TABLE employee_records (
name VARCHAR(50),
employeeID INT, INDEX (employeeID)
)
CREATE INDEX id_index ON employee_records2(employeeID)

What is MYSQL Injection?

SQL injection refers to the act of someone inserting a MySQL statement to be run on your database without your knowledge. Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a MySQL statement that you will unknowingly run on your database.

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 Limit
Linux 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

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 Form
The 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 Form
Where 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

What’s the difference between accessing a class method via -> and via ::?

:: is allowed to access methods that can perform static operations, i.e. those, which do not require object initialization.

What are the advantages and disadvantages of CASCADE STYLE SHEETS?

External Style Sheets
Advantages
Can 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 contexts

Disadvantages

An 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 definitions

Embedded 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

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

How can increase the performance of MySQL select query?

We can use LIMIT to stop MySql for further search in table after we have received our required no. of records, also we can use LEFT JOIN or RIGHT JOIN instead of full join in cases we have related data in two or more tables.

How can we change the name of a column of a table?

MySQL query to rename table: RENAME TABLE tbl_name TO new_tbl_name
or,

ALTER TABLE tableName CHANGE OldName newName.

When you want to show some part of a text displayed on an HTML page in red font color? What different possibilities are there to do this? What are the advantages/disadvantages of these methods?

There are 2 ways to show some part of a text in red:

1. Using HTML tag <font color=”red”>
2. Using HTML tag <span style=”color: red”>

When viewing an HTML page in a Browser, the Browser often keeps this page in its cache. What can be possible advantages/disadvantages of page caching? How can you prevent caching of a certain page (please give several alternate solutions)?

When you use the metatag in the header section at the beginning of an HTML Web page, the Web page may still be cached in the Temporary Internet Files folder.

A page that Internet Explorer is browsing is not cached until half of the 64 KB buffer is filled. Usually, metatags are inserted in the header section of an HTML document, which appears at the beginning of the document. When the HTML code is parsed, it is read from top to bottom. When the metatag is read, Internet Explorer looks for the existence of the page in cache at that exact moment. If it is there, it is removed. To properly prevent the Web page from appearing in the cache, place another header section at the end of the HTML document. For example:

What are the different ways to login to a remote server? Explain the means, advantages and disadvantages?

There is at least 3 ways to logon to a remote server:
Use ssh or telnet if you concern with security
You can also use rlogin to logon to a remote server.

Please give a regular expression (preferably Perl/PREG style), which can be used to identify the URL from within a HTML link tag.

Try this: /href=”([^”]*)”/i

How can I use the COM components in php?

The COM class provides a framework to integrate (D)COM components into your PHP scripts.
string COM::COM( string module_name [, string server_name [, int codepage]]) – COM class constructor.

Parameters:

module_name: name or class-id of the requested component.
server_name: name of the DCOM server from which the component should be fetched. If NULL, localhost is assumed. To allow DCOM com, allow_dcom has to be set to TRUE in php.ini.
codepage – specifies the codepage that is used to convert php-strings to unicode-strings and vice versa. Possible values are CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 and CP_UTF8.
Usage:
$word->Visible = 1; //open an empty document
$word->Documents->Add(); //do some weird stuff

$word->Selection->TypeText(”This is a test…”);
$word->Documents[1]->SaveAs(”Useless test.doc”); //closing word
$word->Quit(); //free the object
$word->Release();
$word = null;

How many ways we can give the output to a browser?

HTML output
PHP, ASP, JSP, Servlet Function
Script Language output Function
Different Type of embedded Package to output to a browser

What is the default session time in php and how can I change it?

The default session time in php is until closing of browser

What changes I have to do in php.ini file for file uploading?

Make the following line uncomment like:
; Whether to allow HTTP file uploads.

file_uploads = On
; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
upload_tmp_dir = C:\apache2triad\temp
; Maximum allowed size for uploaded files.
upload_max_filesize = 2M

How can I set a cron and how can I execute it in Unix, Linux, and windows?

Cron is very simply a Linux module that allows you to run commands at predetermined times or intervals. In Windows, it’s called Scheduled Tasks. The name Cron is in fact derived from the same word from which we get the word chronology, which means order of time.
The easiest way to use crontab is via the crontab command.

# crontab

This command ‘edits’ the crontab. Upon employing this command, you will be able to enter the commands that you wish to run. My version of
Linux uses the text editor vi. You can find information on using vi here.

The syntax of this file is very important – if you get it wrong, your crontab will not function properly. The syntax of the file should be as follows:
minutes hours day_of_month month day_of_week command

All the variables, with the exception of the command itself, are numerical constants. In addition to an asterisk (*), which is a wildcard that allows any value, the ranges permitted for each field are as follows:

Minutes: 0-59
Hours: 0-23
Day_of_month: 1-31

Month: 1-12
Weekday: 0-6

We can also include multiple values for each entry, simply by separating each value with a comma.
command can be any shell command and, as we will see momentarily, can also be used to execute a Web document such as a PHP file.
So, if we want to run a script every Tuesday morning at 8:15 AM, our mycronjob file will contain the following content on a single line:

15 8 * * 2 /path/to/scriptname

This all seems simple enough, right? Not so fast! If you try to run a PHP script in this manner, nothing will happen (barring very special configurations that have PHP compiled as an executable, as opposed to an Apache module). The reason is that, in order for PHP to be parsed, it needs to be passed through Apache. In other words, the page needs to be called via a browser or other means of retrieving

Web content. For our purposes, I’ll assume that your server configuration includes wget, as is the case with most default configurations. To test your configuration, log in to shell. If you’re using an RPM-based system (e.g. Redhat or Mandrake), type the following:

# wget help

If you are greeted with a wget package identification, it is installed in your system.
You could execute the PHP by invoking wget on the URL to the page, like so:

# wget http://www.example.com/file.php

Now, let’s go back to the mailstock.php file we created in the first part of this article. We saved it in our document root, so it should be accessible via the Internet. Remember that we wanted it to run at 4PM Eastern time, and send you your precious closing bell report? Since I’m located in the Eastern timezone, we can go ahead and set up our crontab to use 4:00, but if you live elsewhere, you might have to compensate for the time difference when setting this value.
This is what my crontab will look like:

0 4 * * 1,2,3,4,5 wget http://www.example.com/mailstock.php

Steps for the payment gateway processing?

An online payment gateway is the interface between your merchant account and your Web site. The online payment gateway allows you to immediately verify credit card transactions and authorize funds on a customer’s credit card directly from your Web site. It then passes the transaction off to your merchant bank for processing, commonly referred to as transaction batching

How many ways I can redirect a PHP page?

Here are the possible ways of php page redirection.

1. Using Java script:
‘; echo ‘window.location.href=”‘.$filename.’”;’; echo ”; echo ”; echo ”; echo ”; } } redirect(’http://maosjb.com’); ?>

2. Using php function: header(”Location:http://maosjb.com “);

List out different arguments in PHP header function?

void header ( string string [, bool replace [, int http_response_code]])

What type of headers have to be added in the mail function to attach a file?

$boundary = ‘–’ . md5( uniqid ( rand() ) );
$headers = “From: \”Me\”\n”;

$headers .= “MIME-Version: 1.0\n”;
$headers .= “Content-Type: multipart/mixed; boundary=\”$boundary\””;

How to store the uploaded file to the final location?

move_uploaded_file ( string filename, string destination)

This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP’s HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.

If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.

If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued.

What is the difference between Reply-to and Return-path in the headers of a mail function?

Reply-to: Reply-to is where to delivery the reply of the mail.

Return-path: Return path is when there is a mail delivery failure occurs then where to delivery the failure notification.

Explain about Type Juggling in php?

PHP does not require (or support) explicit type definition in variable declaration; a variable’s type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable $var, $var becomes a string. If you then assign an integer value to $var, it becomes an integer.

An example of PHP’s automatic type conversion is the addition operator ‘+’. If any of the operands is a float, then all operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does NOT change the types of the operands themselves; the only change is in how the operands are evaluated.

$foo += 2; // $foo is now an integer (2)
$foo = $foo + 1.3; // $foo is now a float (3.3)
$foo = 5 + “10 Little Piggies”; // $foo is integer (15)
$foo = 5 + “10 Small Pigs”; // $foo is integer (15)

If the last two examples above seem odd, see String conversion to numbers.

If you wish to change the type of a variable, see settype().
If you would like to test any of the examples in this section, you can use the var_dump() function.
Note: The behavior of an automatic conversion to array is currently undefined.

Since PHP (for historical reasons) supports indexing into strings via offsets using the same syntax as array indexing, the example above leads to a problem: should $a become an array with its first element being “f”, or should “f” become the first character of the string $a? The current versions of PHP interpret the second assignment as a string offset identification, so $a becomes “f”, the result of this automatic conversion however should be considered undefined. PHP 4 introduced the new curly bracket syntax to access characters in string, use this syntax instead of the one presented above:

How can I embed a java programme in php file and what changes have to be done in php.ini file?

There are two possible ways to bridge PHP and Java: you can either integrate PHP into a Java Servlet environment, which is the more stable and efficient solution, or integrate Java support into PHP. The former is provided by a SAPI module that interfaces with the Servlet server, the latter by this Java extension.
The Java extension provides a simple and effective means for creating and invoking methods on Java objects from PHP. The JVM is created using JNI, and everything runs in-process.

Example Code:

getProperty(’java.version’) . ”; echo ‘Java vendor=’ . $system->getProperty(’java.vendor’) . ”; echo ‘OS=’ . $system->getProperty(’os.name’) . ‘ ‘ . $system->getProperty(’os.version’) . ‘ on ‘ . $system->getProperty(’os.arch’) . ‘ ‘; // java.util.Date example $formatter = new Java(’java.text.SimpleDateFormat’, “EEEE, MMMM dd, yyyy ‘at’ h:mm:ss a zzzz”); echo $formatter->format(new Java(’java.util.Date’)); ?>

The behaviour of these functions is affected by settings in php.ini.
Table 1. Java configuration options
Name
Default
Changeable
java.class.path
NULL
PHP_INI_ALL
Name Default Changeable

java.home
NULL
PHP_INI_ALL
java.library.path
NULL
PHP_INI_ALL
java.library
JAVALIB
PHP_INI_ALL

How To Turn On the Session Support?

The session support can be turned on automatically at the site level, or manually in each PHP page script:

  • Turning on session support automatically at the site level: Set session.auto_start = 1 in php.ini.
  • Turning on session support manually in each page script: Call session_start() funtion.

Explain the ternary conditional operator in PHP?

Expression preceding the ? is evaluated, if it’s true, then the expression preceding the : is executed, otherwise, the expression following : is executed.

What’s the difference between include and require?

It’s how they handle failures. If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.

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 cookie?

Set the cookie in past.

How To Read the Entire File into a Single String?

If you have a file, and you want to read the entire file into a single string, you can use the file_get_contents() function. It opens the specified file, reads all characters in the file, and returns them in a single string. Here is a PHP script example on how to file_get_contents():

<?php
$file = file_get_contents(”/windows/system32/drivers/etc/services”);
print(”Size of the file: “.strlen($file).”\n”);

?>

This script will print:

Size of the file: 7116

1.    How do you start and stop MySQL on Windows? – net start MySQL, net stop MySQL
2.    How do you start MySQL on Linux? – /etc/init.d/mysql start
3.    Explain the difference between mysql and mysqli interfaces in PHP? – mysqli is the object-oriented version of mysql library functions.
4.    What’s the default port for MySQL Server? – 3306
5.    What does tee command do in MySQL? – tee followed by a filename turns on MySQL logging to a specified file. It can be stopped by command notee.
6.    Can you save your connection settings to a conf file? – Yes, and name it ~/.my.conf. You might want to change the permissions on the file to 600, so that it’s not readable by others.
7.    How do you change a password for an existing user via mysqladmin? – mysqladmin -u root -p password “newpassword”
8.    Use mysqldump to create a copy of the database? – mysqldump -h mysqlhost -u username -p mydatabasename > dbdump.sql
9.    Have you ever used MySQL Administrator and MySQL Query Browser? Describe the tasks you accomplished with these tools.
10.    What are some good ideas regarding user security in MySQL? – There is no user without a password. There is no user without a user name. There is no user whose Host column contains % (which here indicates that the user can log in from anywhere in the network or the Internet). There are as few users as possible (in the ideal case only root) who have unrestricted access.
11.    Explain the difference between MyISAM Static and MyISAM Dynamic. – In MyISAM static all the fields have fixed width. The Dynamic MyISAM table would include fields such as TEXT, BLOB, etc. to accommodate the data types with various lengths. MyISAM Static would be easier to restore in case of corruption, since even though you might lose some data, you know exactly where to look for the beginning of the next record.
12.    What does myisamchk do? – It compressed the MyISAM tables, which reduces their disk usage.
13.    Explain advantages of InnoDB over MyISAM? – Row-level locking, transactions, foreign key constraints and crash recovery.
14.    Explain advantages of MyISAM over InnoDB? – Much more conservative approach to disk space management – each MyISAM table is stored in a separate file, which could be compressed then with myisamchk if needed. With InnoDB the tables are stored in tablespace, and not much further optimization is possible. All data except for TEXT and BLOB can occupy 8,000 bytes at most. No full text indexing is available for InnoDB. TRhe COUNT(*)s execute slower than in MyISAM due to tablespace complexity.
15.    What are HEAP tables in MySQL? – HEAP tables are in-memory. They are usually used for high-speed temporary storage. No TEXT or BLOB fields are allowed within HEAP tables. You can only use the comparison operators = and <=>. HEAP tables do not support AUTO_INCREMENT. Indexes must be NOT NULL.
16.    How do you control the max size of a HEAP table? – MySQL config variable max_heap_table_size.
17.    What are CSV tables? – Those are the special tables, data for which is saved into comma-separated values files. They cannot be indexed.
18.    Explain federated tables. – Introduced in MySQL 5.0, federated tables allow access to the tables located on other databases on other servers.
19.    What is SERIAL data type in MySQL? – BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT
20.    What happens when the column is set to AUTO INCREMENT and you reach the maximum value for that table? – It stops incrementing. It does not overflow to 0 to prevent data losses, but further inserts are going to produce an error, since the key has been used already.
21.    Explain the difference between BOOL, TINYINT and BIT. – Prior to MySQL 5.0.3: those are all synonyms. After MySQL 5.0.3: BIT data type can store 8 bytes of data and should be used for binary data.
22.    Explain the difference between FLOAT, DOUBLE and REAL. – FLOATs store floating point numbers with 8 place accuracy and take up 4 bytes. DOUBLEs store floating point numbers with 16 place accuracy and take up 8 bytes. REAL is a synonym of FLOAT for now.
23.    If you specify the data type as DECIMAL (5,2), what’s the range of values that can go in this table? – 999.99 to -99.99. Note that with the negative number the minus sign is considered one of the digits.
24.    What happens if a table has one column defined as TIMESTAMP? – That field gets the current timestamp whenever the row gets altered.
25.    But what if you really want to store the timestamp data, such as the publication date of the article? – Create two columns of type TIMESTAMP and use the second one for your real data.
26.    Explain data type TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP – The column exhibits the same behavior as a single timestamp column in a table with no other timestamp columns.
27.    What does TIMESTAMP ON UPDATE CURRENT_TIMESTAMP data type do? – On initialization places a zero in that column, on future updates puts the current value of the timestamp in.
28.    Explain TIMESTAMP DEFAULT ‘2006:09:02 17:38:44′ ON UPDATE CURRENT_TIMESTAMP. – A default value is used on initialization, a current timestamp is inserted on update of the row.
29.    If I created a column with data type VARCHAR(3), what would I expect to see in MySQL table? – CHAR(3), since MySQL automatically adjusted the data type.

Q 1- How to setup admin user for MYSQL ?
Ans:
Login as super user ‘root’ in mysql and execute the following commands.
mysql> use mysql;
mysql> create user ‘test’@’%’ identified by ‘test’;
mysql> grant all on *.* to ‘test’@’%’ with grant option;
mysql> flush privileges;
Q 2- What types of privileges are there in MySQL ?
Ans:
There are 4 types of privileges.
i). Global privileges like *.* (all hosts connecting to Mysql db server)
Example: GRANT SELECT, INSERT ON *.* TO ‘someuser’@’somehost’;
ii). Database privileges like .*
Example: GRANT SELECT, INSERT ON mydb.* TO ‘someuser’@’somehost’;
iii). Table privileges like SELECT, INSERT, UPDATE, DELETE
Example: GRANT SELECT, INSERT ON mydb.mytbl TO ‘someuser’@’somehost’;
iv). Column privileges like
Example: GRANT SELECT (col1), INSERT (col1,col2) ON mydb.mytbl TO ‘someuser’@’somehost’;
Q 3- How to find the version of MySQL ?
Ans:
mysql> select version();
Q 4- How do I limit the number of rows I get out of my database?
Ans:
SELECT name FROM table LIMIT [, ] ;
if you want to get the rows between 10 and 20 do the following:
SELECT name FROM table LIMIT 10, 20 ;
Q 5- Is it possible to insert multiple rows using single command in MySQL ?
Ans:
Yes. Please see below example.
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9) ;
Q 6- I am getting the following error while logging into “mytest” database.
ERROR 1044 (42000): Access denied for user ‘phpzag’@’localhost’ to database ‘mytest’.
Ans:
Please refer the error to DBA asking for granting the privilege to “mytest” database.
mysql > grant all on test.* to ‘user_name’ @ ‘host_name’ ;
Q 7- What is null value in MySQL ?
Ans:
In MySQL NULL is only equal to NULL, but NULL is not equal to ‘ ‘ ( blank value ) or 0(zero).
Q 8- How can I check if a table in MySQL database already exists?
Ans:
Command : SHOW TABLES LIKE ‘%’;
Q 8- Convert datetime from MST (db servers timezone) into GMT returns NULL value, how to solve it?
Ans:
Database should be updated with timezone value from OS otherwise Mysq

1.    What is DDL, DML and DCL? – If you look at the large variety of SQL commands, they can be divided into three large subgroups. Data Definition Language deals with database schemas and descriptions of how the data should reside in the database, therefore language statements like CREATE TABLE or ALTER TABLE belong to DDL. DML deals with data manipulation, and therefore includes most common SQL statements such SELECT, INSERT, etc. Data Control Language includes commands such as GRANT, and mostly concerns with rights, permissions and other controls of the database system.
2.    How do you get the number of rows affected by query? – SELECT COUNT (user_id) FROM users would only return the number of user_id’s.
3.    If the value in the column is repeatable, how do you find out the unique values? – Use DISTINCT in the query, such as SELECT DISTINCT user_firstname FROM users; You can also ask for a number of distinct values by saying SELECT COUNT (DISTINCT user_firstname) FROM users;
4.    How do you return the a hundred books starting from 25th? – SELECT book_title FROM books LIMIT 25, 100. The first number in LIMIT is the offset, the second is the number.
5.    You wrote a search engine that should retrieve 10 results at a time, but at the same time you’d like to know how many rows there’re total. How do you display that to the user? – SELECT SQL_CALC_FOUND_ROWS page_title FROM web_pages LIMIT 1,10; SELECT FOUND_ROWS(); The second query (not that COUNT() is never used) will tell you how many results there’re total, so you can display a phrase “Found 13,450,600 results, displaying 1-10″. Note that FOUND_ROWS does not pay attention to the LIMITs you specified and always returns the total number of rows affected by query.
6.    How would you write a query to select all teams that won either 2, 4, 6 or 8 games? – SELECT team_name FROM teams WHERE team_won IN (2, 4, 6, 8)
7.    How would you select all the users, whose phone number is null? – SELECT user_name FROM users WHERE ISNULL(user_phonenumber);
8.    What does this query mean: SELECT user_name, user_isp FROM users LEFT JOIN isps USING (user_id) – It’s equivalent to saying SELECT user_name, user_isp FROM users LEFT JOIN isps WHERE users.user_id=isps.user_id
9.    How do you find out which auto increment was assigned on the last insert? – SELECT LAST_INSERT_ID() will return the last value assigned by the auto_increment function. Note that you don’t have to specify the table name.
10.    What does –i-am-a-dummy flag to do when starting MySQL? – Makes the MySQL  engine refuse UPDATE and DELETE commands where the WHERE clause is not present.
11.    On executing the DELETE statement I keep getting the error about foreign key constraint failing. What do I do? – What it means is that so of the data that you’re trying to delete is still alive in another table. Like if you have a table for universities and a table for students, which contains the ID of the university they go to, running a delete on a university table will fail if the students table still contains people enrolled at that university. Proper way to do it would be to delete the offending data first, and then delete the university in question. Quick way would involve running SET foreign_key_checks=0 before the DELETE command, and setting the parameter back to 1 after the DELETE is done. If your foreign key was formulated with ON DELETE CASCADE, the data in dependent tables will be removed automatically.
12.    When would you use ORDER BY in DELETE statement? – When you’re not deleting by row ID. Such as in DELETE FROM techinterviews_com_questions ORDER BY timestamp LIMIT 1. This will delete the most recently posted question in the table techinterviews_com_questions.
13.    How can you see all indexes defined for a table? – SHOW INDEX FROM techinterviews_questions;
14.    How would you change a column from VARCHAR(10) to VARCHAR(50)? – ALTER TABLE techinterviews_questions CHANGE techinterviews_content techinterviews_CONTENT VARCHAR(50).
15.    How would you delete a column? – ALTER TABLE techinterviews_answers DROP answer_user_id.
16.    How would you change a table to InnoDB? – ALTER TABLE techinterviews_questions ENGINE innodb;
17.    When you create a table, and then run SHOW CREATE TABLE on it, you occasionally get different results than what you typed in. What does MySQL modify in your newly created tables? –
1.    VARCHARs with length less than 4 become CHARs
2.    CHARs with length more than 3 become VARCHARs.
3.    NOT NULL gets added to the columns declared as PRIMARY KEYs
4.    Default values such as NULL are specified for each column
18.    How do I find out all databases starting with ‘tech’ to which I have access to? – SHOW DATABASES LIKE ‘tech%’;
19.    How do you concatenate strings in MySQL? – CONCAT (string1, string2, string3)
20.    How do you get a portion of a string? – SELECT SUBSTR(title, 1, 10) from techinterviews_questions;
21.    What’s the difference between CHAR_LENGTH and LENGTH? – The first is, naturally, the character count. The second is byte count. For the Latin characters the numbers are the same, but they’re not the same for Unicode and other encodings.
22.    How do you convert a string to UTF-8? – SELECT (techinterviews_question USING utf8);
23.    What do % and _ mean inside LIKE statement? – % corresponds to 0 or more characters, _ is exactly one character.
24.    What does + mean in REGEXP? – At least one character. Appendix G. Regular Expressions from MySQL manual is worth perusing before the interview.
25.    How do you get the month from a timestamp? – SELECT MONTH(techinterviews_timestamp) from techinterviews_questions;
26.    How do you offload the time/date handling to MySQL? – SELECT DATE_FORMAT(techinterviews_timestamp, ‘%Y-%m-%d’) from techinterviews_questions; A similar TIME_FORMAT function deals with time.
27.    How do you add three minutes to a date? – ADDDATE(techinterviews_publication_date, INTERVAL 3 MINUTE)
28.    What’s the difference between Unix timestamps and MySQL timestamps? – Internally Unix timestamps are stored as 32-bit integers, while MySQL timestamps are stored in a similar manner, but represented in readable YYYY-MM-DD HH:MM:SS format.
29.    How do you convert between Unix timestamps and MySQL timestamps? – UNIX_TIMESTAMP converts from MySQL timestamp to Unix timestamp, FROM_UNIXTIME converts from Unix timestamp to MySQL timestamp.
30.    What are ENUMs used for in MySQL? – You can limit the possible values that go into the table. CREATE TABLE months (month ENUM ‘January’, ‘February’, ‘March’,…); INSERT months VALUES (’April’);
31.    How are ENUMs and SETs represented internally? – As unique integers representing the powers of two, due to storage optimizations.

Content
•    Search with special characters
•    Why is InnoDB disabled?
•    How to find MySQL system information?
•    What is the difference between MySQL certified server and community server?
•    MySQL monitoring
•    MySQL backup
•    Corrupt MyISAM table
•    How to compile MySQL
•    Test restore procedure
•    Reset a MySQL user password
•    Reset the MySQL root user password
•    How to enable the InnoDB plug-in
•    Storage Engines shipped with MariaDB / MySQL
•    Compiling MySQL Cluster ndb-test fails
•    NDB information schema does not show up
•    Hyper Threading (HT) enabled?
•    How to make a patch for MariaDB?
•    Where does the InnoDB AUTO-INC waiting come from?
•    My character encoding seems to be wrong. How can I fix it?
•    I think my Slave is not consistent to its Master anymore. How can I check this?
•    My MySQL Server is swapping from time to time. This gives hick-ups in MySQL. How can I avoid this?

Search with special characters
Question: How can I search the following string in a text field: ‘%newline,tabluator,b)%’?
Answer:
CREATE TABLE spec(txt VARCHAR(255));

INSERT INTO spec values (‘bla\tbla\nbla’);
INSERT INTO spec values (‘\n\tb)’);
INSERT INTO spec values (‘abc\n\tb)xyz’);

SELECT * FROM spec;

SELECT * FROM spec WHERE txt LIKE ‘\n\tb)’;
SELECT * FROM spec WHERE txt LIKE ‘%\n\tb)%’;
SELECT * FROM spec WHERE txt REGEXP ‘^\n\tb)$’;
SELECT * FROM spec WHERE txt REGEXP ‘\n\tb)’;

Why is InnoDB disabled?
Question: After reconfiguring the my.conf InnoDB was disabled. Why?
Answer: This can happen when the InnoDB logfile size (innodb_log_file_size) was set to an new value which is not compatible with the old value.
To avoid this problem shut-down MySQL properly (mysqladmin –user=root shutdown). Then backup and after remove the logfiles, configure the my.cnf with the new logfile size. Start MySQL again and check the error.log.

How to find MySQL system information?
Question: How can I find MySQL stytem information?
Answer:
Operating System
Linux:
$ uname -a
$ cat /etc/SuSE-release
$ cat /proc/version
MySQL libraries
$ ldconfig -p | grep -i mysql
MySQL client
$ mysql –version
MySQL server
mysql> STATUS;
mysql> SELECT VERSION();
mysql> SHOW VARIABLES LIKE ‘version%’;

$ mysqladmin version -p
MySQL Table versions
SELECT table_schema, table_name, engine, version, row_format
FROM information_schema.tables
WHERE table_type = ‘BASE TABLE’
ORDER BY table_schema, table_name
;

What is the difference between MySQL certified server and community server?
Question: What is the difference between MySQL certified server and community server?
Answer:
MySQL certified server    MySQL community server
•    Chosen software by MySQL
•    Based on internal quality/feature completeness    •    Serves as base for Certified Server
•    New MySQL Forge helps get contributions!
•    Profits from community testing
•    Receives additional internal/external testing    •    Receives community and basic internal testing
•    Contains no untested/certified feature    •    May contain features for community testing
•    Infrequent major releases    •    Frequent releases (early and often)
•    Under active development
•    Tiered patch releases (every month to once/qtr)    •    Contains patches plus new features
•    Recommended to partners, ISV’s, Enterprise deployment    •    Not recommended to partners, ISV’s
•    Certified on most popular platforms    •    Offered on over two dozen platforms
•    Formal support through MySQL AB    •    Informal support via forums, etc.

MySQL monitoring
Question: How can I monitor MySQL related system information, status and activities?
Answer: MySQL monitoring solutions

MySQL backup
Question: How to do backup?
Answer:
# for both
cp /etc/my.cnf $BACKUP_DIR/my_$BACKUP_TIMESTAMP.cnf

# for MyISAM
BACKUP_TIMESTAMP=`date ‘+%Y-%m-%d_%H-%M-%S’`
BACKUP_DIR=’/mybackupdir’
mysqldump –user=root –all-databases –flush-privileges –lock-all-tables –master-data=1 –quick \
–flush-logs –triggers –routines –events > $BACKUP_DIR/full_dump_$BACKUP_TIMESTAMP.sql

# for InnoDB
BACKUP_TIMESTAMP=`date ‘+%Y-%m-%d_%H-%M-%S’`
BACKUP_DIR=’/mybackupdir’
mysqldump –user=root –all-databases –flush-privileges –single-transaction –master-data=1 –quick \
–flush-logs –triggers –routines –events > $BACKUP_DIR/full_dump_$BACKUP_TIMESTAMP.sql
* –flush-privileges works since 5.1.12
Caution: If you have a mixed environment (MyISAM AND InnoDB) it becomes a little bit more complicated!
Question: Is LVM snapshot a feasible way to take MySQL/InnoDB backups?
Answer: It depends! If you stop MySQL it should work well. If you have MyISAM tables only, then FLUSH TABLES WITH READ LOCK should guarantee a consistent backup. With InnoDB a LVM snapshot should work as well because it is the same situation as in a sever crash. It becomes a problem when the InnoDB log files are located on a different disk than the data files. FLUSH TABLES WITH READ LOCK is in this situation not sufficient for InnoDB because InnoDB still may write some data in the background which can corrupt your LVM snapshot over 2 devices.
There were some cases reported where MySQL/InnoDB refused to recover from a LVM snapshot backup with core dump:
InnoDB: Progress in percents: 0 1 2 3 mysqld got signal 11;
Innobase never approved LVM snapshots as valid way of taking backups! If these are technical or marketing reasons I do not know.
If you choose LVM snapshot as a backup method we recommend to do a restore-test of the backup and restart the database to see if it recovers successfully. Then you are sure your backup is a valid one.
Literature
[1] MySQL Backups using LVM Snapshots
[2] MySQL Server Backup, Restoration, And Disaster Recovery Planning Presentation
[3] Using LVM for MySQL Backup and Replication Setup
[4] Logical volume management
[5] Backup of MySQL Databases on Logical Volumes

Corrupt MyISAM table
Question: How does a corrupt MyISAM table look like?
Answer: InnoDB tables should not get corrupted at all. MyISAM tables can get courrupted after system failure. You should NEVER run corrupted MyISAM tables. I can even get worse! Do always a check after a crash. How you can find if a table got corrupted and how you can repare it again is shown below:
mysql> CHECK TABLE test;
+———–+——-+———-+——————————————————-+
| Table     | Op    | Msg_type | Msg_text                                              |
+———–+——-+———-+——————————————————-+
| test.test | check | warning  | 1 client is using or hasn’t closed the table properly |
| test.test | check | error    | Key in wrong position at page 3072                    |
| test.test | check | error    | Corrupt                                               |
+———–+——-+———-+——————————————————-+
3 rows in set (0.05 sec)

mysql> SELECT COUNT(*) FROM test;
ERROR 145 (HY000): Table ‘./test/test’ is marked as crashed and should be repaired

mysql> REPAIR TABLE test;
+———–+——–+———-+————————————————–+
| Table     | Op     | Msg_type | Msg_text                                         |
+———–+——–+———-+————————————————–+
| test.test | repair | warning  | Number of rows changed from 11000000 to 10000000 |
| test.test | repair | status   | OK                                               |
+———–+——–+———-+————————————————–+
2 rows in set (29 min 17.80 sec)

061004  9:43:50 [ERROR] /usr/local/bin/mysqld: Table ‘./test/test’ is marked as crashed and
should be repaired
061004 10:13:24 [Note] Found 10000000 of 11000000 rows when repairing ‘./test/test’

How to compile MySQL
Question: How do I compile MySQL on platforms were no binaries are provided?
Answer: Recently we wanted to run MySQL on a 64bit PPC Linux platform. We compiled it as follows:
CC=”gcc” CFLAGS=”-O3 -mpowerpc -m64 -mcpu=powerpc” CXX=”gcc” \
CXXFLAGS=”-O3 -m64 -mpowerpc -mcpu=powerpc” \
./configure –prefix=/app/mysql/5.0.37

make

make install
If you never compiled something on your Linux machine before maybe some necessary tools are missing:
•    gmake
•    autoconf
•    automake
•    libtool
•    m4
•    bison
Further very often there are some header files of standard libraries not installed:
•    libreadline-dev
•    libncurses5-dev
If you install all those it should work…
MySQL Documentation: Installing MySQL from a Standard Source Distribution

Test restore procedure
Question: Why should I regularly test my restore procedure?
Answer: You should test your restore procedure on a regular base to make sure it actually works, when you really need it.
See the following real life examples MySQL users were experiencing:
When I backup the database with the command:
shell> mysqldump –user=root -p –hex-blob –max_allowed_packet=128M -x -t test > test_dump.sql
everything works fine. But when I try to restore the database I get the following error:
mysql –user=root -p –max_allowed_packet=128M test < test_dump.sql
ERROR 1153 (08S01) at line 87: Got a packet bigger than ‘max_allowed_packet’ bytes
In this case you possibly would have found the problem already before you have to do the real emergency restore.

Reset a MySQL user password
Question: How do I reset a Password for a MySQL user?
Answer: For a regular MySQL or MariaDB user you can reset the Password with the SET PASSWORD command:
mysql> SET PASSWORD FOR ‘app_owner’@’%.mysite.com’ = PASSWORD(‘secret’);
Consider, that the user in MySQL always consist of a username AND a domain name.
Literature
[1] SET PASSWORD Syntax

Reset the MySQL root user password
Question: How do I reset the MySQL root user password?
Answer: To reset the MySQL or MariaDB root user password you have 2 possibilities:
1.    Restart the mysqld with an init-file where you reset the root password.
2.    Restart the mysqld with the skip-grant-tables option and then reset the root password.
Possibility one: Restart the mysqld with the init-file parameter:
1.    Create a file with the reset commands in a location where nobody else than the MySQL user has access to:
2.    — reset_root_user_password.sql
3.    UPDATE mysql.user SET password = PASSWORD(‘secret’) WHERE user = ‘root’;
FLUSH PRIVILEGES;
4.    Hook this reset command file into your my.cnf
5.    # my.cnf
6.    [mysqld]
init-file = /home/mysql/secret/reset_root_user_password.sql
7.    Stop or kill mysqld
shell> kill `cat <datadir>/<host_name>.pid`
8.    Verify that mysqld was stopped properly:
shell> pgrep mysqld
9.    Start mysqld
shell> /etc/init.d/mysql start
Now you should be capable to use the new root user password.
10.    Remove the init-file parameter again from the my.cnf and delete the reset_root_user_password.sql script.
This methode requires only one database restart.
Possibility two: Restart the mysqld with the skip-grant-tables parameter:
1.    Add the skip-grant-tables parameter to your my.cnf:
2.    # my.cnf
3.    [mysqld]
skip-grant-tables = 1
4.    Stop or kill mysqld
shell> kill `cat <datadir>/host_name.pid`
5.    Verify that mysqld was stopped properly:
shell> pgrep mysqld
6.    Start mysqld
shell> /etc/init.d/mysql start
7.    Now you can login without any password:
shell> mysql –user=root
8.    Reset the root user password:
9.    mysql> UPDATE mysql.user SET password = PASSWORD(‘secret’) WHERE user = ‘root’;
mysql> FLUSH PRIVILEGES;
10.    Remove the skip-grant-tables parameter from the my.cnf.
11.    Restart the mysqld again to protect its security.
shell> /etc/init.d/mysql restart
This methtode requires for security reasons two database restarts.
You can use both methods with mysqld command options as well.
Literature
[1] How to Reset the Root Password
[2] MySQL Server Command Option init-file
[3] MySQL Server Comand Option skip-grant-tables

How to enable the InnoDB plug-in
Question: How do I enable the InnoDB plug-in?
Answer: You can enable the InnoDB plug-in in 3 different ways:
•    In the MySQL Client with the INSTALL PLUGIN command.
•    When starting the mysqld with command line parameters.
•    In the MySQL configuration file:
# my.cnf
[mysqld]
ignore_builtin_innodb
plugin-load=innodb=ha_innodb_plugin.so;innodb_trx=ha_innodb_plugin.so;innodb_locks=ha_innodb_plugin.so;\
innodb_lock_waits=ha_innodb_plugin.so;innodb_cmp=ha_innodb_plugin.so;innodb_cmp_reset=ha_innodb_plugin.so;\
innodb_cmpmem=ha_innodb_plugin.so;innodb_cmpmem_reset=ha_innodb_plugin.so
Pleased make sure that the plugin-load parameter is a one-liner.
You get the following possibilities:
Distribution    Version    Type    Maker    Version
MySQL    5.0    built-in only    Innobase    ?
MariaDB    5.1    built-in only    Percona    1.0
MySQL    5.1    built-in and plug-in    Innobase    ? / 1.0
MariaDB    5.2    built-in only    Percona    1.0
MySQL    5.5    built-in only    Innobase    1.1

Storage Engines shipped with MariaDB / MySQL
Question: What storage engines do I get with MySQL and MariaDB?
Answer: Depending on the release and the distribution you are using you get different Storage Engines. The details you can find in the following matrix:
mysql> SHOW ENGINES;
MySQL
Engine     5.0     5.1     5.5
ARCHIVE     YES     YES     YES
BerkeleyDB    NO
BLACKHOLE     YES     YES     YES
CSV     YES     YES     YES
EXAMPLE     NO     NO
FEDERATED     YES     NO     NO
InnoDB     YES     YES     DEFAULT
ISAM     NO
MEMORY     YES     YES     YES
MRG_MYISAM    YES     YES     YES
MyISAM     DEFAULT     DEFAULT    YES
ndbcluster    DISABLED    NO
Remarks:
•    From MySQL 5.0 to 5.1 BerkleyDB (BDB) and ISAM Storage Engines were removed and Federated Storage Engine was disabled.
•    In 5.5 it looks like the EXAMPLE and the FEDEREATED Storage Engines are not included any more.
•    With 5.5 InnoDB is the new default Storage Engine.
•    The NDB Storage Engine is not support with MySQL 5.5 yet.
MariaDB
Engine     5.1     5.2     5.3
ARCHIVE     YES     YES     YES
Aria         YES     YES
BLACKHOLE     YES     YES     YES
CSV     YES     YES     YES
EXAMPLE     YES     YES     YES
FEDERATED     YES     YES     YES
InnoDB         YES     YES
MARIA     YES
MEMORY     YES     YES     YES
MRG_MYISAM    YES     YES     YES
MyISAM     DEFAULT    DEFAULT    DEFAULT
OQGRAPH         YES
PBXT     YES     YES     YES
SPHINX         YES     YES
Remarks:
•    In MariaDB 5.1 the FEDERATED Storage Engine is integraded in the form of the FederatedX Storage Engine.
•    InnoDB was not taken into MariaDB 5.1. PBXT acts as a substitue for InnoDB.
•    In MariaDB 5.2 the Maria Storage Engine was renamed into Aria and InnoDB comes back in form of XtraDB.
•    The new OQGraph Storage Engine was added with MariaDB 5.2 as well.
•    OQGraph did not build with MariaDB 5.3.0 any more but it is still included in the source code. So I assume this is a bug of this early alpha release.
For more information about the different Storage Engines available see also MySQL Pluggable Storage Engines

Compiling MySQL Cluster ndb-test fails
Question: When I want to compile flexAsynch I get some odd compiling errors.
Answer: We had a similar problem, when we added one include directive the problem disappeared.
When we compiled MySQL Cluster 7.1.9a as follows:
./configure –with-plugins=max –with-ndb-test ; make -j 4
we got the following error message:
g++ -DHAVE_CONFIG_H -DNDEBUG   -I. -I../../../../include -I../../../../storage/ndb/test/include -I. \
-I../../../../include -I../../../../storage/ndb/include -I../../../../include -I../../../../mysys \
-I../../../../storage/ndb/include -I../../../../storage/ndb/include/util \
-I../../../../storage/ndb/include/portlib -I../../../../storage/ndb/include/logger \
-I../../../../storage/ndb/include/mgmapi -I. -I../../../../include \
-I../../../../storage/ndb/include -I../../../../include -I../../../../storage/ndb/include \
-I../../../../storage/ndb/include/ndbapi -I../../../../storage/ndb/include/util \
-I../../../../storage/ndb/include/portlib -I../../../../storage/ndb/test/include \
-I../../../../storage/ndb/include/mgmapi -I../../../../storage/ndb/include/kernel \
-I../../../../storage/ndb/src/ndbapi -I../../../../storage/ndb/include/debugger \
-I../../../../ndb/src/mgmapi -I../../../../ndb/src/mgmsrv -I../../../../ndb/include/mgmcommon \
-DDEFAULT_PREFIX=”\”/usr/local\”” -O3 -fno-implicit-templates -fno-exceptions -fno-rtti -MT atrt-db.o \
-MD -MP -MF .deps/atrt-db.Tpo -c -o atrt-db.o `test -f ‘db.cpp’ || echo ‘./’`db.cpp
main.cpp: In function ‘bool parse_args(int, char**)’:
main.cpp:560: error: ‘lstat’ was not declared in this scope
main.cpp:741: error: ‘lstat’ was not declared in this scope
main.cpp:749: error: ‘S_ISREG’ was not declared in this scope
560   if (argc > 1 && lstat(argv[argc-1], &sbuf) == 0)
741     if (lstat(tmp.c_str(), &sbuf) != 0)
749     if (!S_ISREG(sbuf.st_mode))
This only happens with the –with-ndb-test directive but NOT without! So we assume, that there must be something wrong in the sources, which does not show up on the developers machines…
By just adding the following line to all failing parts (there were 2 or 3 of them):
#include <sys/stat.h>
it worked out for us.

NDB information schema does not show up
Question: When I start my MySQL 7.1 Cluster the NDB information schema does not show up. What can I do?
Answer: This happens in some cases. The reason is not known to us. Seems something like a bug.
When you look at the log MySQL seems to be aware of the NDB information schema:
110125  9:00:24 [Note] NDB: Creating mysql.ndb_schema
110125  9:00:24 [Note] NDB: Flushing mysql.ndb_schema
110125  9:00:24 [Note] NDB Binlog: CREATE TABLE Event: REPL$mysql/ndb_schema
110125  9:00:24 [Note] NDB Binlog: logging ./mysql/ndb_schema (UPDATED,USE_WRITE)

mysql> SHOW DATABASES;
+——————–+
| Database           |
+——————–+
| information_schema |
| mysql              |
| test               |
+——————–+
As mentioned in Bug #54552 ndbinfo missing although activated after online upgrade a mysql_upgrade will help to solve the problem:
shell> mysql_upgrade

mysql> SHOW PLUGINS;
+————+———-+—————-+———+———+
| Name       | Status   | Type           | Library | License |
+————+———-+—————-+———+———+
| ndbcluster | ACTIVE   | STORAGE ENGINE | NULL    | GPL     |
| ndbinfo    | ACTIVE   | STORAGE ENGINE | NULL    | GPL     |
+————+———-+—————-+———+———+

mysql> SHOW DATABASES;
+——————–+
| Database           |
+——————–+
| information_schema |
| mysql              |
| ndbinfo            |
| test               |
+——————–+

Hyper Threading (HT) enabled?
Question: How can I find if Hyper Threading (HT) is enable on my machine?
Answer: /proc/cpuinfo will tell you if Hyper Threading (HT) is enabled on your machine or not:
# cat /proc/cpuinfo | egrep ‘siblings|cpu cores’ | sort | uniq
cpu cores       : 2
siblings        : 4
If the values of cpu cores and siblings are equal, then hyper threading is DISABLED otherwise ENABLED.
On some Linux distributions (RedHat, CentOS) you can even set Hyper Threading online: Is hyper-threading enabled on a Linux system?

How to make a patch for MariaDB?
Question: I have found a bug for MariaDB and have fixed it. How do I make a patch for it?
Answer: I was told by the MariaDB developers that they would like to have it like this:
diff -up orig.cc new.cc

Where does the InnoDB AUTO-INC waiting come from?
Question: With SHOW INNODB STATUS we have seen under high load a lot of transactions waiting on AUTO_INC. Where does it come from?
Answer: This is a bug in MySQL. It looks as follows:
——- TRX HAS BEEN WAITING 10 SEC FOR THIS LOCK TO BE GRANTED:
TABLE LOCK table `test/test` trx id 0 447488123 lock mode AUTO-INC waiting
This bug will be fixed in newer MySQL 5.1 releases (>= 5.1.47) but not in MySQL 5.0.
For more details refer to:
InnoDB auto-inc scalability fixed
Bug #16979: AUTO_INC lock in InnoDB works a table level lock

My character encoding seems to be wrong. How can I fix it?
Question: It looks like my data are somehow wrong in my MySQL database. I get some strange characters. How can I fix those?
Answer: This happens when you use the wrong encoding to fill in your data in the database. How this happens and how to fix it again you can find in the following lines:
mysql> CREATE TABLE `test` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`data` varchar(64) DEFAULT NULL,
`ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=PBXT DEFAULT CHARSET=latin1

# Wrong encoding!!!
mysql> SET NAMES latin1;

mysql> INSERT INTO test VALUES (NULL, ‘äöü’, NULL);

# Data seems to be correct but are not:
mysql> SELECT data, HEX(data) FROM test;
+——–+————–+
| data   | HEX(data)    |
+——–+————–+
| äöü    | C3A4C3B6C3BC |
+——–+————–+

# Set right enconding:
mysql> SET NAMES utf8;

# Wrong umlaut encoding for latin1 column:
mysql> SELECT data, HEX(data) FROM test;
+————–+————–+
| data         | hex(data)    |
+————–+————–+
| äöü       | C3A4C3B6C3BC |
+————–+————–+

# Fix encoding
mysql> ALTER TABLE test MODIFY data VARBINARY(64);
mysql> ALTER TABLE test MODIFY data VARCHAR(64) CHARACTER SET utf8;

mysql> SHOW CREATE TABLE test\G
CREATE TABLE `test` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`data` varchar(64) CHARACTER SET utf8 DEFAULT NULL,
`ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=PBXT DEFAULT CHARSET=latin1

# Now the data are displayed correctly and encoding matches the CHARACTERSET defintion of the column
mysql> SELECT data, HEX(data) FROM test;
+——–+————–+
| data   | hex(data)    |
+——–+————–+
| äöü    | C3A4C3B6C3BC |
+——–+————–+

# Convert encoding now to latin1
mysql> ALTER TABLE test MODIFY data VARCHAR(64) CHARACTER SET latin1;

# Now the data are displayed correctly and encoding matches the CHARACTERSET defintion of the column
mysql> SELECT data, HEX(data) FROM test;
+——–+———–+
| data   | hex(data) |
+——–+———–+
| äöü    | E4F6FC    |
+——–+———–+

mysql> SHOW CREATE TABLE test\G
CREATE TABLE `test` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`data` varchar(64) DEFAULT NULL,
`ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=PBXT DEFAULT CHARSET=latin1
If the table was created with utf8 character set the procedure is as follows:
ALTER TABLE test MODIFY data VARCHAR(64) CHARACTER SET latin1;
ALTER TABLE test MODIFY data VARBINARY(64);
ALTER TABLE test MODIFY data VARCHAR(64);

I think my Slave is not consistent to its Master anymore. How can I check this?
Question: I think my Slave is not consistent to its Master anymore. How can I check this?
Answer: The best way to do it is using the Maatkit-Tools.
In the Maatkit-toolbox there is mk-table-checksum and mk-table-sync. How to use it you can find as follows:
Check
On Master:
mk-table-checksum –create-replicate-table –empty-replicate-table –replicate=test.checksum \
u=root,h=127.0.0.1 \
–tables=test.test
On Slave:
mk-table-checksum –replicate=test.checksum \
–replicate-check=1 \
u=root,h=127.0.0.1 \
–tables=test.test
Sync
On Slave:
mk-table-sync –sync-to-master  –print \
h=127.0.0.1,u=root,D=test,t=test
Then run the queries on the master…

My MySQL Server is swapping from time to time. This gives hick-ups in MySQL. How can I avoid this?
Question: My MySQL Server is swapping from time to time. This gives hick-ups in MySQL. How can I avoid this?
Answer: First of all you have to make sure, that MySQL does not over-allocate memory:
# free
total       used       free     shared    buffers     cached
Mem:      16431968    5736652   10695316          0     127876    2449008
-/+ buffers/cache:    3159768   13272200
Swap:     19802108          0   19802108

# ps aux | grep -e ‘mysqld ‘ -e ‘VSZ’ | cut -b-120
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
mysql     2020  1.8  6.1 3166896 1010840 ?     Sl   08:06  11:09 /home/mysql/product/mysql-5.6.2/bin/mysqld
If you checked this and it looks OK you can check the swappiness of your system:
# cat /proc/sys/vm/swappiness
60

# sysctl -a
# sysctl vm.swappiness
If the value is bigger than 0 you can set it either on the fly or make it permanent:
# sysctl -n vm.swappiness=0
or
#
# /etc/sysctl.conf
#
vm.swappiness=0

# sysctl -p /etc/sysctl.conf
»
•    Login or register to post comments
MySQL Doubts
Submitted by vishnuraj on Wed, 2011-04-13 08:51.
Hi everybody
Please rectify my doubts.
In my database i have three fields as id,medicinename,quantity.
In medicine name i have many different names.Many names comes twice or thrice.Now i need to fetch the data from database for particular medicine name only(this medicine name comes nearly 10 times)say for example if the medicinename is “A” it comes in id 1,4,9,12,25.Now i want to fetch the data from id 1 only.Whent the quantity comes to “0” in id “1”,i want to fetch the datas from next id.Also when the quantity comes to “0” the row shold be deleted automatically.Please help me to do this.
»
•    Login or register to post comments
Medicine table
Submitted by oli on Thu, 2011-04-21 15:19.
Hi vishnuraj
Simple examples are always good to explain or to try to understand. So I created the following table:
In my database I have 3 fields as id,medicinename,quantity.
In medicinename I have many different names. Many names comes twice or thrice.
+——+———————-+———+
| id   | medicinename         | quantiy |
+——+———————-+———+
|    1 | Trifolium arvense L. |      25 |
|    2 | Agave americana      |     120 |
|    3 | Hypericum perforatum |      12 |
|    4 | Trifolium arvense L. |      35 |
|    5 | Agave americana      |     120 |
|    6 | Trifolium arvense L. |     120 |
+——+———————-+———+
Now I need to fetch the data from database for particular medicine name only (this medicine name comes nearly 10 times) say for example if the medicinename is “A” it comes in id 1,4,9,12,25.
SELECT * FROM medicine WHERE medicinename = ‘Trifolium arvense L.’;
+——+———————-+———+
| id   | medicinename         | quantiy |
+——+———————-+———+
|    1 | Trifolium arvense L. |      25 |
|    4 | Trifolium arvense L. |      35 |
|    6 | Trifolium arvense L. |     120 |
+——+———————-+———+
So far so good. Up to here I could follow you but then I loose you:
Now I want to fetch the data from id 1 only. When the quantity comes to “0” in id “1”, I want to fetch the data from next id. Also when the quantity comes to “0” the row should be deleted automatically.
I think there is some missing business logic information in your explanation. What is meant with “when the quantity comes to 0”? Further “I want to fetch the data from next id” and “the row should deleted automatically” sounds like you mix data with business logic.
Could you please explain more in detail, what you want to achieve?

General Information About MySQL
MySQL is a very fast, multi-threaded, multi-user, and robust SQL (Structured Query Language) database server.

MySQL is free software. It is licensed with the GNU GENERAL PUBLIC LICENSE http://www.gnu.org/.
What Is MySQL
MySQL, the most popular Open Source SQL database, is provided by MySQL AB. MySQL AB is a commercial company that builds is business providing services around the MySQL database. See section 1.2 What Is MySQL AB.
ySQL is a database management system.
A database is a structured collection of data. It may be anything from a simple shopping list to a picture gallery or the vast amounts of information in a corporate network. To add, access, and process data stored in a computer database, you need a database management system such as MySQL. Since computers are very good at handling large amounts of data, database management plays a central role in computing, as stand-alone utilities, or as parts of other applications.
MySQL is a relational database management system.
A relational database stores data in separate tables rather than putting all the data in one big storeroom. This adds speed and flexibility. The tables are linked by defined relations making it possible to combine data from several tables on request. The SQL part of MySQL stands for “Structured Query Language” – the most common standardized language used to access databases.
MySQL is Open Source Software.
Open source means that it is possible for anyone to use and modify. Anybody can download MySQL from the Internet and use it without paying anything. Anybody so inclined can study the source code and change it to fit their needs. MySQL uses the GPL (GNU General Public License) http://www.gnu.org, to define what you may and may not do with the software in different situations. If you feel uncomfortable with the GPL or need to embed MySQL into a commercial application you can buy a commercially licensed version from us.
Why use MySQL?
MySQL is very fast, reliable, and easy to use. If that is what you are looking for, you should give it a try. MySQL also has a very practical set of features developed in very close cooperation with our users. You can find a performance comparison of MySQL to some other database managers on our benchmark page. See section 12.7 Using Your Own Benchmarks. MySQL was originally developed to handle very large databases much faster than existing solutions and has been successfully used in highly demanding production environments for several years. Though under constant development, MySQL today offers a rich and very useful set of functions. The connectivity, speed, and security make MySQL highly suited for accessing databases on the Internet.
The technical features of MySQL
For advanced technical information, see section 7 MySQL Language Reference. MySQL is a client/server system that consists of a multi-threaded SQL server that supports different backends, several different client programs and libraries, administrative tools, and a programming interface. We also provide MySQL as a multi-threaded library which you can link into your application to get a smaller, faster, easier to manage product. MySQL has a lot of contributed software available.

It is very likely that you will find that your favorite application/language already supports MySQL. The official way to pronounce MySQL is “My Ess Que Ell” (not MY-SEQUEL). But we try to avoid correcting people who say MY-SEQUEL.
The Main Features of MySQL
The following list describes some of the important characteristics of MySQL:

Fully multi-threaded using kernel threads. That means it can easily use multiple CPUs if available.
C, C++, Eiffel, Java, Perl, PHP, Python and Tcl APIs.
Works on many different platforms.
Many column types: signed/unsigned integers 1, 2, 3, 4, and 8 bytes long, FLOAT, DOUBLE, CHAR, VARCHAR, TEXT, BLOB, DATE, TIME, DATETIME, TIMESTAMP, YEAR, SET, and ENUM types.
Very fast joins using an optimized one-sweep multi-join.
Full operator and function support in the SELECT and WHERE parts of queries. Example:
mysql> SELECT CONCAT(first_name, ” “, last_name) FROM tbl_name
WHERE income/dependents > 10000 AND age > 30;

1 What Is MySQL?
2 What Is mSQL?
3 What Is SQL?
4 What Is Table?
5 What Is Column?
6 What Is Row?
7 What Is Primary Key?
8 What Is Foreign Key?
9 What Is Index?
10 What Is View?
11 What Is Join?
12 What Is Union?
13 What Is ISAM?
14 What Is MyISAM?
15 What Is InnoDB?
16 What Is BDB (BerkeleyDB)?
17 What Is CSV?
18 What Is Transaction?
19 What Is Commit?
20 What Is Rollback?
21 Explain what Is MySQL?
22 How To Install MySQL?
23 How To Start MySQL Server?
24 How Do You Know If Your MySQL Server Is Alive?
25 How Do You Know the Version of Your MySQL Server?
26 How To Create a Test Table in Your MySQL Server?
27 How To Shutdown MySQL Server?
28 What Tools Available for Managing MySQL Server?
29 What Is “mysqld”?
30 What Is “mysqladmin” in MySQL?
31 How To Check Server Status with “mysqladmin”?
32 How To Shut Down the Server with “mysqladmin”?
33 How To Use “mysql” to Run SQL Statements?
34 How To Show All Tables with “mysql”?
35 What Is “mysqlcheck”?
36 How To Analyze Tables with “mysqlcheck”?
37 What Is “mysqlshow”?
38 How To Show Table Names with “mysqlshow”?
39 What Is “mysqldump”?
40 How To Dump a Table to a File with “mysqldump”?
41 What Is “mysqlimport”?
42 How To Load Data Files into Tables with “mysqlimport”?
43 What Is the Command Line End User Interface – mysql?
44 What Are the “mysql” Command Line Options?
45 What Are the “mysql” Command Line Arguments?
46 How Many SQL DDL Commands Are Supported by “mysql”?
47 How Many SQL DML Commands Are Supported by “mysql”?
48 What Are the Non-Standard SQL Commands Supported by “mysql”?
49 How To Get Help Information from the Server?
50 How To Run “mysql” Commands from a Batch File?
51 How To Return Query Output in HTML Format?
52 How To Return Query Output in XML Format?
53 What Is SQL in MySQL?
54 How Many Groups of Data Types?
55 What Are String Data Types?
56 What Are the Differences between CHAR and NCHAR?
57 What Are the Differences between CHAR and VARCHAR?
58 What Are the Differences between BINARY and VARBINARY?
59 What Are Numeric Data Types?
60 What Are Date and Time Data Types?
61 How To Calculate Expressions with SQL Statements?
62 How To Include Comments in SQL Statements?
63 How To Include Character Strings in SQL statements?
64 How To Escape Special Characters in SQL statements?
65 How To Concatenate Two Character Strings?
66 How To Include Numeric Values in SQL statements?
67 How To Enter Characters as HEX Numbers?
68 How To Enter Numeric Values as HEX Numbers?
69 How To Enter Binary Numbers in SQL Statements?
70 How To Enter Boolean Values in SQL Statements?
71 What Are NULL Values?
72 What Happens If NULL Values Are Involved in Expressions?
73 How To Convert Numeric Values to Character Strings?
74 How To Convert Character Strings to Numeric Values?
75 How To Use IN Conditions?
76 How To Use LIKE Conditions?
77 How To Use Regular Expression in Pattern Match Conditions?
78 How To Use CASE Expression?
79 What Are Date and Time Data Types in MySQL?
80 How To Write Date and Time Literals?
81 How To Enter Microseconds in SQL Statements?
82 How To Convert Dates to Character Strings?
83 How To Convert Character Strings to Dates?
84 What Are Date and Time Intervals?
85 How To Increment Dates by 1 in MySQL?
86 How To Decrement Dates by 1 in MySQL?
87 How To Calculate the Difference between Two Dates?
88 How To Calculate the Difference between Two Time Values?
89 How To Present a Past Time in Hours, Minutes and Seconds?
90 How To Extract a Unit Value from a Date and Time?
91 What Are Date and Time Functions in MySQL?
92 What Is TIMESTAMP in MySQL?
93 How Many Ways to Get the Current Time?
94 What Are DDL Statements in MySQL?
95 How To Create a New Table in MySQL?
96 What Happens If You No CREATE Privilege in a Database?
97 How To Get a List of All Tables in a Database?
98 How To Get a List of Columns in an Existing Table?
99 How To See the CREATE TABLE Statement of an Existing Table?
100 How To Create a New Table by Selecting Rows from Another Table in MySQL?
101 How To Add a New Column to an Existing Table in MySQL?
102 How To Delete an Existing Column in a Table?
103 How To Rename an Existing Column in a Table?
104 How To Rename an Existing Table in MySQL?
105 How To Drop an Existing Table in MySQL?
106 How To Create a Table Index in MySQL?
107 How To Get a List of Indexes of an Existing Table?
108 How To Drop an Existing Index in MySQL?
109 How To Create a New View in MySQL?
110 How To Drop an Existing View in MySQL?

——————————————————————————–

Sort By :   Latest First  |  Oldest First  |  By Rating
Question    Rating

What is SERIAL data type in MySQL?

What?s the default port for MySQL Server?

What does “tee” command do in MySQL?

Explain about database design?

What happens when the column is set to AUTO INCREMENT and you reach the maximum value for that table?

How to connect mysql from jsp(Java Server Page)?

Explain the difference between MyISAM Static and MyISAM Dynamic

How will retrieve nth level categories from one query in mysql ?

What does myisamchk do?

what is difference between candidate key and primary key

Which version of MySQL supports Subquery?

Describe the use of PL/SQL tables

Can you save your connection settings to a conf file?

How to display nth highest record in a table for example?How to display 4th highest (salary) record from customer table?

How do you use Outer Join in MySQL

What are some good ideas regarding user security in MySQL?

Explain the difference between mysql and mysqli interfaces in PHP?

How do you change a password for an existing user via mysqladmin?

What is the Oracle rowid counterpart in MySQL?

Describe the use of %ROWTYPE and %TYPE in PL/SQL
Previous 1 2 3 4 5 6 7 8 9 Next
Sort By :   Latest First  |  Oldest First  |  By Rating
Question    Rating

State some security recommendations while using MYSQL?

When is a declare statement needed ?

Explain the difference between BOOL, TINYINT and BIT.

Explain data type TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

What does TIMESTAMP ON UPDATE CURRENT_TIMESTAMP data type do?

Explain about MYSQL and its features?

How do you start and stop MySQL on Windows?

State two considerations which can improve the performance of MYSQL?

How to see the database architecture in MySQL??

What are the advantages of mysql comparing with oracle?

Use mysqldump to create a copy of the database?

What are the advantages of Mysql comparing with oracle?

Explain about the rules which should be followed while assigning a username?

What Is “mysqladmin” in MySQL?

How To Create a New View in MySQL?

State some of the features of MYSQL?

How to create MYSQL new users?

How we can count duplicate entery in particular table against Primary Key ? What are constraints?

how to add video or audio file database

Explain about normalization?
Question    Rating

How do you control the max size of a HEAP table?

What are HEAP tables in MySQL?

Explain some of the uses of MYSQL?

How To Drop an Existing View in MySQL

What happens when we don?t use Console option?

What packages (if any) has Oracle provided for use by developers?

What happens if a table has one column defined as TIMESTAMP?

Explain federated tables

Explain about HEAP table?

How MySQL is different from SQL?

How do you configure mysql on linux

Explain about MyISAM table?

How do you start MySQL on Linux?

Explain about the time stamp field?

Explain about creating database?

How many drivers in MYSQL?

Explain about primary keys?

Comparision between SOAP and REST in PHP.


The important 10 differences between SOAP and REST are given below:

  1. SOAP is a protocol. REST is an architectural style.
  2. SOAP stands for Simple Object Access Protocol. REST stands for REpresentational State Transfer.
  3. SOAP can’t use REST because it is a protocol. REST can use SOAP web services because it is a concept and can use any protocol like HTTP, SOAP.
  4. SOAP uses services interfaces to expose the business logic. REST uses URI to expose business logic.
  5. In Java JAX-WS is the java API for SOAP web services. In Java JAX-RS is the java API for RESTful web services.
  6. SOAP defines standards to be strictly followed. REST does not define too much standards like SOAP.
  7. SOAP requires more bandwidth and resource than REST. REST requires less bandwidth and resource than SOAP.
  8. SOAP defines its own security. RESTful web services inherits security measures from the underlying transport.
  9. SOAP permits XML data format only. REST permits different data format such as Plain text, HTML, XML, JSON etc.
  10. SOAP is less preferred than REST. REST more preferred than SOAP.

REST(REpresentational State Transfer)
REST is an architectural style. It doesn’t define so many standards like SOAP. REST is for are exposing a public API over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.

SOAP(Simple Object Access Protocol)
SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.

Why Rest?

  • Since REST uses standard HTTP it is much simpler in just about ever way.
  • REST permits many different data formats where as SOAP only permits XML.
  • REST allows better support for browser clients due to it’s support for JSON.
  • REST has better performance and scalability. REST reads can be cached, SOAP based reads cannot be cached.
  • If security is not a major concern and we have limited resources. Or we want to create an API that will be easily used by other developers publicly then we should go with REST web services.

Why SOAP?

  • WS-Security: While SOAP supports SSL (just like REST) it also supports WS-Security which adds some enterprise security features.
  • WS-AtomicTransaction: Need ACID Transactions over a service, you’re going to need SOAP.
  • WS-ReliableMessaging: Rest doesn’t have a standard messaging system and expects clients to deal with communication failures by retrying.
  • SOAP is highly secure as it defines its own security.
  • If the security is a major concern and the resources are not limited then we should use SOAP web services. Like if we are creating a web service for banking related work then we should go with SOAP as here high security is needed.

REST fundamentals

  • Everything in REST is considered as a resource.
  • Every resource is identified by an URI.
  • Uses uniform interfaces. Resources are handled uing POST, GET, PUT, DELETE operations which are similar to Create, Read, update and Delete(CRUD) operations.
  • Be stateless. Every request is an independent request. Each request from client to server must contain all the information necessary to understand the request.
  • Communications are done via representations. E.g. XML, JSON RESTful Web Services A RESTFul web services are based on HTTP methods and the concept of REST. A RESTFul web service typically defines the base URI for the services, the supported MIME-types (XML, text, JSON, user-defined, …) and the set of operations (POST, GET, PUT, DELETE) which are supported.

SOAP fundamentals

  • WSDL defines contract between client and service and is static by its nature.
  • SOAP builds an XML based protocol on top of HTTP or sometimes TCP/IP.
  • SOAP describes functions, and types of data.
  • SOAP is a successor of XML-RPC and is very similar, but describes a standard way to communicate.
  • Several programming languages have native support for SOAP, you typically feed it a web service URL and you can call its web service functions without the need of specific code.
  • Binary data that is sent must be encoded first into a format such as base64 encoded.
  • Has several protocols and technologies relating to it: WSDL, XSDs, SOAP, WS-Addressing.

SOAP vs REST?

One of the major benefits of SOAP is that you have a WSDL service description. You can pretty much discover the service automatically and generate a useable client proxy from that service description (generate the service calls, the necessary data types for the methods and so forth). Note that with version 2.0, WSDL supports all HTTP verbs and can be used to document RESTful services as well, but there is a less verbose alternative in WADL (Web Application Description Language) for that purpose.

With RESTful services, message security is provided by the transport protocol (HTTPS), and is point-to-point only. It doesn’t have a standard messaging system and expects clients to deal with communication failures by retrying. SOAP has successful/retry logic built in and provides end-to-end reliability even through SOAP intermediaries.

One of the major benefits of RESTful API is that it is flexible for data representation, for example you could serialize your data in either XML or JSON format. RESTful APIs are cleaner or easier to understand because they add an element of using standardised URIs and gives importance to HTTP verb used (i.e. GET, POST, PUT and DELETE).

RESTful services are also lightweight, that is they don’t have a lot of extra xml markup. To invoke RESTful API all you need is a browser or HTTP stack and pretty much every device or machine connected to a network has that.

Advantages of REST

  • Since REST uses standard HTTP it is much simpler in just about ever way. Creating clients, developing APIs, the documentation is much easier to understand and there aren’t very many things that REST doesn’t do easier/better than SOAP.
  • REST permits many different data formats where as SOAP only permits XML. While this may seem like it adds complexity to REST because you need to handle multiple formats, in my experience it has actually been quite beneficial. JSON usually is a better fit for data and parses much faster. REST allows better support for browser clients due to it’s support for JSON.
  • REST has better performance and scalability. REST reads can be cached, SOAP based reads cannot be cached.
  • No expensive tools require to interact with the Web service
  • Smaller learning curve
  • Efficient (SOAP uses XML for all messages, REST can use smaller message formats)
  • Fast (no extensive processing required)
  • Closer to other Web technologies in design philosophy

Advantages of SOAP

  • WS-Security : While SOAP supports SSL (just like REST) it also supports WS-Security which adds some enterprise security features. Supports identity through intermediaries, not just point to point (SSL). It also provides a standard implementation of data integrity and data privacy. Calling it “Enterprise” isn’t to say it’s more secure, it simply supports some security tools that typical internet services have no need for, in fact they are really only needed in a few “enterprise” scenarios.
  • WS-AtomicTransaction : Need ACID Transactions over a service, you’re going to need SOAP. While REST supports transactions, it isn’t as comprehensive and isn’t ACID compliant. Fortunately ACID transactions almost never make sense over the internet. REST is limited by HTTP itself which can’t provide two-phase commit across distributed transactional resources, but SOAP can. Internet apps generally don’t need this level of transactional reliability, enterprise apps sometimes do.
  • WS-ReliableMessaging : Rest doesn’t have a standard messaging system and expects clients to deal with communication failures by retrying. SOAP has successful/retry logic built in and provides end-to-end reliability even through SOAP intermediaries.
  • Language, platform, and transport independent (REST requires use of HTTP)
  • Works well in distributed enterprise environments (REST assumes direct point-to-point communication)
  • Standardized
  • Provides significant pre-build extensibility in the form of the WS standards
  • Built-in error handling
  • Automation when used with certain language products

Where to use REST

areas where REST works really well for are:

  • Limited bandwidth and resources: remember the return structure is really in any format (developer defined). Plus, any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE verbs. Again, remember that REST can also use the XMLHttpRequest object that most modern browsers support today, which adds an extra bonus of AJAX.
  • Totally stateless operations: if an operation needs to be continued, then REST is not the best approach and SOAP may fit it better. However, if you need stateless CRUD (Create, Read, Update, and Delete) operations, then REST is it.
  • Caching situations: if the information can be cached because of the totally stateless operation of the REST approach, this is perfect.

Where to use SOAP

areas where SOAP works as a great solutionare:

  • Asynchronous processing and invocation: if your application needs a guaranteed level of reliability and security then SOAP 1.2 offers additional standards to ensure this type of operation. Things like WSRM – WS-Reliable Messaging.
  • Formal contracts: if both sides (provider and consumer) have to agree on the exchange format then SOAP 1.2 gives the rigid specifications for this type of interaction.
  • Stateful operations: if the application needs contextual information and conversational state management then SOAP 1.2 has the additional specification in the WS structure to support those things (Security, Transactions, Coordination, etc). Comparatively, the REST approach would make the developers build this custom plumbing.

What is a REST Web Service

The acronym REST stands for Representational State Transfer, this basically means that each unique URL is a representation of some object. You can get the contents of that object using an HTTP GET, to delete it, you then might use a POST, PUT, or DELETE to modify the object (in practice most of the services use a POST for this).

Who’s using REST?

All of Yahoo’s web services use REST, including Flickr, del.icio.us API uses it, pubsub, bloglines, technorati, and both eBay, and Amazon have web services for both REST and SOAP.

Who’s using SOAP?

Google seams to be consistent in implementing their web services to use SOAP, with the exception of Blogger, which uses XML-RPC. You will find SOAP web services in lots of enterprise software as well.

REST vs SOAP

As you may have noticed the companies I mentioned that are using REST api’s haven’t been around for very long, and their apis came out this year mostly. So REST is definitely the trendy way to create a web service, if creating web services could ever be trendy (lets face it you use soap to wash, and you rest when your tired).

The main advantages of REST web services are:

  • Lightweight – not a lot of extra xml markup
  • Human Readable Results
  • Easy to build – no toolkits required

SOAP also has some advantages:

  • Easy to consume – sometimes
  • Rigid – type checking, adheres to a contract
  • Development tools

For consuming web services, its sometimes a toss up between which is easier. For instance Google’s AdWords web service is really hard to consume (in CF anyways), it uses SOAP headers, and a number of other things that make it kind of difficult. On the converse, Amazon’s REST web service can sometimes be tricky to parse because it can be highly nested, and the result schema can vary quite a bit based on what you search for.

What is robots.txt and its requirement in a website.


About /robots.txt

Web site owners use the /robots.txt file to give instructions about their site to web robots; this is called The Robots Exclusion Protocol.

It works likes this: a robot wants to vists a Web site URL, say http://www.example.com/welcome.html. Before it does so, it firsts checks for http://www.example.com/robots.txt, and finds:

User-agent: *

Disallow: /

The “User-agent: *” means this section applies to all robots. The “Disallow: /” tells the robot that it should not visit any pages on the site.

There are two important considerations when using /robots.txt:

  • robots can ignore your /robots.txt. Especially malware robots that scan the web for security vulnerabilities, and email address harvesters used by spammers will pay no attention.
  • the /robots.txt file is a publicly available file. Anyone can see what sections of your server you don’t want robots to use.

So don’t try to use /robots.txt to hide information.

See also:

The details

The /robots.txt is a de-facto standard, and is not owned by any standards body. There are two historical descriptions:

In addition there are external resources:

The /robots.txt standard is not actively developed. See What about further development of /robots.txt? for more discussion.

The rest of this page gives an overview of how to use /robots.txt on your server, with some simple recipes. To learn more see also the FAQ.

How to create a /robots.txt file

Where to put it

The short answer: in the top-level directory of your web server.

The longer answer:

When a robot looks for the “/robots.txt” file for URL, it strips the path component from the URL (everything from the first single slash), and puts “/robots.txt” in its place.

For example, for “http://www.example.com/shop/index.html, it will remove the “/shop/index.html”, and replace it with “/robots.txt”, and will end up with “http://www.example.com/robots.txt&#8221;.

So, as a web site owner you need to put it in the right place on your web server for that resulting URL to work. Usually that is the same place where you put your web site’s main “index.html” welcome page. Where exactly that is, and how to put the file there, depends on your web server software.

Remember to use all lower case for the filename: “robots.txt”, not “Robots.TXT.

See also:

What to put in it

The “/robots.txt” file is a text file, with one or more records. Usually contains a single record looking like this:

User-agent: *

Disallow: /cgi-bin/

Disallow: /tmp/

Disallow: /~joe/

In this example, three directories are excluded.

Note that you need a separate “Disallow” line for every URL prefix you want to exclude — you cannot say “Disallow: /cgi-bin/ /tmp/” on a single line. Also, you may not have blank lines in a record, as they are used to delimit multiple records.

Note also that globbing and regular expression are not supported in either the User-agent or Disallow lines. The ‘*’ in the User-agent field is a special value meaning “any robot”. Specifically, you cannot have lines like “User-agent: *bot*”, “Disallow: /tmp/*” or “Disallow: *.gif”.

What you want to exclude depends on your server. Everything not explicitly disallowed is considered fair game to retrieve. Here follow some examples:

To exclude all robots from the entire server

User-agent: *

Disallow: /

 

To allow all robots complete access

User-agent: *

Disallow:

(or just create an empty “/robots.txt” file, or don’t use one at all)

To exclude all robots from part of the server

User-agent: *

Disallow: /cgi-bin/

Disallow: /tmp/

Disallow: /junk/

To exclude a single robot

User-agent: BadBot

Disallow: /

To allow a single robot

User-agent: Google

Disallow:

 

User-agent: *

Disallow: /

To exclude all files except one

This is currently a bit awkward, as there is no “Allow” field. The easy way is to put all files to be disallowed into a separate directory, say “stuff”, and leave the one file in the level above this directory:

User-agent: *

Disallow: /~joe/stuff/

Alternatively you can explicitly disallow all disallowed pages:

User-agent: *

Disallow: /~joe/junk.html

Disallow: /~joe/foo.html

Disallow: /~joe/bar.html

 

UI(User Interface) developmet Interview Questions with Answers which are mostly asked.


How to create a JQuery Plugin?

JQUERY PLUGIN

(function($) {

$.fn.helloWorld = function( options ) {

// Establish our default settings

var settings = $.extend({

text         : ‘Hello, World!’,

color        : null,

fontStyle    : null

}, options);

        return this.each( function() {
        $(this).text( settings.text );
 
    if ( settings.color ) {
        $(this).css( 'color', settings.color );
    } 

    if ( settings.fontStyle ) {
        $(this).css( 'font-style', settings.fontStyle );
    }
});

}

}(jQuery));

$('h2').helloWorld({
    text        : 'Salut, le monde!',
    color       : '#005dff',
    fontStyle   : 'italic'
}); 

What are the DOCTYPE Declaration?

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;

XHTML 1.0 Strict

This DTD contains all HTML elements and attributes, but does NOT INCLUDE presentational or deprecated elements (like font). Framesets are not allowed. The markup must also be written as well-formed XML.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”&gt;

XHTML 1.0 Transitional

This DTD contains all HTML elements and attributes, INCLUDING presentational and deprecated elements (like font). Framesets are not allowed. The markup must also be written as well-formed XML.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

XHTML 1.0 Frameset

This DTD is equal to XHTML 1.0 Transitional, but allows the use of frameset content.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Frameset//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd”&gt;

XHTML 1.1

This DTD is equal to XHTML 1.0 Strict, but allows you to add modules (for example to provide ruby support for East-Asian languages).

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN” “http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”&gt;

What is Anchor Pseudo-classes?

Links can be displayed in different ways in a CSS-supporting browser:

Example

a:link {color:#FF0000;}      /* unvisited link */
a:visited {color:#00FF00;}  /* visited link */
a:hover {color:#FF00FF;}  /* mouse over link */
a:active {color:#0000FF;}  /* selected link */

Note: a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective!!

Note: a:active MUST come after a:hover in the CSS definition in order to be effective!!

Note: Pseudo-class names are not case-sensitive.

What are the Features of HTML5 ?

  • New features  based on HTML, CSS, DOM, and JavaScript
  • Reduce the need for external plugins (like Flash)
  • Better error handling
  • More markup to replace scripting
  • HTML5 is  device independent
  • New Elements
  • New Attributes
  • Full CSS3 Support
  • Video and Audio
  • 2D/3D Graphics
  • Local Storage
  • Local SQL Database
  • Web Applications

Some of the most interesting new features in HTML5:

  • 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
  • The <canvas> element is used to draw graphics, on the fly, on a web page.
  • Draw a red rectangle, a gradient rectangle, a multicolor rectangle, and some multicolor text onto the canvas:

What is canvas?

The <canvas> element is used to draw graphics, on the fly, on a web page.

Draw a red rectangle, a gradient rectangle, a multicolor rectangle, and some multicolor text onto the canvas:

Rectangle

<canvas id=”myCanvas” width=”200″ height=”100″ style=”border:1px solid #d3d3d3;”>

Your browser does not support the HTML5 canvas tag.</canvas>

<script>

var c=document.getElementById(“myCanvas”);

var ctx=c.getContext(“2d”);

// Create gradient

var grd=ctx.createLinearGradient(0,0,200,0);

grd.addColorStop(0,”red”);

grd.addColorStop(1,”white”);

// Fill with gradient

ctx.fillStyle=grd;

ctx.fillRect(10,10,150,80);

</script>

Give an example of a Circle.

<canvas id=”myCanvas” width=”400″ height=”400″ style=”border:1px solid #d3d3d3;”>

Your browser does not support the HTML5 canvas tag.</canvas>

<script>

var c=document.getElementById(“myCanvas”);

var ctx=c.getContext(“2d”);

ctx.beginPath();

ctx.arc(95,150,80,0,2*Math.PI);

ctx.stroke();

</script>

What is CSS3 box-shadow Property?

box-shadow: h-shadow v-shadow blur spread color inset;

div

{

width:300px;

height:100px;

background-color:yellow;

box-shadow: 10px 10px 10px #888888;

}

10px 10px black

50px 50px black

50px 50px 5px black

50px 50px 10px black

50px 50px 20px black

50px 50px 50px black

50px 50px 50px 5px black

50px 50px 50px 10px black

50px 50px 50px 20px black

50px 50px 50px 20px red

50px 50px 50px 20px blue

50px 50px 50px 20px pink

40px 40px 50px 20px pink

20px 20px 50px 20px pink

10px 10px 50px 20px pink inset

10px 10px 30px 20px pink inset

10px 10px 5px 20px pink inset

10px 10px 5px 10px pink inset

10px 10px 5px 5px pink inset

CSS3 Animations

With CSS3, we can create animations, which can replace animated images, Flash animations, and JavaScripts in many web pages.

Internet Explorer 10, Firefox, and Opera supports the @keyframes rule and animation property.

Chrome and Safari requires the prefix -webkit-.

<style>

div

{

width:100px;

height:100px;

background:red;

animation:myfirst 5s;

-webkit-animation:myfirst 5s; /* Safari and Chrome */

}

@keyframes myfirst

{

from {background:red;}

to {background:yellow;}

}

@-webkit-keyframes myfirst /* Safari and Chrome */

{

from {background:red;}

to {background:yellow;}

}

</style>

bind() Definition and Usage

The bind() method attaches one or more event handlers for selected elements, and specifies a function to run when the event occurs.

$(“p”).bind(“click”,function(){
alert(“The paragraph was clicked.”);
});

The live()

The live() method attaches one or more event handlers for selected elements, and specifies a function to run when the events occur.

Event handlers attached using the live() method will work for both current and FUTURE elements matching the selector (like a new element created by a script).

Tip: To remove event handlers, use the die() method.

bind() attacheds events to elements that exist or match the selector at the time the call is made. Any elements created afterwards or that match going forward because the class was changed, will not fire the bound event.

.live() works for existing and future matching elements. Before jQuery 1.4 this was limited to the following events: click, dblclick mousedown, mouseup, mousemove, mouseover, mouseout, keydown, keypress, keyup.

The element Selector

The jQuery element selector selects elements based on the element name.

You can select all <p> elements on a page like this:

The #id Selector

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.

An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

To find an element with a specific id, write a hash character, followed by the id of the element:

$(“#test”)

The .class Selector

The jQuery class selector finds elements with a specific class.

To find elements with a specific class, write a period character, followed by the name of the class:

$(“.test”)

jQuery – Chaining


With jQuery, you can chain together actions/methods.

Chaining allows us to run multiple jQuery methods (on the same element) within a single statement.

$(“#p1”).css(“color”,”red”).slideUp(2000).slideDown(2000);

this

In JavaScript, as in most object-oriented programming languages, this is a special keyword that is used in methods to refer to the object on which a method is being invoked.

What is clone() method?

The clone() method makes a copy of selected elements, including child nodes, text and attributes.

$(“button”).click(function(){
$(“p”).clone().appendTo(“body”);
});

$(“*”) Selects all elements
$(this) Selects the current HTML element
$(“p.intro”) Selects all <p> elements with
$(“p:first”) Selects the first <p> element
$(“ul li:first”) Selects the first <li> element of the first <ul>
$(“ul li:first-child”) Selects the first <li> element of every <ul>
$(“[href]”) Selects all elements wh an href attribute
$(“a[target=’_blank’]”) Selects all <a> elements with a target attribute value equal to “_blank”
$(“a[target!=’_blank’]”) Selects all <a> elements with a target attribute value NOT equal to “_blank”
$(“:button”) Selects all <button> elements and <input> elements of type=”button”
$(“tr:even”) Selects all even <tr> elements
$(“tr:odd”)What is $(document).ready()?The $(document).ready() method allows us to execute a function when the document is fully loaded.

What is the bind() method?

The bind() method attaches one or more event handlers for selected elements, and specifies a function to run when the event occurs.

$(“p”).bind(“click”,function(){
alert(“The paragraph was clicked.”);
});

The noConflict() Method


What if you wish to use other frameworks on your pages, while still using jQuery?


 

What if other JavaScript frameworks also use the $ sign as a shortcut?

Some other popular JavaScript frameworks are: MooTools, Backbone, Sammy, Cappuccino, Knockout, JavaScript MVC, Google Web Toolkit, Google Closure, Ember, Batman, and Ext JS.

Some of the other frameworks also use the $ character as a shortcut (just like jQuery), and then you suddenly have two different frameworks using the same shortcut, which might result in that your scripts stop working.

The jQuery team have already thought about this, and implemented the noConflict() method.


The jQuery noConflict() Method

The noConflict() method releases the hold on the $ shortcut identifier, so that other scripts can use it.

You can of course still use jQuery, simply by writing the full name instead of the shortcut:

Example

$.noConflict();
jQuery(document).ready(function(){
jQuery(“button”).click(function(){
jQuery(“p”).text(“jQuery is still working!”);
});
});

You can also create your own shortcut very easily. The noConflict() method returns a reference to jQuery, that you can save in a  variable, for later use. Here is an example:

Example

var jq = $.noConflict();
jq(document).ready(function(){
jq(“button”).click(function(){
jq(“p”).text(“jQuery is still working!”);
});
});

If you have a block of jQuery code which uses the $ shortcut and you do not want to change it all, you can pass the $ sign in as a parameter to the ready method. This allows you to access jQuery using $, inside this function – outside of it, you will have to use “jQuery”:

Example

$.noConflict();
jQuery(document).ready(function($){
$(“button”).click(function(){
$(“p”).text(“jQuery is still working!”);
});
});

The localStorage Object

The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.

Example

localStorage.lastname=”Smith”;
document.getElementById(“result”).innerHTML=”Last name: ”
+ localStorage.lastname;

The following example counts the number of times a user has clicked a button. In this code the value string is converted to a number to be able to increase the counter:

clickcount

Example

if (localStorage.clickcount)
{
localStorage.clickcount=Number(localStorage.clickcount)+1;
}
else
{
localStorage.clickcount=1;
}
document.getElementById(“result”).innerHTML=”You have clicked the button ” + localStorage.clickcount + ” time(s).”;

What is The sessionStorage Object

The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the browser window.

The following example counts the number of times a user has clicked a button, in the current session:

Example

if (sessionStorage.clickcount)
{
sessionStorage.clickcount=Number(sessionStorage.clickcount)+1;
}
else
{
sessionStorage.clickcount=1;
}
document.getElementById(“result”).innerHTML=”You have clicked the button ” + sessionStorage.clickcount + ” time(s) in this session.”;

What is Media queries?

Media queries consist of a media type and can, as of the CSS3 specification, contain one or more expressions, expressed as media features, which resolve to either true or false.  The result of the query is true if the media type specified in the media query matches the type of device the document is being displayed on and all expressions in the media query are true.

<!-- CSS media query on a link element -->
<link rel="stylesheet" media="(max-width: 800px)" href="example.css" />
 
<!-- CSS media query within a style sheet -->
<style>
@media (max-width: 600px) {
  .facet_sidebar {
    display: none;
  }
}
</style>

@media (min-width: 700px) { ... }
@media (min-width: 700px) and (orientation: landscape) { ... }

What is CSS3 Box Shadow?

box-shadow: left  top  opacity  color;

In CSS3, the box-shadow property is used to add shadow to boxes:

<style>

0px;

height:100px;

background-codiv

{

width:30lor:yellow;

box-shadow: 10px 10px 5px #888888;

}

</style>

Define detach(), remove(), empty().

The detach() method removes the selected elements, including all text and child nodes. However, it keeps data and events.

This method also keeps a copy of the removed elements, which allows them to be reinserted at a later time.

Tip: To remove the elements and its data and events, use the remove() method instead.

Tip: To remove only the content from the selected elements, use the empty() method.

What is bootstrap?

Bootstrap is an open-source Javascript framework developed by the team at Twitter. It is a combination of HTML, CSS, and Javascript code designed to help build user interface components. Bootstrap was also programmed to support both HTML5 and CSS3.

Important! Bootstrap is a CSS and Javascript framework that is used within your HTML. Bootstrap provides more advanced functionality to your web site. Generally, if you are not a developer you do not need to worry about bootstrap.

Best explained: http://en.wikipedia.org/wiki/Bootstrap_%28front-end_framework%29

What is included with Bootstrap?

If you were to download bootstrap, you would find that it includes css files, javascript files, and images. Here’s a sneak peak at the files included:

 

Css

bootstrap.css

bootstrap.min.css

bootstrap-responsive.css

bootstrap-responsive.min.css

img  

glyphicons-halflings.png

glyphicons-halflings-white.png

js

bootstrap.js

bootstrap.min.js

What is Media Queries and how to use it?

By using the @media rule, a website can have a different layout for screen, print, mobile phone, tablet, etc.

Media Types

Some CSS properties are only designed for a certain media. For example the “voice-family” property is designed for aural user agents. Some other properties can be used for different media types. For example, the “font-size” property can be used for both screen and print media, but perhaps with different values. A document usually needs a larger font-size on a screen than on paper, and sans-serif fonts are easier to read on the screen, while serif fonts are easier to read on paper.

The @media Rule

The @media rule allows different style rules for different media in the same style sheet.

The style in the example below tells the browser to display a 14 pixels Verdana font on the screen. But if the page is printed, it will be in a 10 pixels Times font. Notice that the font-weight is set to bold, both on screen and on paper:

A media query consists of a media type and at least one expression that limits the style sheets’ scope by using media features, such as width, height, and color. Media queries, added in CSS3, let the presentation of content be tailored to a specific range of output devices without having to change the content itself.

Syntax

Media queries consist of a media type and can, as of the CSS3 specification, contain one or more expressions, expressed as media features, which resolve to either true or false.  The result of the query is true if the media type specified in the media query matches the type of device the document is being displayed on and all expressions in the media query are true.

<!-- CSS media query on a link element -->
<link rel="stylesheet" media="(max-width: 800px)" href="example.css" />
 
<!-- CSS media query within a style sheet -->
<style>
@media (max-width: 600px) {
  .facet_sidebar {
    display: none;
  }
}
</style>

 

Selects all odd <tr> elements

Interview Questions and Answers on PayPal, Authorize.Net (Online Payment Gateways)


Q. What is recurring payment in payment gateway process?

Overview

PayPal Recurring Payments allows you to bill a buyer for a fixed amount of money on a fixed schedule. Consider the following examples:

  • A buyer purchases a subscription to a magazine or newsletter from your site and agrees to pay a monthly fee.
  • A buyer agrees to pay an Internet Service Provider a flat fee on a semi-annual basis to host a website.

These examples represent payment transactions that reoccur periodically and are for a fixed amount.

The buyer signs up for recurring payments during checkout from your site using the Recurring Payments API or you can set up recurring payments from your PayPal account.

How Recurring Payments Work

When you create recurring payments for a buyer, you create a recurring payments profile. The profile contains information about the recurring payments, including details for an optional trial period and a regular payment period. Each of these subscription periods contains information about the payment frequency and payment amounts, including shipping and tax, if applicable.

After a profile is created, PayPal automatically queues payments based on the billing start date, billing frequency, and billing amount, until the profile expires or is canceled by the merchant.

Limitations
The current release of the Recurring Payments API has the following limitations:

  • A profile can have at most one optional trial period and a single regular payment period.
  • The profile start date may not be earlier than the profile creation date.

Recurring Payments Terms

Term Definition
Recurring payments profile Your record of a recurring transaction for a single customer. The profile includes all information required to automatically bill the buyer a fixed amount of money at a fixed interval.
Billing cycle One payment is made per billing cycle. Each billing cycle is made up of two components. The billing period specifies the unit to be used to calculate the billing cycle (such as days or months).
The billing frequency specifies the number of billing periods that make up the billing cycle.
For example, if the billing period is Month and the billing frequency is 2, the billing cycle will be two months. If the billing period is Week and the billing frequency is 6, the payments will be scheduled every 6 weeks.
Regular payment period The main subscription period for this profile, which defines a payment amount for each billing cycle. The regular payment period begins after the trial period, if a trial period is specified for the profile.
Trial period An optional subscription period before the regular payment period begins. A trial period may not have the same billing cycles and payment amounts as the regular payment period.
Payment amount The amount to be paid by the buyer for each billing cycle.
Outstanding balance If a payment fails for any reason, that amount is added to the profile’s outstanding balance.
Profile ID An alphanumeric string (generated by PayPal) that uniquely identifies a recurring profile.

Administering Recurring Payments From Your PayPal Account

You can create, modify, suspend, reactivate, or cancel recurring payment profiles from your PayPal account. You can also list all recurring payment profiles. To access the PayPal Recurring Payments tools, click Recurring Payments from the Tools section of your account overview.

You can also access recurring payments reports from the PayPal Business Overview page.

What is Website Payments Standard?

Website Payments Standard enables you to accept online payments from customers with — or without — PayPal accounts.

  • Accept all major credit/debit cards (Visa, MasterCard, American Express, and Discover), eChecks, bank transfers, and PayPal accounts.
  • Easily create payment buttons (like Buy Now and Add to Cart) for your websites with PayPal tools. You design the button features, and the tools generate all the HTML code for you.

What do my buyers see when they check out?

Your customers go through a 4-step process to pay for a purchase:

  1. They click the payment buttons next to the selected items.
  2. If they have a PayPal account, they log into PayPal. If they don’t have a PayPal account, they enter all their payment information on a web page protected by PayPal.
  3. They review and complete the purchase on PayPal.
  4. They return to your website.

For an illustration, refer to the section “The payment experience” on the Website Payments Standard overview page.

Do my buyers need a PayPal account to pay me?

No. They can pay with their credit/debit card (Visa, MasterCard, American Express, and Discover) — all without having a PayPal account.

How can I accept payments online using Website Payments Standard?

You have 3 options.

  1. Create buttons for your website. You don’t even need a PayPal account to get started!
  2. Use a third-party cart compatible with Website Payments Standard.
  3. Customize your integration with the help of a web developer.

Can I track my inventory?

Yes. If you’re selling something on your website, you can create a button that keeps track of what you’ve sold. PayPal will also notify you by e-mail when your inventory gets low, so you don’t sell items that are out of stock.

Does Website Payments Standard include a shopping cart?

Yes. PayPal provides a free, simple shopping cart. All you do is create the “Add to Cart” and “View Cart” buttons with easy-to-use tools.

You can also choose any of the hundreds of shopping carts pre-integrated with Website Payments Standard.

Does Website Payments Standard support multiple currencies?

Yes. You can buy, sell, send, or receive payments globally in currencies supported by PayPal.

Does Website Payments Standard calculate shipping and taxes?

Yes. Website Payments Standard offers shipping and tax calculators for both domestic and international sales in countries where PayPal is available.

All tax and shipping calculators are locationd in your PayPal account profile.

What kind of reporting does Website Payments Standard have?

Website Payments Standard offers a variety of reporting tools:

  • Profit and loss tracking
  • History log
  • Downloadable logs
  • Settlement and reconciliation system
  • Monthly account statements

Can I send invoices?

Invoicing tools are available within the Email Payments tool.

Can I customize my PayPal checkout pages with my company’s look and feel?

Yes. You can easily use your site’s logo and color scheme at the top of your checkout pages on PayPal. Your customers will feel as if they are staying on your website for the entire purchase. Tools for customizing your checkout pages are in your PayPal profile.

How long does it take for funds to show up in my PayPal account?

Just a few minutes — when customers pay with credit or debit cards or a balance in their PayPal accounts. Payments made with eChecks take longer, because they have to clear the bank.

What is the difference between Website Payments Standard and Website Payments Pro?

Website Payments Standard

  • Your customers shop on your website and pay on a secure PayPal page.
  • Minimal technical skills required to integrate it with your website.
  • Begin creating payment buttons immediately — with or without a PayPal account.
  • Low-cost solution: no monthly, start-up, or cancellation fees – and no annual commitment.

Website Payments Pro

  • Your customers shop and pay on your website.
  • Programming skills required to integrate it with your website.
  • Pro application and approval (2-3 days) required after you create a PayPal Business account.
  • Monthly fee applies.

Can I take orders by phone, fax, or mail?

Yes. You can use Virtual Terminal to process phone, fax, or mail orders. Use Virtual Terminal together with Website Payments Standard to reach more customers.

Does Website Payments Standard let me accept recurring payments?

Yes. Website Payments Standard supports recurring payments for subscriptions and donations.

Can I create payment buttons using an API?

Yes. We provide a set of APIs for developers and partners. You can find details in the Website Payments Standard Integration Guide.

What is Express Checkout?

If we use PayPal Express Checkout, when our customers check out, they will be directed to a page that requires them to log into their PayPal account or create a new one. Therefore, this is the best option if you anticipate that most of your customers either have a PayPal account or will sign up for an account on checkout.

Express Checkout allows your customers to complete transactions in very few steps. It lets them use postage and billing information stored securely at PayPal to check out, so they don’t have to re-enter it on your site.

How it works.

  1. After selecting products to purchase your customer clicks on Check out with PayPal on your website.
  2. They’re transferred to PayPal – where they select their payment method, as well as the correct postage and billing address – then are returned to your website to complete their purchases.
  3. PayPal automatically gives you the postal address, email address and other customer information needed to fulfil your order.

With Express Checkout, your buyers finish their orders on your website, not PayPal’s, so you can:

  • Get real-time notification of successful payments
  • Automate your internal business processes.
  • Ensure buyers make it to your final confirmation page
  • Be notified that the buyer’s address is confirmed, and ensure you’re eligible for coverage under PayPal’s Seller Protection Policy

What is PayPal Website Payments Standard?

If you use PayPal Website Payments Standard, when your customers check out, they will be directed to a page that allows them to log into their PayPal account or pay by credit card without having to sign up for a PayPal account. This is the best option if you anticipate that most of your customers will not want to sign up for a PayPal account.

PayPal Website Payments Standard allows users the choice of signing in or not signing in, and can be considered the default choice

What is  PayPal Sandbox?

The PayPal Sandbox is a self-contained environment within which you can prototype and test PayPal features and APIs. The PayPal Sandbox is an almost identical copy of the live PayPal website. Its purpose is to give developers a shielded environment for testing and integration purposes and to help avoid problems that might occur while testing PayPal integration solutions on the live site. Before moving any PayPal-based application into production, you should test the application in the Sandbox to ensure that it functions as you intend and within the guidelines and standards set forth by the PayPal Developer Network (PDN).

Q. What are the parameters for the PayPal payment process?

<form name=”frmOS” action=”<?=PAYPAL_URL?>” method=”post”>
<div style=”height:200px;”>
<h1><?=PAGE_TITLE?></h1>
<input type=”hidden” name=”cmd” value=”_xclick”>
<input type=”hidden” name=”business” value=”<?=PAYPAL_BIZ_EMAIL?>” />
<input type=”hidden” name=”item_name” value=”Order on Website Name” />
<input type=”hidden” name=”amount” value=”<?=$value?>” />
<input type=”hidden” name=”notify_url” value=”<?=PAYPAL_NOTIFY_URL?>” />
<input type=”hidden” name=”return” value=”<?=PAYPAL_RETURN_URL?>” />
<input type=”hidden” name=”cancel_return” value=”<?=PAYPAL_CANCEL_URL?>” />
<input type=”hidden” name=”image_url” value=”<?=PAYPAL_LOGO_URL?>” />
<input type=”hidden” name=”currency_code” value=”USD” />
<input type=”hidden” name=”lc” value=”<?=$value?>” />
<input type=”hidden” name=”rm” value=”1″ />
<input type=”hidden” name=”custom” value=”<?=$value?>” />
<input type=”hidden” name=”first_name” value=”<?=$value?>” />
<input type=”hidden” name=”last_name” value=”<?=$value?>” />
<input type=”hidden” name=”city” value=”<?=$value?>” />
<input type=”hidden” name=”state” value=”<?=$value?>” />
<input type=”hidden” name=”zip” value=”<?=$value?>” />
<input type=”hidden” name=”country” value=”<?=$value?>” />
<input type=”hidden” name=”phone” value=”<?=$value?>” />
<input type=”hidden” name=”email” value=”<?=$value?>” />
<input type=”hidden” name=”address1″ value=”<?=$value?>” />
<p align=”center” style=”margin-top:35px;”><input type=”submit” name=”submitPaypal” value=”Proceed to Payment &raquo;” style=”cursor:pointer” /></p>
</div>

Q.What is Return URL Requirements in PayPal?

The following items are required to set up Auto Return.

In accordance with the User Agreement, you must provide written information on the page displayed by the Return URL that will help the buyer understand that the payment has been made and that the transaction has been completed.

You must provide written information on the page displayed by the Return URL that explains that payment transaction details will be emailed to the buyer.

Example: Thank you for your payment. Your transaction has been completed, and a receipt for your purchase has been emailed to you. You may log in to your account at http://www.paypal.com to view details of this transaction.

Q. What is notify URL in PayPal?

PayPal returns data back to our site via what they call IPN. Its really just a callback to a URL you specify. You can set this URL via the variable notify_url you can send to PayPal. By using those post data we can do the transaction through the curl, update the database also send the email.

Example:

<input name="notify_url" value="http://yourdomain.com/notify_url.php" type="hidden">

The notify_url.php in the example above receives some POST variables from PayPal when the payment is completed, even if the customer never returns to your website.

Q.What is PAYPAL CANCEL URL(cancel_return)?

An internet URL where the user will be returned if payment is cancelled. For example, a URL on your site which hosts a “Payment Cancelled” page. If if omitted, users will be taken to the PayPal site.

How many types of payment Mode in Authorize.net?

Server Integration Method (SIM)

SIM provides a customizable, secure hosted payment form to make integration easy for Web merchants that do not have an SSL certificate.

See how it works

SIM uses scripting techniques to authenticate transactions with a unique transaction fingerprint.

The Authorize.Net Payment Gateway can handle all the steps in the secure transaction process – payment data collection, data submission and the response to the customer – while keeping Authorize.Net virtually transparent.

  • Payment gateway hosted payment form employs 128-bit SSL data encryption.
  • Digital fingerprints enhance security, providing multiple layers of authentication.
  • Customize the look and feel of the payment gateway hosted payment form and/or receipt page.

<form name=”authnetSubmit” method=’post’ action=”<?=AUTH_NET_URL?>”>

<input type=’hidden’ name=”x_login” value=”<?php echo $api_login_id?>” />

<input type=’hidden’ name=”x_fp_hash” value=”<?php echo $fingerprint?>” />

<input type=’hidden’ name=”x_amount” value=”<?php echo $amount?>” />

<input type=’hidden’ name=”x_fp_timestamp” value=”<?php echo $fp_timestamp?>” />

<input type=’hidden’ name=”x_fp_sequence” value=”<?php echo $fp_sequence?>” />

<input type=’hidden’ name=”x_first_name” value=”<?php echo $first_name?>” />

<input type=’hidden’ name=”x_last_name” value=”<?php echo $last_name?>” />

<input type=’hidden’ name=”x_company” value=”” />

<input type=’hidden’ name=”x_address” value=”<?php echo $home_address?>” />

<input type=’hidden’ name=”x_city” value=”<?php echo $city?>” />

<input type=’hidden’ name=”x_state” value=”<?php echo $state?>” />

<input type=’hidden’ name=”x_zip” value=”<?php echo $zip?>” />

<input type=’hidden’ name=”x_country” value=”<?php echo $country?>” />

<input type=’hidden’ name=”x_email” value=”<?php echo $email_address?>” />

<input type=’hidden’ name=”x_version” value=”3.1″ />

<input type=’hidden’ name=”x_show_form” value=”payment_form” />

<input type=’hidden’ name=”x_test_request” value=”<?=TEST_MODE?>” />

<input type=’hidden’ name=”x_method” value=”cc” />

<input type=”hidden” name=”x_cust_id” value=”<?=$attendee_id?>” />

<input type=”hidden” name=”x_invoice_num” value=”<?=$order_id?>” />

<input type=”hidden” name=”x_description” value=”Course Tuition” />

<input type=”hidden” name=”x_relay_response” value=”TRUE”>

<input type=”hidden” name=”x_relay_url” value=”<?=RECEIPT_LINK_URL?>”>

</form>

Simple Checkout

Simple Checkout helps you create “Buy Now” and “Donate” buttons for your Web site, even if you have minimal technical expertise.

See how it works

Simple Checkout is a perfect solution for organizations that rely on donations and specialty merchants that typically sell one item (in any quantity) per order.

Choosere-designed Buy Now and Donae buttons or customize your own buttons to include text of your choosing.

How Simple Checkout Works

To generate the buttons, you simply enter applicable information such as an item description and price into the Authorize.Net Merchant Interface. HTML code is then generated automatically, which you can copy and paste into your Web site. When customers click your Simple Checkout button, they are taken to our secure, hosted payment form to enter their payment information, along with any other required information.

Because sensitive card data is collected using our secure servers, Simple Checkout can help simplify your compliance with the Payment Card Industry (PCI) Data Security Standard.

Configuring Your Buy Now or Donate Buttons

Simple Checkout allows you to customize several settings for each item:

  • Item ID and Description Each item can be assigned a unique item ID and description, which is displayed on your Web site’s order page, as well as the payment form and receipt page.
  • Suggested Donation Amounts Nonprofit organizations can specify suggested donation amounts.
  • Shipping Methods If shipping is required, you can configure up to 10 shipping methods (e.g. Ground, Overnight, Two Day, etc.), with ranges and costs (e.g. 1-5 items = $4.95, 6-10 items = $6.95, etc.) for each method.
  • Maximum Per Order You can specify the maximum quantity of each item, per order, that a customer may purchase.
  • Verified Merchant Seal Display our Authorize.Net Verified Merchant Seal on your site to increase customer confidence and potentially increase sales.

Direct Post Method(DPM)

Direct Post Method allows developers to fully customize the experience of the entire payment flow, while simplifying PCI compliance.

See how it works

The Authorize.Net Payment Gateway handles all the steps in the secure transaction while remaining virtually transparent.

  • Customer data is protected with 128-bit SSL encryption.
  • Digital fingerprints enhance security, providing multiple layers of authentication.

Advanced Integration Method (AIM)

AIM is Authorize.Net’s recommended connection method and offers the most secure and flexible integration for all types of transactions, including mobile, websites and other business applications.

See how it works

AIM allows merchants to host their own secure payment form on a website, mobile device, etc., and send transactions to the payment gateway using an end-to-end secure sockets layer (SSL) connection.

AIM is also the required connection method for shopping cart developers participating in the Authorize.Net Shopping Cart Certification (SCC) program.

  • Employs industry standard secure data encryption technology — 128-bit Secure Sockets Layer (SSL) protocol.
  • Uses transaction key authentication for ultimate security.
  • Allows control over all phases of the customer’s online transaction experience.
  • Configurable transaction response integrates easily with merchant applications.
  • Provides mobile SDKs for Apple iOS and Android.

Automated Recurring Billing (ARB) API

For merchants enabled for the Automated Recurring Billing (ARB) service, the additional ARB API feature supports integration with a Web site payment form or a proprietary business application-allowing online customers or sales representatives using a business application to select and submit subscription- or installment-based payments.

  • Expand payment options for online and mail order/telephone order (MOTO) customers, potentially increasing sales.
  • Create, update, and cancel subscriptions programmatically.
  • Utilize Authorize.Net’s secure data center to store payment information safely for recurring transactions.

Customer Information Manager (CIM) API

The Authorize.Net Customer Information Manager (CIM) allows merchants to create customer profiles that are stored on Authorize.Net’s secure servers. By providing quick access to stored customer information, CIM is ideal for businesses that:

  • Process recurring transactions where the date and/or amount is different each month (e.g. utility companies).
  • Process usage charges – where you only bill when the service is used. (e.g. pay-as-you-go cell phones).
  • Are concerned with PCI compliance.
  • Want to provide returning customers with the convenience of not having to re-enter personal data.

The CIM API supports integration with a Web site payment form or a proprietary business application. The profiles, which include payment and shipping information, can then be referenced in future transactions, eliminating steps in the transaction process for repeat customers and potentially increasing customer loyalty.

What is  PayPal Sandbox?

The PayPal Sandbox is a self-contained environment within which you can prototype and test PayPal features and APIs. The PayPal Sandbox is an almost identical copy of the live PayPal website. Its purpose is to give developers a shielded environment for testing and integration purposes and to help avoid problems that might occur while testing PayPal integration solutions on the live site. Before moving any PayPal-based application into production, you should test the application in the Sandbox to ensure that it functions as you intend and within the guidelines and standards set forth by the PayPal Developer Network (PDN).

Q. What are the parameters for the PayPal payment process?

<form name=”frmOS” action=”<?=PAYPAL_URL?>” method=”post”>
<div style=”height:200px;”>
<h1><?=PAGE_TITLE?></h1>
<input type=”hidden” name=”cmd” value=”_xclick”>
<input type=”hidden” name=”business” value=”<?=PAYPAL_BIZ_EMAIL?>” />
<input type=”hidden” name=”item_name” value=”Order on OttoSkin” />
<input type=”hidden” name=”amount” value=”<?=$value?>” />
<input type=”hidden” name=”notify_url” value=”<?=PAYPAL_NOTIFY_URL?>” />
<input type=”hidden” name=”return” value=”<?=PAYPAL_RETURN_URL?>” />
<input type=”hidden” name=”cancel_return” value=”<?=PAYPAL_CANCEL_URL?>” />
<input type=”hidden” name=”image_url” value=”<?=PAYPAL_LOGO_URL?>” />
<input type=”hidden” name=”currency_code” value=”USD” />
<input type=”hidden” name=”lc” value=”<?=$value?>” />
<input type=”hidden” name=”rm” value=”1″ />
<input type=”hidden” name=”custom” value=”<?=$value?>” />
<input type=”hidden” name=”first_name” value=”<?=$value?>” />
<input type=”hidden” name=”last_name” value=”<?=$value?>” />
<input type=”hidden” name=”city” value=”<?=$value?>” />
<input type=”hidden” name=”state” value=”<?=$value?>” />
<input type=”hidden” name=”zip” value=”<?=$value?>” />
<input type=”hidden” name=”country” value=”<?=$value?>” />
<input type=”hidden” name=”phone” value=”<?=$value?>” />
<input type=”hidden” name=”email” value=”<?=$value?>” />
<input type=”hidden” name=”address1″ value=”<?=$value?>” />
<p align=”center” style=”margin-top:35px;”><input type=”submit” name=”submitPaypal” value=”Proceed to Payment &raquo;” style=”cursor:pointer” /></p>
</div>

Q.What is Return URL Requirements in PayPal?

The following items are required to set up Auto Return.

In accordance with the User Agreement, you must provide written information on the page displayed by the Return URL that will help the buyer understand that the payment has been made and that the transaction has been completed.

You must provide written information on the page displayed by the Return URL that explains that payment transaction details will be emailed to the buyer.

Example: Thank you for your payment. Your transaction has been completed, and a receipt for your purchase has been emailed to you. You may log in to your account at http://www.paypal.com to view details of this transaction.

Q. What is notify URL in PayPal?

PayPal returns data back to our site via what they call IPN. Its really just a callback to a URL you specify. You can set this URL via the variable notify_url you can send to PayPal. By using those post data we can do the transaction through the curl, update the database also send the email.

Example:

<input name="notify_url" value="http://yourdomain.com/notify_url.php" type="hidden">

The notify_url.php in the example above receives some POST variables from PayPal when the payment is completed, even if the customer never returns to your website.

What is IPN in PayPal?

Instant Payment Notification (IPN) is PayPal’s message service that sends a notification when a transaction is affected. Once IPN is integrated,
sellers can automate their back office so they don’t have to wait for payments to come in to trigger order fulfillment.
IPN can send notifications for these transactions:

Instant payments, including Express Checkout and direct credit card payments
eCheck payments and pending, completed, or denied status payments
Pending payments
Recurring payments and subscriptions
Authorizations
Disputes, chargebacks, reversals, and refunds

You can also view notifications on PayPal’s IPN History page and resend them if you need to.
As PayPal’s interface for handling purchase confirmation and server-to-server communications, IPN can also be used to manage and customize a variety of
APIs and communications, including:

Customize your website’s response to customer purchases in seconds
Track customers via IPN “pass-through” variables
Notify sellers who deal mostly in software downloads and other digital, online goods
Track affiliate sales and commissions
Store transaction information in your own databaseInstant Payment Notification (IPN) is PayPal’s message service that sends a notification when a transaction is affected. Once IPN is integrated,
sellers can automate their back office so they don’t have to wait for payments to come in to trigger order fulfillment.
IPN can send notifications for these transactions:

Instant payments, including Express Checkout and direct credit card payments
eCheck payments and pending, completed, or denied status payments
Pending payments
Recurring payments and subscriptions
Authorizations
Disputes, chargebacks, reversals, and refunds

You can also view notifications on PayPal’s IPN History page and resend them if you need to.
As PayPal’s interface for handling purchase confirmation and server-to-server communications, IPN can also be used to manage and customize a variety of
APIs and communications, including:

Customize your website’s response to customer purchases in seconds
Track customers via IPN “pass-through” variables
Notify sellers who deal mostly in software downloads and other digital, online goods
Track affiliate sales and commissions
Store transaction information in your own database

Instant Payment Notification (IPN) is PayPal’s message service that sends a notification when a transaction is affected. Once IPN is integrated,
sellers can automate their back office so they don’t have to wait for payments to come in to trigger order fulfillment.
IPN can send notifications for these transactions:

Instant payments, including Express Checkout and direct credit card payments
eCheck payments and pending, completed, or denied status payments
Pending payments
Recurring payments and subscriptions
Authorizations
Disputes, chargebacks, reversals, and refunds

You can also view notifications on PayPal’s IPN History page and resend them if you need to.
As PayPal’s interface for handling purchase confirmation and server-to-server communications, IPN can also be used to manage and customize a variety of
APIs and communications, including:

Customize your website’s response to customer purchases in seconds
Track customers via IPN “pass-through” variables
Notify sellers who deal mostly in software downloads and other digital, online goods
Track affiliate sales and commissions
Store transaction information in your own database

Q.What is PAYPAL CANCEL URL(cancel_return)?

An internet URL where the user will be returned if payment is cancelled. For example, a URL on your site which hosts a “Payment Cancelled” page. If if omitted, users will be taken to the PayPal site.

How many types of payment Mode in Authorize.net?

Server Integration Method (SIM)

SIM provides a customizable, secure hosted payment form to make integration easy for Web merchants that do not have an SSL certificate.

See how it works

SIM uses scripting techniques to authenticate transactions with a unique transaction fingerprint.

The Authorize.Net Payment Gateway can handle all the steps in the secure transaction process – payment data collection, data submission and the response to the customer – while keeping Authorize.Net virtually transparent.

  • Payment gateway hosted payment form employs 128-bit SSL data encryption.
  • Digital fingerprints enhance security, providing multiple layers of authentication.
  • Customize the look and feel of the payment gateway hosted payment form and/or receipt page.

<form name=”authnetSubmit” method=’post’ action=”<?=AUTH_NET_URL?>”>

<input type=’hidden’ name=”x_login” value=”<?php echo $api_login_id?>” />

<input type=’hidden’ name=”x_fp_hash” value=”<?php echo $fingerprint?>” />

<input type=’hidden’ name=”x_amount” value=”<?php echo $amount?>” />

<input type=’hidden’ name=”x_fp_timestamp” value=”<?php echo $fp_timestamp?>” />

<input type=’hidden’ name=”x_fp_sequence” value=”<?php echo $fp_sequence?>” />

<input type=’hidden’ name=”x_first_name” value=”<?php echo $first_name?>” />

<input type=’hidden’ name=”x_last_name” value=”<?php echo $last_name?>” />

<input type=’hidden’ name=”x_company” value=”” />

<input type=’hidden’ name=”x_address” value=”<?php echo $home_address?>” />

<input type=’hidden’ name=”x_city” value=”<?php echo $city?>” />

<input type=’hidden’ name=”x_state” value=”<?php echo $state?>” />

<input type=’hidden’ name=”x_zip” value=”<?php echo $zip?>” />

<input type=’hidden’ name=”x_country” value=”<?php echo $country?>” />

<input type=’hidden’ name=”x_email” value=”<?php echo $email_address?>” />

<input type=’hidden’ name=”x_version” value=”3.1″ />

<input type=’hidden’ name=”x_show_form” value=”payment_form” />

<input type=’hidden’ name=”x_test_request” value=”<?=TEST_MODE?>” />

<input type=’hidden’ name=”x_method” value=”cc” />

<input type=”hidden” name=”x_cust_id” value=”<?=$attendee_id?>” />

<input type=”hidden” name=”x_invoice_num” value=”<?=$order_id?>” />

<input type=”hidden” name=”x_description” value=”Course Tuition” />

<input type=”hidden” name=”x_relay_response” value=”TRUE”>

<input type=”hidden” name=”x_relay_url” value=”<?=RECEIPT_LINK_URL?>”>

</form>

Simple Checkout

Simple Checkout helps you create “Buy Now” and “Donate” buttons for your Web site, even if you have minimal technical expertise.

See how it works

Simple Checkout is a perfect solution for organizations that rely on donations and specialty merchants that typically sell one item (in any quantity) per order.

Choose from pre-designed Buy Now and Donate buttons or customize your own buttons to include text of your choosing.

How Simple Checkout Works

To generate the buttons, you simply enter applicable information such as an item description and price into the Authorize.Net Merchant Interface. HTML code is then generated automatically, which you can copy and paste into your Web site. When customers click your Simple Checkout button, they are taken to our secure, hosted payment form to enter their payment information, along with any other required information.

Because sensitive card data is collected using our secure servers, Simple Checkout can help simplify your compliance with the Payment Card Industry (PCI) Data Security Standard.

Configuring Your Buy Now or Donate Buttons

Simple Checkout allows you to customize several settings for each item:

  • Item ID and Description Each item can be assigned a unique item ID and description, which is displayed on your Web site’s order page, as well as the payment form and receipt page.
  • Suggested Donation Amounts Nonprofit organizations can specify suggested donation amounts.
  • Shipping Methods If shipping is required, you can configure up to 10 shipping methods (e.g. Ground, Overnight, Two Day, etc.), with ranges and costs (e.g. 1-5 items = $4.95, 6-10 items = $6.95, etc.) for each method.
  • Maximum Per Order You can specify the maximum quantity of each item, per order, that a customer may purchase.
  • Verified Merchant Seal Display our Authorize.Net Verified Merchant Seal on your site to increase customer confidence and potentially increase sales.

Direct Post Method(DPM)

Direct Post Method allows developers to fully customize the experience of the entire payment flow, while simplifying PCI compliance.

See how it works

The Authorize.Net Payment Gateway handles all the steps in the secure transaction while remaining virtually transparent.

  • Customer data is protected with 128-bit SSL encryption.
  • Digital fingerprints enhance security, providing multiple layers of authentication.

Advanced Integration Method (AIM)

AIM is Authorize.Net’s recommended connection method and offers the most secure and flexible integration for all types of transactions, including mobile, websites and other business applications.

See how it works

AIM allows merchants to host their own secure payment form on a website, mobile device, etc., and send transactions to the payment gateway using an end-to-end secure sockets layer (SSL) connection.

AIM is also the required connection method for shopping cart developers participating in the Authorize.Net Shopping Cart Certification (SCC) program.

  • Employs industry standard secure data encryption technology — 128-bit Secure Sockets Layer (SSL) protocol.
  • Uses transaction key authentication for ultimate security.
  • Allows control over all phases of the customer’s online transaction experience.
  • Configurable transaction response integrates easily with merchant applications.
  • Provides mobile SDKs for Apple iOS and Android.

Automated Recurring Billing (ARB) API

For merchants enabled for the Automated Recurring Billing (ARB) service, the additional ARB API feature supports integration with a Web site payment form or a proprietary business application-allowing online customers or sales representatives using a business application to select and submit subscription- or installment-based payments.

  • Expand payment options for online and mail order/telephone order (MOTO) customers, potentially increasing sales.
  • Create, update, and cancel subscriptions programmatically.
  • Utilize Authorize.Net’s secure data center to store payment information safely for recurring transactions.

Customer Information Manager (CIM) API

The Authorize.Net Customer Information Manager (CIM) allows merchants to create customer profiles that are stored on Authorize.Net’s secure servers. By providing quick access to stored customer information, CIM is ideal for businesses that:

  • Process recurring transactions where the date and/or amount is different each month (e.g. utility companies).
  • Process usage charges – where you only bill when the service is used. (e.g. pay-as-you-go cell phones).
  • Are concerned with PCI compliance.
  • Want to provide returning customers with the convenience of not having to re-enter personal data.

The CIM API supports integration with a Web site payment form or a proprietary business application. The profiles, which include payment and shipping information, can then be referenced in future transactions, eliminating steps in the transaction process for repeat customers and potentially increasing customer loyalty.

WordPress Interview Questions and Answers.


Why “WP to Twitter” plugin fail to submit an update to Twitter in WordPress?
When creating your application, do not click the “create your access token” until you first click on Settings and change the Application Type to “Read, Write and Access direct messages”.
After your Twitter application has been updated to “Read, Write and Access direct messages”, click on the Home tab, and “create your access token”.

1 What is WordPress?

The WordPress web site defines WordPress as “web software you can use to create a beautiful website or blog. “ That describes it in the simplest form possible though I will try to expand on that. WordPress is the platform that we currently use for the majority of all client web sites. It was originally used for blogs but has since expanded to be used for full web sites, both personal and business. The main reason people prefer using WordPress now is that it is extremely easy to use, even for a beginner. Once the site is setup (that is where we come in) you will be able to update the content of your web site yourself, without having to know any programming at all! If you are able to create a document in Microsoft Word then you will be bale to update your web site, it is that easy.
WordPress also allows your site to be expanded with incredible features thanks to the many plugins available. We will determine at the start of the project what you will need and everything will be setup and customized for you.

2 Tell me Is a web site on WordPress secure?

Out of the box WordPress is secure and you should not have to worry about any problems with your site. While we agree with that sentiment it does not stop us from taking extra steps to be positive your site will be secure. Part of the process of creating your site involves us taking extra measures to be sure your site will be secure for you. There are many things we will do that you will never need to understand, but unlike many design firms we will not just do a basic install and walk away. This will help prevent attacks against your web site (something that is not very common to begin with though).
There is a common myth that WordPress web sites are more prone to be attacked or hacked than a normal web site. After working on nothing but WordPress sites and blogs for the past three years I have only had to go in and repair a single site and that was due to a problem with the host of the site and not the site itself. Major businesses now use WordPress for their web sites, I am sure they would not do so if they felt it was not secure.

3 What is the difference between characters 23 and x23?

The first one is octal 23, the second is hex 23.

4 How come the code <?php print Contents: $arr[1]; ?> works, but <?php print Contents: $arr[1][2]; ?> doesnt for two-dimensional array of mine?

Any time you have an array with more than one dimension, complex parsing syntax is required. print “Contents: {$arr[1][2]}” would’ve worked. />

5 Tell me Would you initialize your strings with single quotes or double quotes?

Since the data inside the single-quoted string is not parsed for variable substitution, it’s always a better idea speed-wise to initialize a string with single quotes, unless you specifically need variable substitution.

6 Do you know Why doesnt the following code print the newline properly?

<?php
$str = ‘Hello, there.nHow are you?nThanks for visiting Us’;
print $str;
?>
Because inside the single quotes the n character is not interpreted as newline, just as a sequence of two characters – and n.

7 How to call a constructor for a parent class?

parent::constructor($value)

8 Tell me Are objects passed by value or by reference?

Everything is passed by value.

9 What is the difference between accessing a class method via -> and via ::?

:: is allowed to access methods that can perform static operations, i.e. those, which do not require object initialization.

10 Suppose If the variable $a is equal to 5 and variable $b is equal to character a, whats the value of $$b?

100, it’s a reference to existing variable.

11 How to find out the number of parameters passed into function?

func_num_args() function returns the number of parameters passed in.

12 What is the ternary conditional operator in PHP?

Expression preceding the ? is evaluated, if it’s true, then the expression preceding the : is executed, otherwise, the expression following : is executed.

13 Explain When are you supposed to use endif to end the conditional statement?

When the original if was followed by : and then the code block without braces.

14 Explain Will comparison of string 10″ and integer 11 work in PHP?

Yes, internally PHP will cast everything to the integer type, so numbers 10 and 11 will be compared.

15 How to pass a variable by value in WordPress?

Just like in C++, put an ampersand in front of it, like $a = &$b

16 How to define a constant?

17 Do you know Would I use print $a dollars or {$a} dollars to print out the amount of dollars in this example?

In this example it wouldn’t matter, since the variable is all by itself, but if you were to print something like “{$a},000,000 mln dollars”, then you definitely need to use the braces.

18 Suppose I am trying to assign a variable the value of 0123, but it keeps coming up with a different number, whats the problem?

PHP Interpreter treats numbers beginning with 0 as octal. Look at the similar PHP interview questions for more numeric problems.

21 What are the features of WordPress?

  • The key features of wordpress are –
    1. Full standards compliance
    2. No rebuilding
    3. WordPress Pages
    4. WordPress Links
    5. WordPress Themes
    6. Cross-blog communication tools
    7. Comments
    8. Spam protection
    9. Full user registration
    10. Password Protected Posts
    11. Easy installation and upgrades
    12. Easy Importing
    13. XML-RPC interface
    14. Workflow
    15. Typographical niceties
    16. Intelligent text formatting
    17. Multiple authors
    18. Bookmarklets
    19. Ping away

22 How many tables a default WordPress will have?

A default wordpress will have 11 tables. They are-
1. wp_commentmeta
2. wp_comments
3. wp_links
4. wp_options
5. wp_postmeta
6. wp_posts
7. wp_terms
8. wp_term_relationships
9. wp_term_taxonomy
10.wp_usermeta
11.wp_users

23 Who is the founder of WordPress?

Matthew Charles Mullenweg.

24 What if I need help after the project?

That is what we are here for! You will get full training at the conclusion of the project and we will be available for email support following the project when needed. Additional one on one training will be available at an additional cost if needed.
Coming soon we will be launching a new members support area here on the web site that will include full training for clients only. This will include a number of PDF downloads, tutorials and video training. This will be available to all past and future clients.

25 Are there any limitations to a WordPress web site?

Not that we have found yet. You can use WordPress for e-commerce sites, membership sites, photo galleries and any other type of site you can think of. The web site is created using the same html code as any other site so there are no limitations there either. I have yet to find a reason not to use WordPress for any client site.

26 Do I need to have a blog in order to use WordPress for my site?

WordPress was originally used as blogging software (and still is) though it has since become popular for web sites also. You do not need to include a blog on your web site in order to use WordPress. We have created a number of sites that do not have any blog at all but the client wanted the ability to update content themselves so we used WordPress.
We do suggest having a blog because it will help with your search engine optimization. Though we only suggest that if you plan on updating the blog on a regular basis, otherwise having a blog without any updates is not going to do you any good.

27 Will using WordPress help my site show up on Google?

Yes. That is one of the major selling points of using WordPress is that it includes excellent built in search engine optimization (SEO). With a normal site you would need to include all of the SEO yourself (or hire someone). While it is still recommended that you hire someone for a full SEO campaign if needed, the built in SEO capabilities of WordPress more than enough to get you started.
We will also install additional plugins to help with your SEO when you first launch the site. These are popular plugins that are known to help your rank on search engines such as Google and Bing.

28 Do I need to know any programming to make updates?

To initially setup a site and customize it you will, though you don’t need to worry about that because that is what we are doing for you. Once the site is setup we will train you on how to perform the updates (very simple) and you will be good to go. In order to perform the content updates you may need in the future you will not need to know any programming at all. I compared it earlier to using Microsoft Word and it really is that easy!
Forget about having to hire a programmer to make simple text updates on your site from now on, you can go in and do it yourself in a matter of minutes.

29 Will I have the ability to update my own content?

That depends on the site/project itself. We have created sites where almost every aspect could be edited by the client (content, navigation, photos, forms, etc) and others where it was a simple setup to allow for the main content areas to be edited. This is something we will discuss when planning the project and determine what your need will be. At the very least you will be able to edit the site content yourself and the ability to add/remove photos.

30. How to hide the top admin bar at the frontend of wordpress 3.4?

Add the below mentioned code in the theme(active) function.php add_filter(‘show_admin_bar’, ‘__return_false’);

(or)

Add the below code in the active theme stylesheet

#wpadminbar {

display: none; visibility: hidden;

}
31. In PHP, what are magic methods and how are they used?

PHP functions that start with a double underscore – a “__” – are called magic functions (and/or methods) in PHP. They are functions that are always defined inside classes, and are not stand-alone (outside of classes) functions. The magic functions available in PHP are: __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone(), and __autoload().
32. Run Any Query on the Database for WordPress

The query function allows you to execute any SQL query on the WordPress database. It is best to use a more specific function (see below), however, for SELECT queries.

 <?php $wpdb->query('query'); ?>

33.What are the Feature of WordPress?

  • Simplicity Simplicity makes it possible for you to get online and get publishing, quickly. Nothing should get in the way of you getting your website up and your content out there. WordPress is built to make that happen.
  • Flexibility With WordPress, you can create any type of website you want: a personal blog or website, a photoblog, a business website, a professional portfolio, a government website, a magazine or news website, an online community, even a network of websites. You can make your website beautiful with themes, and extend it with plugins. You can even build your very own application.
  • Publish with Ease If you’ve ever created a document, you’re already a whizz at creating content with WordPress. You can create Posts and Pages, format them easily, insert media, and with the click of a button your content is live and on the web.
  • Publishing Tools WordPress makes it easy for you to manage your content. Create drafts, schedule publication, and look at your post revisions. Make your content public or private, and secure posts and pages with a password.
  • User Management Not everyone requires the same access to your website. Administrators manage the site, editors work with content, authors and contributors write that content, and subscribers have a profile that they can manage. This lets you have a variety of contributors to your website, and let others simply be part of your community.
  • Media Management They say a picture says a thousand words, which is why it’s important for you to be able to quickly and easily upload images and media to WordPress. Drag and drop your media into the uploader to add it to your website. Add alt text, captions, and titles, and insert images and galleries into your content. We’ve even added a few image editing tools you can have fun with.
  • Full Standards Compliance Every piece of WordPress generated code is in full compliance with the standards set by the W3C. This means that your website will work in today’s browser, while maintaining forward compatibility with the next generation of browser. Your website is a beautiful thing, now and in the future.
  • Easy Theme System WordPress comes bundled with two default themes, but if they aren’t for you there’s a theme directory with thousands of themes for you to create a beautiful website. None of those to your taste? Upload your own theme with the click of a button. It only takes a few seconds for you to give your website a complete makeover.
  • Extend with Plugins WordPress comes packed full of features for every user, for every other feature there’s a plugin directory with thousands of plugins. Add complex galleries, social networking, forums, social media widgets, spam protection, calendars, fine-tune controls for search engine optimization, and forms.
  • Built-in Comments Your blog is your home, and comments provide a space for your friends and followers to engage with your content. WordPress’s comment tools give you everything you need to be a forum for discussion and to moderate that discussion.
  • Search Engine Optimized When the head of Google’s web spam team says that WordPress is a great choice, taking care of 80-90% of the mechanics of search engine optimization for you, you know you’re on to a good thing. For more fine-grained SEO control, there are plenty of SEO plugins to take care of that for you.
  • Multilingual WordPress is available in more than 70 languages. If you or the person you’re building the website for would prefer to use WordPress in a language other than English, that’s easy to do.
  • Easy Installation and Upgrades WordPress has always been easy to install and upgrade. If you’re happy using an FTP program, you can create a database, upload WordPress using FTP, and run the installer. Not familiar with FTP? Plenty of web hosts offer one-click WordPress installers that let you install WordPress with, well, just one click!
  • Importers Using blog or website software that you aren’t happy with? Running your blog on a hosted service that’s about to shut down? WordPress comes with importers for blogger, LiveJournal, Movable Type, TypePad, Tumblr, and WordPress. If you’re ready to make the move, we’ve made it easy for you.
  • Own Your Data Hosted services come and go. If you’ve ever used a service that disappeared, you know how traumatic that can be. If you’ve ever seen adverts appear on your website, you’ve probably been pretty annoyed. Using WordPress means no one has access to your content. Own your data, all of it – your website, your content, your data.
  • Freedom WordPress is licensed under the GPL which was created to protect your freedoms. You are free to use WordPress in any way you choose: install it, use it, modify it, distribute it. Software freedom is the foundation that WordPress is built on.
  • Community As the most popular open source CMS on the web, WordPress has a vibrant and supportive community. Ask a question on the support forums and get help from a volunteer, attend a WordCamp or Meetup to learn more about WordPress, read blogs posts and tutorials about WordPress. Community is at the heart of WordPress, making it what it is today.
  • Contribute You can be WordPress too! Help to build WordPress, answer questions on the support forums, write documentation, translate WordPress into your language, speak at a WordCamp, write about WordPress on your blog. Whatever your skill, we’d love to have you!

Developer Features

For developers, we’ve got lots of goodies packed under the hood that you can use to extend WordPress in whatever direction takes your fancy.

  • Plugin System The WordPress APIs make it possible for you to create plugins to extend WordPress. WordPress’s extensibility lies in the thousands of hooks at your disposal. Once you’ve created your plugin, we’ve even got a plugin repository for you to host it on.
  • Theme System Create WordPress themes for clients, customers, and for WordPress users. The WordPress API provides the extensibility to create themes as simple or as complex as you wish. If you want to give your theme away for free you can give it to users in the Theme Repository
  • Application Framework If you want to build an application, WordPress can help with that too. Under the hood WordPress provides a lot of the features that your app will need, things like translations, user management, HTTP requests, databases, URL routing and much, much more.
  • Custom Content Types WordPress comes with default content types, but for more flexibility you can add a few lines of code to create your own custom post types, taxonomies, and metadata. Take WordPress in whatever direction you wish.
  • The Latest Libraries WordPress comes with the latest script libraries for you to make use of. These include jQuery, Plupload, Underscore.js and Backbone.js. We’re always on the lookout for new tools that developers can use to make a better experience for our users.

34. What are rules to follow in wordpress plugin development?

  • Find a unique name
  • Setup a prefix (related to your brand)
  • Create the plugin’s folder
  • Create sub-folders for PHP files, assets, and translations
  • Create the main plugin file and fill in obligatory header information
  • Create a readme.txt file
  • Use proper constants and functions to detect paths to plugin files
  • Create additional PHP files and include them inside the main one
  • Create activation and deactivation functions
  • Create an uninstall script

35. What is hooks and types of hooks in wordpress?

Hooks are provided by WordPress to allow your plugin to ‘hook into’ the rest of WordPress; that is, to call functions in your plugin at specific times, and thereby set your plugin in motion. There are two kinds of hooks:

  1. Actions: Actions are the hooks that the WordPress core launches at specific points during execution, or when specific events occur. Your plugin can specify that one or more of its PHP functions are executed at these points, using the Action API.
  2. Filters: Filters are the hooks that WordPress launches to modify text of various types before adding it to the database or sending it to the browser screen. Your plugin can specify that one or more of its PHP functions is executed to modify specific types of text at these times, using the Filter API.

Actions Functions

Filter Functions

35. Does the 644 permissions on wp-config.php compromise the username and password to all other users on my shared server?

This is a limitation of the way PHP is set up on your server. If you previously used MovableType, Perl was probably set up with suexec so Movable Type executed as your user. In this case, PHP is running as the web server user, which is why it has to be at least 444. There is phpsuexec but it seems many hosts don’t use it.

However this is often not an issue on modern shared hosts because even though the file is “world” readable each account is set up with a “jailshell” which keeps people locked in their home directory, and PHP can be easily modified with an open_basedir restriction to keep people from writing PHP scripts to read your files. If you are really concerned, you should contact your host to see what measures they are taking.

How do I prevent my images from being hot-linked by another website?

You can use your .htaccess file to protect images from being hot linked, or, in other words, being linked-to from other websites. This can be a drain on your bandwidth, because if someone links directly to the image on your site, then you lose the bandwidth.

How do I prevent comment flooding?

Comment flooding is when a lot of comments (probably spam) are posted to your website in a very short duration of time. This is only one aspect of the broader problem of comment spam in general, but it can quickly overwhelm a moderator’s ability to manually delete the offending comments.

WordPress manages the worst floods automatically by default. Any commenters from the same IP or e-mail address (other than registered users with manage_options capabilities) that post within 15 seconds of their last comment gets their comment discarded. The time setting can be changed by a number of plugins that extend this functionality. You might also consider one of the many broader spam blocking plugins, such as Akismet, or even turning your comment system over to Disqus.

You could also just change the time setting by directly hacking the core file, but the correct way would be to create and install a very basic plugin and insert the following code:

function dam_the_flood( $dam_it, $time_last, $time_new ) {

if ( ($time_new – $time_last) < 300 ) // time interval is 300

return true; // seconds

return false;

}

add_filter(‘comment_flood_filter’, ‘dam_the_flood’, 10, 3);

How do I redirect users back to my blog’s main page after they login?

By default, WordPress reroutes a registered user to the Administration Panels after they log into the blog. To change the page, there are WordPress Plugins that can handle the redirect, or you can set the Theme function to handle it. See Function_Reference/wp_login_url.

Why can’t I delete the uncategorized Category?

Any Category with a non-zero value for # of Posts in the Administration > Manage > Categories cannot be deleted. The uncategorized Category might be assigned to some Posts, but all Pages are assigned the uncategorized Category. So even though there may be no posts assigned to the uncategorized Category, Pages are included in the count of # of Posts.

The default category cannot be deleted even if it is empty, however you can specify your default categories for posts or links on the Options – Writing page of the admin panel.

How can I have a static front page and posts display on a page called Blog?

If using WordPress as a CMS, you might want to present readers with a static front page, and then display your posts on another page called Blog. To accomplish that follow these instructions:

Create a Page and use “My Front Page” for the Page Title. Of course, in the content for that Page, you can enter the information you want presented on your site’s front page (see example below if you want to display a post).

Create a Page and call it Blog. Nothing needs to be entered in the content field of this Page.

In Administration > Settings > Reading set the Front page displays to A static page, and select My Front Page for Front page:, and select Blog for the Posts page:.

If you want to further customize your front page, you can create a Template, and fit it to meet your needs:

With the help of the Template Hierarchy article, determine what Template is normally used to display your Pages (e.g. page.php or index.php).

Copy that template to myfront.php. If you were using the WordPress Default theme you would copy wp-content/themes/default/page.php to wp-content/themes/default/myfront.php.

In Administration > Appearance > Editor, edit the myfront.php and change the beginning of the file from:

<?php

/**

* @package WordPress

* @subpackage Default_Theme

*/

to:

<?php

/*

Template Name: MyFront

*/

?>

Then access the Page called Front in Administration > Page > Edit and set the Template to MyFront.

Once that’s all working, begin changing myfront.php to make it look like what you want.

That’s it. You are done.

Use this example for the ‘MyFront’ Page Template if you want to display one post, instead of the Page content, on your ‘static front page’:

<?php

/*

Template Name: MyFront

*/

?>

<?php get_header(); ?>

<div id=”content”>

<?php

query_posts(‘p=1′); //set p=x where x is post id of post you want to see or use query_posts(‘cat=1&posts_per_page=1); to show one post from Category 1

if (have_posts()) : ?>

<?php while (have_posts()) : the_post(); ?>

<div <?php post_class() ?> id=”post-<?php the_ID(); ?>”>

<h2><a href=”<?php the_permalink() ?>” rel=”bookmark” title=”Permanent Link to <?php the_title_attribute(); ?>”><?php the_title(); ?></a></h2>

<small><?php the_time(‘F jS, Y’) ?> <!– by <?php the_author() ?> –></small>

<div class=”entry”>

<?php the_content(‘Read the rest of this entry »’); ?>

</div>

<p class=”postmetadata”><?php the_tags(‘Tags: ‘, ‘, ‘, ‘<br />’); ?> Posted in <?php the_category(‘, ‘) ?> | <?php edit_post_link(‘Edit’, ”, ‘ | ‘); ?> <?php comments_popup_link(‘No Comments »’, ’1 Comment »’, ‘% Comments »’); ?></p>

</div>

<?php endwhile; ?>

<div class=”navigation”>

<div class=”alignleft”><?php next_posts_link(‘« Older Entries’) ?></div>

<div class=”alignright”><?php previous_posts_link(‘Newer Entries »’) ?></div>

</div>

<?php else : ?>

<h2 class=”center”>Not Found</h2>

<p class=”center”>Sorry, but you are looking for something that isn’t here.</p>

<?php get_search_form(); ?>

<?php endif; ?>

</div>

<?php get_sidebar(); ?>

<?php get_footer(); ?>

How do I determine a Post, Page, Category, Tag, Link, Link Category, or User ID?

Sometimes it is necessary to know the ID of a particular Post, Page, Category, Tag, Link, Link Category, or User. To determine that ID, use one of these method:

Look in your browser status bar for the ID:

Visit the related ‘Edit’ screen in your Administration Panel. For instance in the case of Posts visit Posts->Edit, for Pages visit Pages->Edit, and for Categories visit Posts->Categories.

Now hover your mouse over the ‘item’ you need the ID. In the case of Pages, hover over that particular Page’s title in the Title column and for Categories hover over the Categories Name in the Name column.

Look at the status bar (at the bottom of your browser) and the you will find at the end of the line something like “post=123″ or “cat_ID=67″. In these cases, 123 is the Page ID, and 67 is the Category ID.

Install a plugin:

Install and activate Reveal IDs for WP Admin, Simply Show IDs, or ShowID for Post/Page/Category/Tag/Comment.

Find the ID displayed with each item.

How can I change what appears between Categories when I post in more than one Category?

To configure the way the post’s categories display, open the index.php file and find the line <div class meta>. There you will see the following code:

<?php the_category() ?>

Inside of the parentheses ( ) and quote marks, add or change this to reflect the new look you desire.

If you would like to have commas between the categories, the tag should read:

<?php the_category(‘,’) ?>

If you would like to have an arrow, the tag would look like this:

<?php the_category(‘ > ‘) ?>

If you would like to have a bullet, the tag would look like this:

<?php the_category(‘ &bull; ‘) ?>

If you would like the “pipe” ( | ) between the categories, the tag would look like this:

<?php the_category(‘ | ‘) ?>

Use your imagination and creativity to make the separations in the categories look any way you like.

Why are all the comments being moderated?

Go to the Options > Discussion panel and make sure that An administrator must approve the comment (regardless of any matches below) is unchecked. With that option selected, all comments are sent to the moderation queue to await approval. Make sure that Hold a comment in the queue if it contains more than x links is not blank and contains a number higher than zero. If this value is blank or zero, all comments containing links will be moderated. If the option mentioned above is unchecked, the link moderation value is higher than zero, and you still have this problem, your Spam Words list probably has blank lines, punctuation marks, or single letters between the information in the list. There should be spaces between the listed items or each item must be on its own line. If you have done this, then upgrade the comment spam plugins you have installed. If this continues to be a problem, deactivate the comment spam plugins one by one to determine the culprit and contact the plugin author for help.

How do I disable comments?

First, unchecked Allow people to post comments on the article on the Options > Discussion panel. This will only disable comments on future posts. Now, to completely disable comments, you will have to edit each past post and uncheck Allow Comments from the Write Post SubPanel. Alternatively, you could run this MySQL query from the command line on a shell account or using phpMyAdmin: UPDATE wp_posts SET comment_status=”closed”;

If your goal is to permanently disable comments, then you should delete the wp-comments-post.php file as well.

How do I disable trackbacks and pingbacks?

First, unchecked Allow link notifications from other Weblogs (pingbacks and trackbacks.) on the Options > Discussion panel. This will only disable trackbacks and pingbacks on future posts. Now, to completely disable trackbacks and pingbacks, you will have to edit each past post and uncheck Allow Pings from the Write Post SubPanel. Alternatively, run this MySQL query from the command line on a shell account or using PHPMyAdmin: UPDATE wp_posts SET ping_status=”closed”;

If your goal is to permanently disable trackbacks and pingbacks, then you should delete the wp-trackback.php file as well.

How do I change the site admin name?

To change your Admin Name, in the Administration Panel, choose the Users->Your Profile tab. Make your changes there. However, you are not able to change the username from within the Administration panel. In order to do this you must directly edit the MySQL database, however this is not recommended as your username is not often seen by other users.

How do I find the absolute path I need for uploading images?

To find the absolute path of a page, absolutepath.zip will help you. Download, unzip, ftp to the location of the page / image / directory and then call the file in your browser – http://www.example.com/images/absolutepath.php

Can I rename the WordPress folder?

If you have not already installed WordPress, you can rename the folder with the WordPress files, before, or even after uploading the files.

If you have already installed WordPress, and you want to rename the folder, login to the weblog as the administrator and change the following settings in Settings > General:

WordPress address (URI):

Blog address (URI):

Once you have done this, you can rename the directory or folder with the WordPress files in it.

How can I hide my blog from people?

Whether you are testing a new version of WordPress, setting up a new blog or have some other reason to limit access, the following information may help you keep unwanted visitors out.

Apache

There is no guaranteed way to do this. You can use the .htaccess file (which also contains your permalink code) to check for certain IP addresses and prevent them from viewing your site. This will only stop the IP address, not the person, so if they have access to an allowed IP address, they can get to your page. One tutorial for this is located at Clockwatchers.com

An .htaccess file can also be used to prevent others from “hot-linking” to your images (bandwidth theft) or to set up a password protected blog.

Apache Basic Authentication

To require a password to access your site using .htaccess and .htpasswd: Clockwatchers.com .htpasswd.

Tools that help you create the files necessary to password protect your site: Clockwatchers.com .htaccess And .htpasswd Tools

Note: When your site is accessed the password is encoded weakly using Base64 and can be easily intercepted and decoded.

Windows IIS Basic Authentication

To require a password if your site is hosted on IIS, you can deselect Allow Anonymous Access and select Basic Authentication. You’ll also need to have a username with a password.

Note: When your site is accessed the password is encoded weakly using Base64 and can be easily intercepted and decoded.

How can I get WordPress working when I’m behind a reverse proxy?

In some setups, it’s necessary to use something other than the HTTP_HOST header to generate URLs. Reverse proxies take the original request and send it to one of a group of servers. To do so, it overwrites the HTTP_HOST with the internal server’s domain. When that domain is not publicly accessible, at best your images might not load correctly, at worst, you’ll be stuck in a redirect loop. To fix this, figure out which header has the right domain name and add a line to your wp-config.php file that overwrites HTTP_HOST with the correct hostname.

If you need to use SERVER_NAME, add this line to wp-config.php:

$_SERVER[‘HTTP_HOST’] = $_SERVER[‘SERVER_NAME’];

If you need to use HTTP_X_FORWARDED_HOST, add this line to wp-config.php:

$_SERVER[‘HTTP_HOST’] = $_SERVER[‘HTTP_X_FORWARDED_HOST’];

Do I really need MySQL?

You certainly need the MySQL database server to power your WordPress blog. In fact, WordPress only supports the MySQL database server. Listed are the PHP and MySQL requirements:

WordPress server requirements for Version 3.2:

PHP version 5.2.4 or greater

MySQL version 5.0.15 or greater

(Optional)(Required for MultiSite) Apache mod_rewrite module (for clean URIs known as Permalinks)

Can I use a database other than MySQL?

Other databases are not supported at the moment.

There are several other excellent database storage engines, such as PostgreSQL and SQLite that WordPress is interested in supporting in the future. Supporting multiple databases is trickier than it sounds and is not under active development, although there are plenty of architectural discussions about the best approach to take. Approaches for increasing the number of supported databases are discussed at Using Alternative Databases. There is a PostgreSQL port of WordPress available called WordPress-Pg.

Why does WordPress use MySQL?

MySQL is extremely fast. It is also the most widely available database server in the world. Open-source and free, MySQL is supported by thousands of low-cost Linux (and Windows!) hosts, which means a very low barrier to entry for anyone wanting to start a WordPress (or database-driven) website. MySQL’s documentation is useful, cogent and thorough. (Note: it may be intimidating if you are new to all this.) Add to all that the fact that users are able to directly manipulate MySQL with phpMyAdmin, developed expressly for that purpose, and it is obvious that MySQL is the best choice. Of course, WordPress insists on the best.

What is XML-RPC?
Overview

XML-RPC is a Remote Procedure Calling protocol that works over the Internet.

An XML-RPC message is an HTTP-POST request. The body of the request is in XML. A procedure executes on the server and the value it returns is also formatted in XML.

Procedure parameters can be scalars, numbers, strings, dates, etc.; and can also be complex record and list structures.

Request example

Here’s an example of an XML-RPC request:

POST /RPC2 HTTP/1.0
User-Agent: Frontier/5.1.2 (WinNT)
Host: betty.userland.com
Content-Type: text/xml
Content-length: 181

examples.getStateName 41

Header requirements

The format of the URI in the first line of the header is not specified. For example, it could be empty, a single slash, if the server is only handling XML-RPC calls. However, if the server is handling a mix of incoming HTTP requests, we allow the URI to help route the request to the code that handles XML-RPC requests. (In the example, the URI is /RPC2, telling the server to route the request to the “RPC2″ responder.)

A User-Agent and Host must be specified.

The Content-Type is text/xml.

The Content-Length must be specified and must be correct.

Payload format

The payload is in XML, a single structure.

The must contain a sub-item, a string, containing the name of the method to be called. The string may only contain identifier characters, upper and lower-case A-Z, the numeric characters, 0-9, underscore, dot, colon and slash. It’s entirely up to the server to decide how to interpret the characters in a methodName.

For example, the methodName could be the name of a file containing a script that executes on an incoming request. It could be the name of a cell in a database table. Or it could be a path to a file contained within a hierarchy of folders and files.

If the procedure call has parameters, the must contain a sub-item. The sub-item can contain any number of s, each of which has a .

Scalar s

s can be scalars, type is indicated by nesting the value inside one of the tags listed in this table:

 

HTML5 and CSS3 Interview Questions & Answers for UI Development.


HTML5 interview questions and Answers:

What is SVG and advantages of SVG?

SVG is a language for describing two-dimensional vector graphics in XML.

SVG stands for Scalable Vector Graphics
SVG is used to define vector-based graphics for the Web
SVG defines the graphics in XML format
SVG graphics do NOT lose any quality if they are zoomed or resized
Every element and every attribute in SVG files can be animated
SVG is a W3C recommendation

Code Example:

<?xml version=”1.0″ standalone=”no”?>
<!DOCTYPE svg PUBLIC “-//W3C//DTD SVG 1.1//EN”
http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd&#8221;&gt;

<svg xmlns=”http://www.w3.org/2000/svg&#8221; version=”1.1″>
<circle cx=”100″ cy=”50″ r=”40″ stroke=”black”
stroke-width=”2″ fill=”red” />
</svg>

Advantages:

Advantages of using SVG over other image formats (like JPEG and GIF) are:

SVG images can be created and edited with any text editor
SVG images can be searched, indexed, scripted, and compressed
SVG images are scalable
SVG images can be printed with high quality at any resolution
SVG images are zoomable (and the image can be zoomed without degradation)

Differences Between SVG and Canvas:

SVG is a language for describing 2D graphics in XML.

Canvas draws 2D graphics, on the fly (with a JavaScript).

SVG is XML based, which means that every element is available within the SVG DOM. You can attach JavaScript event handlers for an element.

In SVG, each drawn shape is remembered as an object. If attributes of an SVG object are changed, the browser can automatically re-render the shape.

Canvas is rendered pixel by pixel. In canvas, once the graphic is drawn, it is forgotten by the browser. If its position should be changed, the entire scene needs to be redrawn, including any objects that might have been covered by the graphic.

Difference between Transitional and Strict doctype.

Strict : This DTD contains all HTML elements and attributes, but does NOT INCLUDE presentational or deprecated elements (like font). Framesets are not allowed.

Transitional : This DTD contains all HTML elements and attributes, INCLUDING presentational and deprecated elements (like font). Framesets are not allowed.

What are New Semantic/Structural Elements
HTML5 offers new elements for better structure:
Tag Description
<article> Defines an article
<aside> Defines content aside from the page content
<bdi> Isolates a part of text that might be formatted in a different direction from other text outside it
<command> Defines a command button that a user can invoke
<details> Defines additional details that the user can view or hide
<dialog> Defines a dialog box or window
<summary> Defines a visible heading for a <details> element
<figure> Specifies self-contained content, like illustrations, diagrams, photos, code listings, etc.
<figcaption> Defines a caption for a <figure> element
<footer> Defines a footer for a document or section
<header> Defines a header for a document or section
<hgroup> Groups a set of <h1> to <h6> elements when a heading has multiple levels
<mark> Defines marked/highlighted text
<meter> Defines a scalar measurement within a known range (a gauge)
<nav> Defines navigation links
<progress> Represents the progress of a task
<ruby> Defines a ruby annotation (for East Asian typography)
<rt> Defines an explanation/pronunciation of characters (for East Asian typography)
<rp> Defines what to show in browsers that do not support ruby annotations
<section> Defines a section in a document
<time> Defines a date/time
<wbr> Defines a possible line-break

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
For embedded content, such as a plug-in
<track> For text tracks used in mediaplayers
we can use Canvas element in html5 like <canvas></canvas>
Q 5- Do you know New Input Type Attribute in HTML5
Ans: 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
1. <video width=“320″ height=“240″ controls=“controls”>
2. <source src=“mysong.mp4″ type=“video/mp4″ />
3. <source src=“mysong.ogg” type=“video/ogg” />
4. </video>
And audio like this
1. <audio controls=“controls”>
2. <source src=“mysong.ogg” type=“audio/ogg” />
3. <source src=“mysong.mp3″ type=“audio/mpeg” />
4. </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
1. <script type=“text/javascript”>
2. localStorage.name=“PHPZAG”;
3. document.write(localStorage.name);
4. </script>
5. <script type=“text/javascript”>
6. localStorage.address=“Newyork USA”;
7. document.write(localStorage.address);
8. </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
1. <script type=“text/javascript”>
2. sessionStorage.name=“PHPZAG”;
3. document.write(sessionStorage.name);
4. </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
1. <canvas id=“pcdsCanvas” width=“500″ height=“400″>
2. </canvas>
3. <script type=“text/javascript”>
4. var pcdsCanvas=document.getElementById(“phpzagCanvas”);
5. var pcdsText=pcdsCanvas.getContext(“2d”);
6. pcdsText.fillStyle=“#82345c”;
7. pcdsText.fillRect(0,0,150,75);
8. </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:
1. <audio controls=“controls”>
2. <source src=“test.mp3″ type=“audio/mp3″ />
3. </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
1. <script type=“text/javascript”>
2. localStorage.lastname=“ZAG”;
3. document.write(localStorage.lastname);
4. </script>
SessionStorage – stores data for one session.The data is deleted when the user closes the browser window.
1. <script type=“text/javascript”>
2. sessionStorage.lastname=“ZAG”;
3. document.write(sessionStorage.lastname);
4. </script>
Q 14- HOW DO YOU PLAY A VIDEO USING HTML5?
Ans:
We can display video using the tag as shown below:
1. <video width=“320″ height=“240″ controls=“controls”>
2. <source src=“test.mp4″ type=“video/mp4″ />
3. </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
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.

What is HTML5?
Ans :
HTML5 is The New HTML Standard with new elements, attributes, and behaviors.

———————————————————————————————-
HTML 5 Features:
Ans :

1. The <canvas> element for 2D drawing
2. The <video> and <audio> elements for media playback
3. local storage support.
4. Added New elements, like <figure>,<small>, <header>, <nav>,<article>, <footer>, <section>,<mark>
5. New form controls, like placeholder,calendar, date, time, email, url, search,required ,autofocus
6. In HTML5 there is only one <!doctype> declaration: <!DOCTYPE html>
———————————————————————————————-
What is HTML5 Web Storage?
Ans :
In HTML5, we can store data locally within the user’s browser.It is possible to store large amounts of data without affecting the website’s performance.
Web Storage is more secure and faster.
there are two types of Web Storages
1.LocalStorage:stores data locally with no limit
2.SessionStorage:stores data for one session

———————————————————————————————-
How to store data on client in HTML5?
Ans : we can store data using HTML5 Web Storage.

1.LocalStorage

<script type=”text/javascript”>
localStorage.name=”Raj”;
document.write(localStorage.name);
</script>

2.SessionStorage
<script type=”text/javascript”>
sessionStorage.email=”test@gmail.com”;
document.write(sessionStorage.email);
</script>

———————————————————————————————-
How do you play a Video using HTML5?

Ans : HTML5 defines a new element to embed a video on Web Page
the <video> element.

Example:
<video width=”500″ height=”300″ controls>
<source src=”video1.mp4″ type=”video/mp4″>
</video>

———————————————————————————————-
How do you play a Audio using HTML5?

Ans : HTML5 defines a new element to embed a video on Web Page
the <audio> element.

Example:
<audio controls>
<source src=”audio.mp3″ type=”audio/mpeg”>
</audio>

———————————————————————————————-
Canvas Element in HTML5?
Ans : The canvas element is used to draw graphics images on a web page

<canvas id=”canvas_image” width=”400″ height=”200″></canvas>

The canvas is a two-dimensional grid.

———————————————————————————————-
HTML5 <input> Types ?
Ans :
• search
• tel
• time
• color
• email
• month
• date
• datetime
• datetime-local
• number
• range
• url
• week

———————————————————————————————-
HTML5 New Form Attributes?
Ans :

• pattern
• placeholder
• required
• step
• autocomplete
• autofocus
• height and width
• list
• min and max
• multiple
• form
• formaction
• formenctype
• formmethod
• formnovalidate
• formtarget
———————————————————————————————-
What does a <hgroup> tag do?

Ans : The <hgroup> tag is used to group heading elements.
The <hgroup> element is used to group a set of <h1> to <h6> elements.

<hgroup>
<h1>Hello</h1>
<h2>How r u?</h2>
</hgroup>

———————————————————————————————-
Which video formats are used for the video element?
Ans :

Internet Explorer 9+: MP4
Chrome 6+: MP4, WebM, Ogg
Firefox 3.6+ : WebM, Ogg
Safari 5+ : MP4,
Opera 10.6+ : WebM,Ogg

———————————————————————————————-
Difference between HTML4 and HTML5
———————————————————————————————-
What is the <!DOCTYPE> ? Is it necessary to use in HTML5 ?
Ans : The <!DOCTYPE> declaration must be the very first thing in HTML5 document, before the <html> tag

———————————————————————————————-
What are the New Media Elements in HTML5?
Ans :

• <audio>
• <video>
• <source>

• <track>
1 :: What is the status of the development of the HTML 5 standard?
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. As of March 2010, the specification is in the Draft Standard state at the WHATWG, and in Working Draft state at the W3C.

2 :: What are the new APIs provided by the HTML 5 standard? Give a brief description of each
► 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

3 :: What purpose does HTML5 serve?
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.

4 :: What other advantages does HTML5 have?
► Cleaner markup
► Standardized approach to mobile devices support
► Additional semantics of new elements like <header>, <nav>, and <time>
► New form input types and attributes that will (and in Opera’s case, do) take the hassle out of scripting forms.

5 :: WHAT IS THE DIFFERENCE BETWEEN HTML5 APPLICATION CACHE AND REGULATE HTML BROWSER CACHE?
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.

6 :: WHAT IS HTML5?
HTML5 is the latest version of HTML standard supporting multimedia and graphical content.
1

7 :: GIVE AN EXAMPLE OF NEW ELEMENTS IN HTML5 TO SUPPORT MULTIMEDIA AND GRAPHICS?
HTML5 introduced many elements such as , instead of to support multimedia.
1

8 :: Explain WHAT OTHER ADVANTAGES DOES HTML5 HAVE?
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.
1

9 :: HOW DO YOU PLAY A VIDEO USING HTML5?
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>
1

10 :: WHAT ARE THE DIFFERENT TYPES OF STORAGE IN HTML5?
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>

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

<audio controls=“controls”>
<source src=“test.mp3″ type=“audio/mp3″ />
</audio>

12 :: What is the difference between HTMl5 Application cache and regular HTML browser cache?
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.

13 :: Tell me What purpose does HTML5 serve?
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.

14 :: Can you explain What the use of Canvas Element in HTML5?
The canvas element is used to draw graphics images on a web page by using javascript like below

<canvas id=“pcdsCanvas” width=“500″ height=“400″>
</canvas>
<script type=“text/javascript”>
var pcdsCanvas=document.getElementById(“phpzagCanvas”);
var pcdsText=pcdsCanvas.getContext(“2d”);
pcdsText.fillStyle=“#82345c”;
pcdsText.fillRect(0,0,150,75);
</script>

15 :: Do you know What is the sessionStorage Object in html5? How to create and access?
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=“PHPZAG”;
document.write(sessionStorage.name);
</script>

16 :: Explain What is the use of localStorage in HTML5?
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>

17 :: Tell me How to add video and audio in HTML5
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>

18 :: Tell me Do you know New Input Type Attribute in HTML5
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

19 :: Explain What are the New Media Elements in HTML5? is canvas element used in HTML5
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
For embedded content, such as a plug-in
<track> For text tracks used in mediaplayers

we can use Canvas element in html5 like <canvas></canvas>

20 :: Explain How many New Markup Elements you know in HTML5
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.
21 :: Tell me What is the <!DOCTYPE>? Is it necessary to use in HTML5
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).

22 :: Explain the difference between HTML and HTML5
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

(1) What is the use of Canvas Element in HTML5?
HTML5 Canvas element can be used to draw graphics images on a web page by using javascript.
(2) Can you give an example of Canvas element how it can be used?

<canvas id=“DGTCanvas” width=“500″ height=“400″>
</canvas>
<script type=“text/javascript”>
var DGTCanvas=document.getElementById(“DGTCanvas”);
var DGTText=DGTCanvas.getContext(“2d”);
DGTText.fillStyle=“#82345c”;
DGTText.fillRect(0,0,150,75);
</script>
(3) What is the purpose of HTML5 versus XHTML?
HTML5 is the next version of 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. Instead of using those plugins, it enables browser to serve elements such as video and audio without any additional requirements on the client machine.
(4) What is the difference between HTML and HTML5 ?
HTML5 is nothing more then upgraded version of HTML where in HTML5 supports the innovative features such as 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 elemenents.
(5) WHAT are some other advantages of HTML5?
a) Cleaner markup than earlier versions of HTML
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.
Related article on DGlobalTech.com
• Flash versus HTML5
• HTML5 – Video and Audio File formats and browser support
• HTML Javascript online Realtime Editor
(6) What is the <!DOCTYPE>? Is it mandatory to use in HTML5?
The <!DOCTYPE> is an instruction to the web browser about what version of HTML the page is written in. The <!DOCTYPE> tag does not have an end tag. 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).
(7) What are the New Media Elements in HTML5?
New Media Elements in HTML5 are :
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
For embedded content, such as a plug-in
<track> For text tracks used in mediaplayers
(8) What is the major improvement with HTML5 in reference to Flash?
Flash is not supported by major mobile devices such as iPad, iPhone and universal android applications. Those mobile devices have lack of support for installing flash plugins. HTML5 is supported by all the devices, apps and browser including Apple and Android products. Compared to Flash, HTML5 is very secured and protected. That eliminates major concerns that we have seen with Flash.
(10) What is the sessionStorage Object in html5 ? How you can create and access that?
The HTML5 sessionStorage object stores the data for one session. The data is deleted when the user closes the browser window. We can create and access a sessionStorage, created “name” as session
<script type=“text/javascript”>
sessionStorage.name=“DGTECH”;
document.write(sessionStorage.name);
</script>

HTML5 – New Features
Some of the most interesting new features in HTML5:
• 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
Questions : 1 What is the difference between CSS and CSS3 ?
Answers : 1 CSS3 is upgreaded version of CSS with new future like Selectors,Box Model, Backgrounds and Borders, Text Effects,2D/3D Transformations, Animations, Multiple Column Layout,User Interface etc
Questions : 2 List out CSS3 modules
Answers : 2 Below are the listed major modules
• Selectors
• Box Model
• Backgrounds and Borders
• Text Effects
• 2D/3D Transformations
• Animations
• Multiple Column Layout
• User Interface
Questions : 3 What new futures added in CSS3 for Borders and how Browser Support it?
Answer : 3 following border futures added
• border-radius
• box-shadow
• border-image

and all modern Browser Support it like below
Internet Explorer 9 supports border-radius and box-shadow
Firefox requires the prefix -moz- for border-image.
Chrome and Safari requires the prefix -webkit- for border-image.
Opera requires the prefix -o- for border-image.
Questions : 4 How you will create Rounded Corners using css3
Answer : 4 We have to creat a class like below
<style>
.roundc{
border:2px solid #ff0000;
border-radius:25px;
background:#dddddd;
width:300px;
-moz-border-radius:25px; /* Firefox */
-webkit-border-radius:25px; /* Chrome and Safari */
-o-border-radius:25px; /* Opera */
}
</style>
and we have to add this class where we want the round corner like in below div
<div class=”roundc” > this is the round corner by css3 </div>
This is the div and round corner by css3
Questions : 5 how we create border using images by CSS3
Answers : 5 By using border-image: property of css3 we can create a border using images like below
.roundpcds
{
border-image:url(borderpcds.png) 30 30 round;
-moz-border-image:url(borderpcds.png) 30 30 round; /* Firefox */
-webkit-border-image:url(borderpcds.png) 30 30 round; /* Safari and Chrome */
-o-border-image:url(borderpcds.png) 30 30 round; /* Opera */
}
.stretchPcds
{
-moz-border-image:url(borderpcds.png) 30 30 stretch; /* Firefox */
-webkit-border-image:url(borderpcds.png) 30 30 stretch; /* Safari and Chrome */
-o-border-image:url(borderpcds.png) 30 30 stretch; /* Opera */
border-image:url(borderpcds.png) 30 30 stretch;
}
Questions : 6 How you will create Box Shadow and text Shadow using CSS3 Answers : 6 Like below we can create Box Shadow using CSS3 .boxshadowpcds
{
box-shadow: 10px 10px 5px #ccccc;
}
.textshadowpcds
{
text-shadow: 5px 5px 5px #FF0000;
} and then need to use these class boxshadownpcds ,textshadowpcds
Questions : 7 What is the CSS3 The background size Property
Answers : 7 The background-size property specifies the size of the background image.
As we know Before CSS3, the background image size was find out by the real size of the image. In CSS3 it is possible to specify the size of the background image, which allows you to re-use background images in different ways.
.pcdsbp1
{
background:url(background.gif);
-moz-background-size:80px 60px; /* Firefox 3.6 */
background-size:80px 60px; /* or we can do background-size:100% 100%;*/
background-repeat:no-repeat;
}
Questions : 8 What is the word wrap / word wrapping in CSS3 ?
Answers : 8 to Allow long words to be able to break and wrap onto the next line in css3 we used word-wrap property like below class
.wordwrappcds{word-wrap:break-word;}
Questions : 9 What is the CSS3 animation ?
Answers : 9
When the animation is created in the @keyframe, bind it to a selector, otherwise the animation will have no effect.
Bind the animation to a selector by specifying at least these two CSS3 animation properties:
• Specify the name of the animation
• Specify the duration of the animation

Interview Questions UI(User Interface) Developer


JavaScript

How to create a cookie through Jvascripts?

What is a Cookie?

A cookie is a variable that is stored on the visitor’s computer. Each time the same computer requests a page with a browser, it will send the cookie too. With JavaScript, you can both create and retrieve cookie values.

Examples of cookies:

  • Name cookie – The first time a visitor arrives to your web page, he or she must fill in her/his name. The name is then stored in a cookie. Next time the visitor arrives at your page, he or she could get a welcome message like “Welcome John Doe!” The name is retrieved from the stored cookie
  • Date cookie – The first time a visitor arrives to your web page, the current date is stored in a cookie. Next time the visitor arrives at your page, he or she could get a message like “Your last visit was on Tuesday August 11, 2005!” The date is retrieved from the stored cookie
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

<!DOCTYPE html>
<html>
<head>
<script>
function getCookie(c_name)
{
var c_value = document.cookie;
var c_start = c_value.indexOf(” ” + c_name + “=”);
if (c_start == -1)
{
c_start = c_value.indexOf(c_name + “=”);
}
if (c_start == -1)
{
c_value = null;
}
else
{
c_start = c_value.indexOf(“=”, c_start) + 1;
var c_end = c_value.indexOf(“;”, c_start);
if (c_end == -1)
{
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
}

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? “” : “; expires=”+exdate.toUTCString());
document.cookie=c_name + “=” + c_value;
}

function checkCookie()
{
var username=getCookie(“username”);
if (username!=null && username!=””)
{
alert(“Welcome again ” + username);
}
else
{
username=prompt(“Please enter your name:”,””);
if (username!=null && username!=””)
{
setCookie(“username”,username,365);
}
}
}
</script>
</head>
<body onload=”checkCookie()”>
</body>
</html>

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

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

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

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

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

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

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

17. Where are cookies actually stored on the hard disk?
This depends on the user’s browser and OS.
In the case of Netscape with Windows OS,all the cookies are stored in a single file called

cookies.txt
c:Program FilesNetscapeUsersusernamecookies.txt
In the case of IE,each cookie is stored in a separate file namely username@website.txt.
c:WindowsCookiesusername@Website.txt

23. What is negative infinity?
It’s a number in JavaScript, derived by dividing negative number by zero.

25. What is the data type of variables of in JavaScript?
All variables are of object type in JavaScript.

26. Methods GET and POST in HTML forms – what’s the difference?.
GET: Parameters are passed in the querystring. Maximum amount of data that can be sent via the GET method is limited to about 2kb.
POST: Parameters are passed in the request body. There is no limit to the amount of data that can be transferred using POST. However, there are limits on the maximum amount of data that can be transferred in one name/value pair.

31. Are Java and JavaScript the Same?
No.java and javascript are two different languages.
Java is a powerful object – oriented programming language like C++,C whereas Javascript is a
client-side scripting language with some limitations.

49. How about 2+5+”8″?
Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, it’s concatenation, so 78 is the result.

36. What does “1”+2+4 evaluate to?
Since 1 is a string, everything is a string, so the result is 124.

68. What is the difference between undefined value and null value?
(i)Undefined value cannot be explicitly stated that is there is no keyword called undefined whereas null value has keyword called null
(ii)typeof undefined variable or property returns undefined whereas typeof null value returns object

113. decodeURI(), encodeURI()
Many characters cannot be sent in a URL, but must be converted to their hex encoding. These functions are used to convert an entire URI (a superset of URL) to and from a format that can be sent via a URI.

var uri = “http://www.google.com/search?q=sonofusion Taleyarkhan”
document.write(“Original uri: “+uri);
document.write(”
encoded: “+encodeURI(uri));

44. What is the difference between an alert box and a confirmation box?
An alert box displays only one button which is the OK button whereas the Confirm box
displays two buttons namely OK and cancel.

Still others modify entire elements (or groups of elements) themselves—inserting, copying, removing, and so on. All of these methods are referred to as “setters,” as they change the values of properties.
A few of these methods—such as .attr(), .html(), and .val()—also act as “getters,” retrieving information from DOM elements for later use.

DOM = Document Object Model

The DOM defines a standard for accessing HTML and XML documents:

“The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.”

Get Content – text(), html(), and val()
Three simple, but useful, jQuery methods for DOM manipulation is:
• text() – Sets or returns the text content of selected elements
• html() – Sets or returns the content of selected elements (including HTML markup)
• val() – Sets or returns the value of form fields
$(“#btn1”).click(function(){
$(“#test1”).text(function(i,origText){
return “Old text: ” + origText + ” New text: Hello world!
(index: ” + i + “)”;
});
});

$(“button”).click(function(){
$(“#w3s”).attr({
“href” : “http://www.w3schools.com/jquery&#8221;,
“title” : “W3Schools jQuery Tutorial”
});
});

• append() – Inserts content at the end of the selected elements
• prepend() – Inserts content at the beginning of the selected elements
• after() – Inserts content after the selected elements
• before() – Inserts content before the selected elements
function appendText()
{
var txt1=”

Text.

“; // Create element with HTML
var txt2=$(”

“).text(“Text.”); // Create with jQuery
var txt3=document.createElement(“p”); // Create with DOM
txt3.innerHTML=”Text.”;
$(“p”).append(txt1,txt2,txt3); // Append the new elements
}

• width() sets or returns the width of an element (includes NO padding, border, or margin).
• height()
• innerWidth() returns the width of an element (includes padding).
• innerHeight()
• outerWidth() returns the width of an element (includes padding and border).
• outerHeight()
• outerWidth(true) returns the width of an element (includes padding and border & margin).
The jQuery load() method is a simple, but powerful AJAX method.

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: ‘pcdsEmpRecords.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: ‘pcdsEmpRecords.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 #pcds
$(‘#pcds’).attr(‘disabled’, true);
// Enable #pcds
$(‘#pcds’).attr(‘disabled’, false);
Add or remove the ‘disabled’ attribute:
// Disable #pcds
$(“#pcds”).attr(‘disabled’, ‘disabled’);
// Enable #x
$(“#pcds”).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 #pcds
$(‘#pcds’).attr(‘checked’, true);
// Uncheck #pcds
$(‘#pcds’).attr(‘checked’, false);
Add or remove the ‘checked’ attribute:
// Check #pcds
$(“#pcds”).attr(‘checked’, ‘checked’);
// Uncheck #pcds
$(“#pcds”).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:
$(“#pcdsselect”).val();
// => 1
The second is the text value of the select. For example, using the following select box:
Code:

Mr
Mrs
Ms
Dr
Prof

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:
$(“#mpcdsselect option:selected”).text();
// => “Mr”

• Is jQuery a library for client scripting or server scripting?
Ans: Client scripting
• Is jQuery a W3C standard?
Ans: No
• What are jQuery Selectors?
Ans: Selectors are used in jQuery to find out DOM elements. Selectors can find the elements via ID, CSS, Element name and hierarchical position of the element.
• The jQuery html() method works for both HTML and XML documents?
Ans: It only works for HTML.
• Which sign does jQuery use as a shortcut for jQuery?
Ans: $(dollar) sign.
• What does $(“div”) will select?
Ans: It will select all the div element in the page.
• What does $(“div.parent”) will select?
Ans: All the div element with parent class.
• What is the name of jQuery method used for an asynchronous HTTP request?
Ans: jQuery.ajax()
jQuery Tip : Always load your jQuery framework from CDN
Here is a quick tip for the day. Always load your jQuery framework from Google, Microsoft or jQuery CDN(Content Delivery Network). As it provides several advantages.

1. You always use the latest jQuery framework.
2. It reduces the load from your server.
3. It saves bandwidth. jQuery framework will load faster from these CDN.
4. The most important benefit is it will be cached, if the user has visited any site which is using jQuery framework from any of these CDN.

Code to load jQuery Framework from Google CDN
1

3
Code to load jQuery Framework from Microsoft CDN
1

3
Code to load jQuery Framework from jQuery Site(EdgeCast CDN)
1

3

How to load jQuery locally when CDN fails
There are couple of advantage if you load your jQuery from any CDN. Read my post about “jQuery Tip : Always load your jQuery framework from CDN”. It is a good approach to always use CDN but sometimes what if the CDN is down (rare possibility though) but you never know in this world as anything can happen. So if you have loaded your jQuery from any CDN and it went down then your jQuery code will stop working and your client will start shouting.

Hang on, there is a solution for this as well. Below given jQuery code checks whether jQuery is loaded from Google CDN or not, if not then it references the jQuery.js file from your folder.
1
2
3 if (typeof jQuery == ‘undefined’)
4 {
5 document.write(unescape(“%3Cscript src=’Scripts/jquery.1.5.1.min.js’ type=’text/javascript’%3E%3C/script%3E”));
6 }
7
It first loads the jQuery from Google CDN and then check the jQuery object. If jQuery is not loaded successfully then it will references the jQuery.js file from hard drive location. In this example, the jQuery.js is loaded from Scripts folder.

What is jQuery.noConflict()
What is jQuery.noConflict()? Well, jQuery is popular because there are plenty of useful, simple and easy to use plugins. But while using jQuery plugins, sometimes we include other libraries like prototype, mootools, YUI etc. The problem comes when one or more other libraries are used with jQuery as they also use $() as their global function and to define variables. This situation creates conflict as $() is used by jQuery and other library as their global function. To overcome from such situations, jQuery has introduced jQuery.noConflict().
How to use it?
01
02
03
04 jQuery.noConflict();
05 // Use jQuery via jQuery(…)
06 jQuery(document).ready(function(){
07 jQuery(“div”).hide();
08 });
09 // Use Prototype with $(…), etc.
10 $(‘someid’).hide();
11
When .noConflict() is called then jQuery returns $() to its previous owner and you will need to use jQuery() instead of shorthand $() function. In this case, “jQuery” will be used in rest of the code. You won’t be able to take advantage of shorthand.

There is another option if you want to take advantage of shorthand.
01
02
03
04 var $j = jQuery.noConflict();
05 // Use jQuery via jQuery(…)
06 $j(document).ready(function(){
07 $j(“div”).hide();
08 });
09 // Use Prototype with $(…), etc.
10 $(‘someid’).hide();
11
But you still love $() and don’t want to lose it. So what to do? But there is a solution for this also.
01
02
03
04 jQuery.noConflict();
05 // Put all your code in your document ready area
06 jQuery(document).ready(function($){
07 // Do jQuery stuff using $
08 $(“div”).hide();
09 });
10 // Use Prototype with $(…), etc.
11 $(‘someid’).hide();
12
What you need to do is in jQuery(document).ready() put function($) and now you use $ for your jQuery code.

Difference between $(this) and ‘this’ in jQuery
Before writing this post, I was also confused about ‘$(this)’ and ‘this’ in jQuery. I did some R&D and found out the difference between both of them. Let’s first see how do we use them.
1 $(document).ready(function(){
2 $(‘#spnValue’).mouseover(function(){
3 alert($(this).text());
4 });
5 });
1 $(document).ready(function(){
2 $(‘#spnValue’).mouseover(function(){
3 alert(this.innerText);
4 });
5 });
Got any idea about the difference?

this and $(this) refers to the same element. The only difference is the way they are used. ‘this’ is used in traditional sense, when ‘this’ is wrapped in $() then it becomes a jQuery object and you are able to use the power of jQuery.

In the second example, I have to use innerText() to show the text of the span element as this keyword is not a jQuery object yet. So I have to use the native JavaScript to get the value of span element. But once it is wrapped in $() then jQuery method text() is used to get the text of Span.

So the summary is $(this) is a jQuery object and you can use the power and beauty of jQuery, but with ‘this’ keyword, one need to use native JavaScript.

jQuery empty() vs remove()
jQuery provides 2 methods empty() and remove() to remove the elements from DOM. I have seen the programmers getting confused between both the methods.

empty() method removes all the child element of the matched element where remove() method removes set of matched elements from DOM. Confused? Let me explain you with an example.

There are 2 div elements “dvParent” and “dvChild”.

Parent Div

jQuery By Example: Demo of empty() vs remove() method.

Now when we call empty() method on “dvChild”, then it will remove all the child element of div.

$(‘#dvChild’).empty();

Result will be:

Parent Div

Now when remove() method is called on “dvChild” element then it will not only remove the child element but it will also remove the “dvChild” element from DOM.
$(‘#dvChild’).remove();
Result will be:

Parent Div

So the difference between both the method is that empty() remove only the child element of the element on which the method is called where remove() method removes not only the child but also the element on which it is called.

So to summarize, there are 3 differences between .remove() and .detach()
• remove() method would erase data associated with the element(data that had been set using the data() method).
• remove() method would also erase the event associated with the element.
• If you are not concerned about the data and event then use remove() as it is faster than detach(). There is a performance test created at jsPerf.com for remove() and detach() and below is the result.

Is window.onload is different from document.ready()
window.onload() is traditional Java script code which is used by developers from many years. This event is gets called when the page is loaded. But how this is different from jQuery document.ready() event?

Well, the main difference is that document.ready() event gets called as soon as your DOM is loaded. It does not wait for the contents to get loaded fully. For example, there are very heavy images on any web page and takes time to load. If you have used window.onload then it will wait until all your images are loaded fully, hence it slows down the execution. On the other side, document.ready() does not wait for elements to get loaded.

$(function(){

// jQuery methods go here…

});
jQuery Tip – How to check if element is empty
In this post, I will show you a simple tip to check or verify that the element that you are accessing in jQuery is empty or not. jQuery provides a method to get and set html of any control.Check these articles for more details.
• Get HTML of any control using jQuery
• Set HTML of any control using jQuery
We will use the same html() attribute to determine whether the element is empty or not.
1 $(document).ready(function() {
2 if ($(‘#dvText’).html()) {
3 alert(‘Proceed as element is not empty.’);
4 }
5 else
6 {
7 alert(‘Element is empty’);
8 }
9 });
Declare a div element “dvText” with no content like this.
1

But there is a problem here. If you declare your div like below given code, above jQuery code will not work because your div is no more empty. By default some spaces gets added.
1

2

So what’s the solution? Well, I had posted about “How to remove space from begin and end of string using jQuery”, so we will use the trim function to trim the spaces from the begin and end of the html() attribute.

1 $(document).ready(function() {
2 if ($(‘#dvText’).html().trim()) {
3 alert(‘Proceed as element is not empty.’);
4 }
5 else
6 {
7 alert(‘Element is empty’);
8 }
9 });

width() vs css(‘width’) and height() vs css(‘height’)
jQuery provides two ways to set width and height of any element. You can set using css or you can use jQuery provided methods. If you want to set width to 100px then
1 $(‘#dvText1’).css(‘width’,’100px’);
1 $(‘#dvText2’).width(100);
Then what is the difference?

The difference lies in datatype. As its clear in code that with css method you need to append ‘px’ to the width value and with width you don’t need to specify.

When you want to read width of any element then css method will return you string value like ‘100px’ while width will return an integer value.
1 alert($(‘#dvText1’).css(‘width’));
This return ‘100px’.
1 alert($(‘#dvText2’).width());
This returns 100.

So if you want to do any kind of manipulation then width function is the best option.

How to Check element exists or not in jQuery
Have you ever thought that what will happen if you try to access an element using jQuery which does not exist in your DOM? For example, I am accessing “dvText” element in below code and that element does not exists in my DOM.
1 var obj = $(“#dvText”);
2 alert(obj.text());
What will happen?

There could be 2 possibilities. Either an error will be thrown and rest of the code will not get executed OR Nothing will happen.

If you think that error will be thrown then you are wrong. In jQuery, you don’t need to be worried about checking the existence of any element. If element does not exists, jQuery will do nothing.

Then what is this post all about? As post title says “How to Check element exists or not in jQuery”, where you are not worried about element existence as jQuery handles it quite well. Well, Let say there is some long code related to the element you want to execute and you are not sure that element exists or not. jQuery doesn’t throw error but that doesn’t mean that you don’t check the existence. So it’s always better to check the existence. So how do we check it? See below code
1 if ($(‘#dvText’).length) {
2 // your code
3 }
jQuery provides length property for every element which returns 0 if element doesn’t exists else length of the element.

/* The .bind() method attaches the event handler directly to the DOM
element in question ( “#members li a” ). The .click() method is
just a shorthand way to write the .bind() method. */

$( “#members li a” ).bind( “click”, function( e ) {} );
$( “#members li a” ).click( function( e ) {} );

/* The .live() method attaches the event handler to the root level
document along with the associated selector and event information
( “#members li a” & “click” ) */

$( “#members li a” ).live( “click”, function( e ) {} );

/* The .delegate() method behaves in a similar fashion to the .live()
method, but instead of attaching the event handler to the document,
you can choose where it is anchored ( “#members” ). The selector
and event information ( “li a” & “click” ) will be attached to the
“#members” element. */

$( “#members” ).delegate( “li a”, “click”, function( e ) {} );

Bind attaches an event handler only to the elements that match a particular selector. This, expectedly, excludes any dynamically generated elements.

1. $(“#items li”).click(function() {
2. $(this).parent().append(”

  • New Element

“);
3. });
Live allows for the binding of event handlers to all elements that match a selector, including those created in the future. It does this by attaching the handler to the document. Unfortunately, it does not work well with chaining.
4. // children().next()…etc.
5. $(“li”).live(“click”, function() {
6. $(this).parent().append(”

  • New Element

“);
7. });
Delegate is a complete replacement for Live(). However, that obviously would have broken a lot of code! Nonetheless, delegate remedies many of the short-comings found in live(). It attaches the event handler directly to the context, rather than the document. It also doesn’t suffer from the chaining issues that live does. There are many performance benefits
8. // to using this method over live().
9. $(‘#items’).delegate(‘li’, ‘click’, function() {
10. $(this).parent().append(‘

  • New Element

‘);
11. });
12. // By passing a DOM element as the context of our selector, we can make
13. // Live() behave (almost) the same way that delegate()
14. // does. It attaches the handler to the context, not
15. // the document – which is the default context.
16. // The code below is equivalent to the delegate() version
17. // shown above.
18. $(“li”, $(“#items”)[0]).live(“click”, function() {
19. $(this).parent().append(”

  • New Element

“);
20. });

More Examples of jQuery Selectors
Syntax Description Example
$(“*”) Selects all elements Try it

$(this) Selects the current HTML element Try it

$(“p.intro”) Selects all

elements with class=”intro” Try it

$(“p:first”) Selects the first

element Try it

$(“ul li:first”) Selects the first

  • element of the first
      Try it

$(“ul li:first-child”) Selects the first

  • element of every
      Try it

$(“[href]”) Selects all elements with an href attribute Try it

$(“a[target=’_blank’]”) Selects all elements with a target attribute value equal to “_blank” Try it

$(“a[target!=’_blank’]”) Selects all elements with a target attribute value NOT equal to “_blank” Try it

$(“:button”) Selects all elements and elements of type=”button” Try it

$(“tr:even”) Selects all even
elements Try it

$(“tr:odd”) Selects all odd
elements $(“p”).click(function(){ // action goes here!! });

$(document).ready(function(){
$(“#hide”).click(function(){
$(“p”).hide();
});
});
• fadeIn()fade in a hidden element.
• fadeOut()fade out a visible element.
• fadeToggle()faded out, fadeToggle() will fade them in.& faded in, fadeToggle() will fade them out
• fadeTo()fading to a given opacity
$(“button”).click(function(){
$(“#div1”).fadeTo(“slow”,0.15);
$(“#div2”).fadeTo(“slow”,0.4);
$(“#div3”).fadeTo(“slow”,0.7);
});
$(“button”).click(function(){
$(“#div1”).fadeIn();
$(“#div2”).fadeIn(“slow”);
$(“#div3”).fadeIn(3000);
});

• slideDown()
• slideUp()
• slideToggle()
The jQuery animate() method is used to create custom animations.
$(selector).animate({params},speed,callback);

$(“button”).click(function(){
$(“div”).animate({
left:’250px’,
opacity:’0.5′,
height:’150px’,
width:’150px’
});
});
$(“button”).click(function(){
$(“p”).hide(“slow”,function(){
alert(“The paragraph is now hidden”);
});
});
jQuery Method Chaining
$(“#p1”).css(“color”,”red”).slideUp(2000).slideDown(2000);

Empty, Remove, Detach
So the difference between both the method is that empty() remove only the child element of the element on which the method is called where remove() method removes not only the child but also the element on which it is called.
So to summarize, there are 3 differences between .remove() and .detach()
• remove() method would erase data associated with the element(data that had been set using the data() method).
• remove() method would also erase the event associated with the element.
• If you are not concerned about the data and event then use remove() as it is faster than detach(). There is a performance test created at jsPerf.com for remove() and detach() and below is the result.
Difference between body onload() function document.ready() function used in jQuery?

1. We can have more than one document.ready() function in a page where we can have only one body onload function.
2. document.ready() function is called as soon as DOM is loaded where body.onload() function is called when everything gets loaded on the page that includes DOM, images and all associated resources of the page.
The .bind() method attaches the event handler directly to the DOM element The .click() method is just a shorthand way to write the .bind() method.

$( “#members li a” ).bind( “click”, function( e ) {} );
$( “#members li a” ).click( function( e ) {} );

The .live() method attaches the event handler to the root level document along with the associated selector and event information

$( “#members li a” ).live( “click”, function( e ) {} );

The .delegate() method behaves in a similar fashion to the .live()
method, but instead of attaching the event handler to the document,

$( “#members” ).delegate( “li a”, “click”, function( e ) {} );

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:

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

,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: ‘pcdsEmpRecords.php’,
success: function(response) {
alert(response);
},
error: function(xhr) {
alert(‘Error! Status = ‘ + xhr.status);
}
});

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 #pcds
$(‘#pcds’).attr(‘disabled’, true);
// Enable #pcds
$(‘#pcds’).attr(‘disabled’, false);
Add or remove the ‘disabled’ attribute:
// Disable #pcds
$(“#pcds”).attr(‘disabled’, ‘disabled’);
// Enable #x
$(“#pcds”).removeAttr(‘disabled’);

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:
$(“#pcdsselect”).val();
// => 1
The second is the text value of the select. For example, using the following select box:
Code:

Mr

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:
$(“#mpcdsselect option:selected”).text();
// => “Mr”

Q2. Why jQuery?
Ans: Due to following functionality.
1. Cross-browser support (IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+)
2. AJAX functions
3. CSS functions
4. DOM manipulation
5. DOM transversal
6. Attribute manipulation
7. Event detection and handling
8. JavaScript animation
9. Hundreds of plug-ins for pre-built user interfaces, advanced animations, form validation etc.
10. Expandable functionality using custom plug-ins
Q3. Is jQuery replacement of Java Script?
Ans: No. jQuery is not a replacement of JavaScript. jQuery is a different library which is written on top of JavaScript. jQuery is a lightweight JavaScript library that emphasizes interaction between JavaScript and HTML.
Q8. What are the different type of selectors in Jquery?
Ans: There are 3 types of selectors in Jquery
1. CSS Selector
2. XPath Selector
3. Custom Selector
Q9. Name some of the methods of JQuery used to provide effects?
Ans: Some of the common methods are :
1. Show()
2. Hide()
3. Toggle()
4. FadeIn()
5. FadeOut()
Q10. What is JQuery UI?
Ans: jQuery UI is a library which is built on top of jQuery library. jQuery UI comes with cool widgets, effects and interaction mechanism.
What are features of JQuery or what can be done using JQuery?
Features of Jquery
1. One can easily provide effects and can do animations.
2. Applying / Changing CSS.
3. Cool plugins.
4. Ajax support
5. DOM selection events
6. Event Handling
Why jQuery?
jQuery is very compact and well written JavaScript code that increases the productivity of the developer by enabling them to achieve critical UI functionality by writing very less amount of code.

It helps to

# Improve the performance of the application
# Develop most browser compatible web page
# Implement UI related critical functionality without writing hundreds of lines of codes
# Fast
# Extensible – jQuery can be extended to implement customized behavior
–>

PHP object oriented questions and answers.


Q. PHP Interfaces: when and why you should use them instead of classes?
First, what are interfaces?

Interfaces are 100% abstract classes – they have methods but the methods have no ‘guts’.
Interfaces cannot be instantiated – they are a construct in OOP that allows you to inject ‘qualities’ into classes .. like abstract classes.
Where an abstract class can have both empty and working/concrete methods, interface methods must all be shells – that is to say, it must be left to the class (using the interface) to flesh out the methods.


interface employee
{
        function setdata($empname,$empage);
        function outputData();
}

class Payment implements employee
{
        function setdata($empname,$empage)
	{
			  //Functionality
			  echo strtoupper($empname);
	}

	function outputData()
	{
				echo "Inside Payment Class";
	}
}

$a = new Payment();
//$a->outputData();
$a->setdata('My name is Steave', 'test');

Example of a class:
class dog
{

	function bark()
	{
		echo “yap, yap, yap …”;
	}

}

Example of an interface:
interface animal
{
	function breath();
	function eat();
}

Note: the interface’s functions/methods cannot have the details/guts filled in – that is left to the class that uses the interface.

Example of a class using an interface:
class dog implements animal
{

     function bark()
     {
           echo “yap, yap, yap …”;
     }

/* the interface methods/functions must be implemented (given their ‘guts’) in the class */

function breath()
 {
        echo “dog is breathing …”;
 }

 function eat()
 {
      echo “dog is easting …”;
 }

}

/*

Remember: when a class uses/implements an interface, the class MUST define all the methods/functions of the interface otherwise the php engine will barf … ‘barf’ is a technical term for: give you an error.

*/

PRIMARY PURPOSES OF AN INTERFACE:

Interfaces allow you to define/create a common structure for your classes – to set a standard for objects.
Interfaces solves the problem of single inheritance – they allow you to inject ‘qualities’ from multiple sources.
Interfaces provide a flexible base/root structure that you don’t get with classes.
Interfaces are great when you have multiple coders working on a project – you can set up a loose structure for programmers to follow and let them worry about the details.

WHEN SHOULD YOU MAKE A CLASS AND WHEN SHOULD YOU MAKE AN INTEFACE?

If you have a class that is never directly instantiated in your program, this is a good candidate for an interface. In other words, if you are creating a class to only serve as the parent to other classes, it should probably be made into an interface.
When you know what methods a class should have but you are not sure what the details will be.
When you want to quickly map out the basic structures of your classes to serve as a template for others to follow – keeps the code-base predictable and consistent.

MISC. NOTES:

The ‘Holy Grail’ of programming is the reuse of existing code – interfaces play an important role in this.
Remember to push up all the code (up the class hierarchy,) to the highest level class. Interfaces help to make this happen.

What is final keyword in class concept?

PHP 5 introduces the final keyword, which 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. If we do that then it will throw an fatal error.

 <?php
class BaseClass
{
    public function test()
    {
        echo "BaseClass::test() called\n";
    }
    final public function moreTesting()
    {
        echo “BaseClass::moreTesting() called\n”;
    }
}

class ChildClass extends BaseClass
{
    public function moreTesting()
    {
        echo “ChildClass::moreTesting() called\n”;
    }
}
// Results in Fatal error: Cannot override final method BaseClass::moreTesting()
?>

Q. Difference between method overloading and method overriding
Method Overloading verses Method OverridingIn Object Oriented Programming (OOP), Overloading is defining functions that have similar signatures, yet have different parameters. Overriding is only pertinent to derived classes, where the parent class has defined a method and the derived class wishes to override that method.Method Overloading means having two or more methods with the same name but with different signature(deifferent parameters list and different type of paramerts) in same class or in differenet classes.

What is Inheritance?
Inheritance is a fundamental capability/construct in OOP where you can use one class, as the base/basis for another class … or many other classes.
What is access modifiers?
Restricting access to properties using ‘ access modifiers ‘
One of the fundamental principles in OOP is ‘encapsulation’. The idea is that you create cleaner better code, if you restrict access to the data structures (properties) in your objects.
You restrict access to class properties using something called ‘access modifiers’. There are 3 access modifiers:
1. public
2. private
3. protected
When you declare a property as ‘private’, only the same class can access the property.
When a property is declared ‘protected’, only the same class and classes derived from that class can access the property – this has to do with inheritance …more on that later.
Properties declared as ‘public’ have no access restrictions, meaning anyone can access them.

What is Constructors?

All objects can have a special built-in method called a ‘constructor’. Constructors allow you to initialise your object’s properties (translation: give your properties values,) when you instantiate (create) an object.
Note: If you create a __contruct() function (it is your choice,) PHP will automatically call the __contruct() method/function when you create an object from your class.
The ‘construct’ method starts with two underscores (__) and the word ‘construct’. You ‘feed’ the constructor method by providing a list of arguments (like a function) after the class name. name = $persons_name;
}
function set_name($new_name) {
$this->name = $new_name;
}
function get_name() {
return $this->name;
}
}
?>

Object Oriented Programming
Introduction to Object-Oriented Programming Using PHP.This page will describes the term `object-oriented programming`.let’s start with few basic concepts before you can begin writing any code.
Object-oriented programming is a method of programming based on a hierarchy of classes, and well-defined objects.

Brief overview of object-oriented concepts and terminology:

• Object.
• Class.
• Inheritance.
• Interface.
• Package.

• The functional/practical advantages:
• For smaller projects, using object oriented PHP may be overkill. That said, object oriented PHP really begins to shine as the project becomes more complex, and when you have more than one person doing the programming.
• For example:
• If you find that you have say 10-20 or more functions and you find that some of the functions are doing similar things … it is time to consider packaging things up into objects and using OOP.
Interfaces:

• In interface all the method must be abstract(only define).
• All methods declared in an interface must be public.
• Interfaces cannot contain variables and concrete methods except constants.
• A class can implement many interfaces and Multiple interface inheritance is possible.
• To extend from an Interface, keyword implements is used.
Example:

interface Shape
{
function getShape();
}

class Circle implements Shape{
public function getShape() {
return “This is Shape of the Circle\n”;
}
}

class MultiInher {
public function read(Shape $s) {
$shape = $s->getShape();
//
echo $shape;
}
}

$c = new Circle();

$m = new MultiInher();
$m->read($c);
Unified Modeling Language(UML)
UML stands for Unified Modeling Language.UML is used to manage large and complex systems.

With UML you can:
• Manage project complexity.
• create database schema.
• Produce reports.
Types of UML Diagrams:
1. Class Diagrams
2. Package Diagrams
3. Object Diagrams
4. Use Case Diagrams
5. Sequence Diagrams
6. Collaboration Diagrams
7. State chart Diagrams
8. Activity Diagrams
9. Component Diagrams
10. Deployment Diagrams
11.
12.

Advantages of object oriented programming:
• Code Re-usability(Polymorphism,Interfaces): In OOPs objects created in one program can be reused in different programs.
• Code extensibility: for addding new features or modifying existing objects can be solved by introducing new objects.
• Catch errors at compile time rather than at runtime.
• Maintainability :objects can be maintained separately, so u can easily fix errors.
• Imrove error handling:We can use exceptions to improve error handling.
• Modularity: can create seperate Modules.
• Modifiability:it is easy to make minor changes in some classes as Changes inside a class do not affect any other part of a program.

• Class in OOP
• class is like a blueprint/template in OOPs, and this template is used to create objects.The collection of properties &behavior of an object is also called as class.
A class contains properties, fields, data members, attributes.

Example:
Car is an object , cars is a class
public class cars
{
//
}

According to the sample given below we can say that the cars object, named object_car, has created out of the cars class.
cars object_car = new cars();

Object in Object oriented programming
object is an instance of a class.An object is an entity that has attributes, behavior, and identity. Objects are members of a class.
Objects are accessed, created or deleted during program run-time.

Declaration of an Object in OOPs
ClassName objectName=new ClassName();

Example:
Car objCar= new Car();

Attribute in OOPs: Attributes define the characteristics of a class. In Class Program attribute can be a string or it can be a integer.
Behavior in OOPS: Every object has behavior.
Identity in OOPS: Each time an object is created the object identity is been defined.
What is the relation between Classes and Objects
Class is a definition, while object is a instance of the class created.
class is like a blueprint/template in OOPs, and this template is used to create objects.The collection of properties &behavior of an object is also called as class.
A class contains properties, fields, data members, attributes.

Example:
Car is an object , cars is a class
public class cars
{
//
}

According to the sample given below we can say that the cars object, named object_car, has created out of the cars class.
cars object_car = new cars();

object is an instance of a class.An object is an entity that has attributes, behavior, and identity. Objects are members of a class.
Objects are accessed, created or deleted during program run-time.

Declaration of an Object in OOPs
ClassName objectName=new ClassName();
Example:
Car objCar= new Car();

Attribute in OOPs: Attributes define the characteristics of a class. In Class Program attribute can be a string or it can be a integer.
Behavior in OOPS: Every object has behavior.
Identity in OOPS: Each time an object is created the object identity is been defined.

Properties of Object Oriented Systems:

• support inheritance
• provides encapsulation of data
• provides extensibility of existing data types and classes
• provide support for complex data types
• Inheritance-one class inherite the property of another class..
• Aggregation-.is a part whole relationship.
• Association.:is a relationship between 1 or more instances of a class.

In this tutorial ,I will explain about abstract class in PHP, how to declare and use of an abstract class.

What is Abstract Class?

It may contain one or more abstract methods.abstract classes may not be instantiated.The child classes which inherits the property of abstract base class, must define all the methods declared as abstract.
Any class that contains at least one abstract method must also be abstract.
if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.

Example:

getValue() . “\n”;
}
}

class ChildClass1 extends AbstractClass
{
protected function getValue() {
return “ChildClass1”;
}

public function setValue($val) {
return “ChildClass{$val}”;
}
}

class ChildClass2 extends AbstractClass
{
public function getValue() {
return “ChildClass2”;
}

public function setValue($val) {
return “ChildClass{$val}”;
}
}

$class1 = new ChildClass1;
$class1->Display();
echo ”
“;
echo $class1->setValue(‘1’) .”\n”;
echo ”
“;
$class2 = new ChildClass2;
$class2->Display();
echo ”
“;
echo $class2->setValue(‘2’) .”\n”;
?>

Encapsulation:
The wrapping of data and function together in a single unit(class) is called encapsulation.
In PHP 4 objects were little more than arrays.In PHP 5 you get much more control by visibility,
interfaces,and more.

PHP5 provides data-hiding capabilities with public, protected, and private data attributes and methods:

Public : A public variable or method can be accessed directly by any user of the class.

Protected : A protected variable or method cannot be accessed by users of the class but can be accessed inside a subclass that inherits from the class.

Private: private variable or method can only be accessed internally from the class in which it is defined.

E.g.:
class is a protective wrapper which binds data and methods together,they can be accessed only though object of that class.

Example:

_circle == null ) {
$this->_circle = new Circle();
}
return $this->_circle;
}

}

class Circle {

private $_radius;

public function __construct() {
$this->_radius = “10”;
}

public function GetRadius() {
return $this->_radius;
}
}

$shape= new Shape();

echo $shape->Circle()->GetRadius();
?>

Abstract Class:

To define a class as Abstract, the keyword abstract is to be used e.g. abstract class ClassName { }

• In abstract class at least one method must be abstract.
• we can create object of abstract class.
• Abstract classes may not be instantiated.
• The child classes which inherits the property of abstract base class, must define all the methods declared as abstract.
• Any class that contains at least one abstract method must also be abstract.
• If the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.
• Abstract class can contain variables and concrete methods.
• A class can Inherit only one Abstract class and Multiple inheritance is not possible for Abstract class.
Example:

getValue() . “\n”;
}
}

class ChildClass1 extends AbstractClass
{
protected function getValue() {
return “ChildClass1”;
}

public function setValue($val) {
return “ChildClass{$val}”;
}
}

class ChildClass2 extends AbstractClass
{
public function getValue() {
return “ChildClass2”;
}

public function setValue($val) {
return “ChildClass{$val}”;
}
}

$class1 = new ChildClass1;
$class1->Display();
echo ”
“;
echo $class1->setValue(‘1’) .”\n”;
echo ”
“;
$class2 = new ChildClass2;
$class2->Display();
echo ”
“;
echo $class2->setValue(‘2’) .”\n”;
?>
Interfaces:

• In interface all the method must be abstract(only define).
• All methods declared in an interface must be public.
• Interfaces cannot contain variables and concrete methods except constants.
• A class can implement many interfaces and Multiple interface inheritance is possible.
• To extend from an Interface, keyword implements is used.
Example:

interface Shape
{
function getShape();
}

class Circle implements Shape{
public function getShape() {
return “This is Shape of the Circle\n”;
}
}

class MultiInher {
public function read(Shape $s) {
$shape = $s->getShape();
//
echo $shape;
}
}

$c = new Circle();

$m = new MultiInher();
$m->read($c);
Difference between abstract classes and interfaces?
Abstract Class:

• To define a class as Abstract, the keyword abstract is to be used.
• In abstract class at least one method must be abstract.
• we can create object of abstract class.
• abstract classes may not be instantiated.
• The child classes which inherits the property of abstract base class, must define all the methods declared as abstract.
• Any class that contains at least one abstract method must also be abstract.
• If the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.
• Abstract class can contain variables and concrete methods.
• A class can Inherit only one Abstract class and Multiple inheritance is not possible for Abstract class.

Interfaces:
• In interface all the method must be abstract.
• All methods declared in an interface must be public.
• Interfaces cannot contain variables and concrete methods except constants.
• A class can implement many interfaces and Multiple interface inheritance is possible.
• To extend from an Interface, keyword implements is used.

Static Keyword:

In this Article,I will explain how to use Static Keyword in PHP5.

• To implement static keyword functionality to the attributes or the methods will have to be prefix with static keyword.
• Static properties or methods can be accessible without needing an instantiation of the class.
• A property declared as static can not be accessed with an instantiated class object.
• $this is not available inside the method declared as static.
• Static properties cannot be accessed using the arrow operator ->.
• Static properties can be accessed using the Scope Resolution Operator (::) operator.
ClassName::$staticvar= $value;

Example:

getColor();
}

public function getColor ()
{
echo Box::$color;
}
}

$a = new Box(“RED”);
$a = new Box(“GREEN”);
$a = new Box(“”);
?>

OUTPUT:
RED
GREEN
GREEN
Static Methods and Properties:

In this Article,I will explain how to use Static properties or methods in PHP5.

• To implement static keyword functionality to the attributes or the methods will have to be prefix with static keyword.
• Static properties or methods can be accessible without needing an instantiation of the class.
• A property declared as static can not be accessed with an instantiated class object.
• $this is not available inside the method declared as static.
• Static properties cannot be accessed using the arrow operator ->.
• Static properties can be accessed using the Scope Resolution Operator (::) operator.

ClassName::$staticvar= $value;

Example:

getColor();
}
public function getColor()
{
echo Box::$color ;
}

static public function StaticMethod() {

echo self::$color;

}

}
$a = new Box(“RED”);
Box::StaticMethod();
$a = new Box(“GREEN”);
$a = new Box(“”);
?>

OUTPUT:
RED
RED
GREEN
GREEN
Constructor:

PHP 5 allows developers to declare constructor methods for classes.Classes call constructor method on each newly-created object.
function __construct() {
//
}
Example:


Note: If PHP 5 cannot find a __construct() function for a given class, it will search for the old constructor function, by the name of the class.

Destructor:

The destructor method will be called as soon as Classes destroy the object.

function __destruct() {
//
}
Example:

Note:The destructor method will be called even if script execution is stopped using exit().
What is access modifier?
OOP provides data-hiding capabilities with public, protected, and private data attributes and methods:

Public : A public variable or method can be accessed directly by any user of the class.

Protected : A protected variable or method cannot be accessed by users of the class but can be accessed inside a subclass that inherits from the class.

Private:A private variable or method can only be accessed internally from the class in which it is defined.
Serialization and UnSerialization in PHP

Serialization/UnSerialization:
• Generates a storable representation of a value.
• serialize() returns a string containing a byte-stream representation of any value that can be stored in PHP.
• unserialize() can use this string to recreate the original variable values.
• This process makes a storable representation of a value that is useful for storing or passing PHP values.
• To make the serialized string into a PHP value again, use unserialize().

Before starting your serialization process, PHP will execute the __sleep function automatically. This is a magic function or method.
Before starting your unserialization process, PHP will execute the __wakeup function automatically. This is a magic function or method.

What can you Serialize and Unserialize?

• Variables
• Arrays
• Objects
What cannot you Serialize and Unserialize?

• Resource-type
Example:
//BaseClass.php
var;
}
}

// test1.php:

include(“BaseClass.php”);

$a = new A;
$v = serialize($a);
file_put_contents(‘store_in_var’, $v);

// page2.php:

include(“BaseClass.php”);
$v = file_get_contents(‘store_in_var’);
$a = unserialize($v);

$a->show();
?>

In the Case if you want to store entire array into database then with serialze() it would be useful to store an entire array in a field in a database.
You can pass an array to the function, and it will return a string that is essentially the string.
You can then unserialize() it to obtain the full array once again.

example:

This will output a:3:{i:0;s:14:”Rajesh Shewale”;i:1;s:6:”Rajesh”;i:2;s:7:”RajeshS”;}
so you can store entire array in a field in a database.


This will output a Array ( [0] => Rajesh Shewale [1] => Rajesh [2] => RajeshS ).

Inheritance in OOP :
In this tutorial we will study about Inheritance.

• Inheritance is a mechanism of extending an existing class.
• In Inheritance child class inherits all the functionality of Parent Class.

For example, when you extend a class, the subclass inherits all of the public and protected methods from the parent class. Unless a class overrides those methods.

GetValue(‘Rajesh Shewale’); // Output: ‘BaseClass: Rajesh Shewale’
$b->setValue(‘Rajesh Shewale’); // Output: ‘Rajesh Shewale’
$c->GetValue(‘Rajesh Tutorials’); // Output:’ChildClass: Rajesh Tutorials’
$c->setValue(‘Rajesh Shewale’); // Output: ‘Rajesh Shewale’

?>
What is Encapsulation?
Encapsulation:
The wrapping of data and function together in a single unit(class) is called encapsulation.
In PHP 4 objects were little more than arrays.In PHP 5 you get much more control by visibility,
interfaces,and more.

PHP5 provides data-hiding capabilities with public, protected, and private data attributes and methods:

Public : A public variable or method can be accessed directly by any user of the class.

Protected : A protected variable or method cannot be accessed by users of the class but can be accessed inside a subclass that inherits from the class.

Private: private variable or method can only be accessed internally from the class in which it is defined.

E.g.:
class is a protective wrapper which binds data and methods together,they can be accessed only though object of that class.

Example:

_circle == null ) {
$this->_circle = new Circle();
}
return $this->_circle;
}

}

class Circle {

private $_radius;

public function __construct() {
$this->_radius = “10”;
}

public function GetRadius() {
return $this->_radius;
}
}

$shape= new Shape();

echo $shape->Circle()->GetRadius();
?>

Polymorphism in OOP:

• Polymorphism in PHP5 : To allow a class member to perform diffrent tasks.
• polymorphism where the function to be called is detected based on the class object calling it at runtime.

Polymorphism helps a sub class to behave like a parent class. When an object belonging to different data types respond to methods which have a same name, the only condition being that those methods should perform different function.
Example:
< ? class Person { public function Talk() { echo “English”; } } class Language extends Person { public function Talk() { echo “French”; } } function CallMethod(Person $p) { $p->Talk();
}

$l = new Language();
CallMethod($l);
?>