CSS [Cascading Style Sheets] Interview questions and answers

Explain in brief about the term CSS.

Answer
A stylesheet language used to describe the presentation of a document written in a markup language. Cascading Style Sheets are a big breakthrough in Web design because they allow developers to control the style and layout of multiple Web pages all at once.
What are the various style sheets?

Answer
Inline, external, imported and embedded are the different types of style sheets.
What are style sheet properties?

Answer
CSS Background
CSS Text
CSS Font
CSS Border
CSS Outline
CSS Margin
CSS Padding
CSS List
CSS Table
List various font attributes used in style sheet.

Answer
font-style
font-variant
font-weight
font-size/line-height
font-family
caption
icon
menu
message-box
small-caption
status-bar
Explain inline, embedded and external style sheets.

Answer
Inline
If only a small piece of code has to be styled then inline style sheets can be used.

Embedded
Embedded style sheets are put between the <head> </head> tags.

External
If you want to apply a style to all the pages within your website by changing just one style sheet, then external style sheets can be used.

1. Explain in brief about the term CSS.
2. What are the various style sheets?
3. What are style sheet properties?
4. List various font attributes used in style sheet.
5. Explain inline, embedded and external style sheets.

What is CSS?
1. CSS stands for Cascading Style Sheets and is a simple styling language which allows attaching style to HTML elements. Every element type as well as every occurrence of a specific element within that type can be declared an unique style, e.g. margins, positioning, color or size.

2. CSS is a web standard that describes style for XML/HTML documents.

3. CSS is a language that adds style (colors, images, borders, margins?) to your site. It?s really that simple. CSS is not used to put any content on your site, it?s just there to take the content you have and make it pretty. First thing you do is link a CSS-file to your HTML document. Do this by adding this line:

<link rel=”stylesheet” href=”style.css”
type=”text/css”>

The line should be placed in between your <head> and </head> tags. If you have several pages you could add the exact same line to all of them and they will all use the same stylesheet, but more about that later. Let?s look inside the file ?style.css? we just linked to.

h1 {
font-size: 40px;
height: 200px;
}
.warning {
color: Red;
font-weight: bold;
}
#footer {
background-color: Gray;
}

4. Cascading Style Sheets (CSS) is a simple mechanism for adding style (e.g. fonts, colors, spacing) to Web documents. This is also where information meets the artistic abilities of a web-designer. CSS helps you spice up your web-page and make it look neat in wide variety of aspects.

What are Cascading Style Sheets?
A Cascading Style Sheet (CSS) is a list of statements (also known as rules) that can assign various rendering properties to HTML elements. Style rules can be specified for a single element occurrence, multiple elements, an entire document, or even multiple documents at once. It is possible to specify many different rules for an element in different locations using different methods. All these rules are collected and merged (known as a “cascading” of styles) when the document is rendered to form a single style rule for each element.

How do I center block-elements with CSS1?
There are two ways of centering block level elements:

1. By setting the properties margin-left and margin-right to auto and width to some explicit value:

BODY {width: 30em; background: cyan;}
P {width: 22em; margin-left: auto; margin-right: auto}

In this case, the left and right margins will each be four ems wide, since they equally split up the eight ems left over from (30em – 22em). Note that it was not necessary to set an explicit width for the BODY element; it was done here to keep the math clean.

Another example:

TABLE {margin-left: auto; margin-right: auto; width: 400px;}
In most legacy browsers, a table’s width is by default determined by its content. In CSS-conformant browsers, the complete width of any element (including tables) defaults to the full width of its parent element’s content area. As browser become more conformant, authors will need to be aware of the potential impact on their designs.

If background and color should always be set together, why do they exist as separate properties?
There are several reasons for this. First, style sheets become more legible — both for humans and machines. The background property is already the most complex property in CSS1 and combining it with color would make it even more complex. Second, color inherits, but background doesn’t and this would be a source of confusion.

What is class?
Class is a group of 1) instances of the same element to which an unique style can be attached or 2) instances of different elements to which the same style can be attached.

1) The rule P {color: red} will display red text in all paragraphs. By classifying the selector P different style can be attached to each class allowing the display of some paragraphs in one style and some other paragraphs in another style.
2) A class can also be specified without associating a specific element to it and then attached to any element which is to be styled in accordance with it’s declaration. All elements to which a specific class is attached will have the same style.

To classify an element add a period to the selector followed by an unique name. The name can contain characters a-z, A-Z, digits 0-9, period, hyphen, escaped characters, Unicode characters 161-255, as well as any Unicode character as a numeric code, however, they cannot start with a dash or a digit. (Note: in HTML the value of the CLASS attribute can contain more characters). (Note: text between /* and */ are my comments).

CSS
P.name1 {color: red} /* one class of P selector */
P.name2 {color: blue} /* another class of P selector */
.name3 {color: green} /* can be attached to any element */

HTML
<P class=name1>This paragraph will be red</P>
<P class=name2>This paragraph will be blue</P>
<P class=name3>This paragraph will be green</P>
<LI class=name3>This list item will be green</LI>

It is a good practice to name classes according to their function than their appearance; e.g. P.fotnote and not P.green. In CSS1 only one class can be attached to a selector. CSS2 allows attaching more classes, e.g.:
P.name1.name2.name3 {declaration} <P class=”name1 name2 name2″>This paragraph has three classes attached</P>

What is grouping ?
Grouping is gathering (1) into a comma separated list two or more selectors that share the same style or (2) into a semicolon separated list two or more declarations that are attached to the same selector (2).

1. The selectors LI, P with class name .first and class .footnote share the same style, e.g.:
LI {font-style: italic}
P.first {font-style: italic}
.footnote {font-style: italic}

To reduce the size of style sheets and also save some typing time they can all be grouped in one list.
LI, P.first, .footnote {font-style: italic}

2. The declarations {font-style: italic} and {color: red} can be attached to one selector, e.g.:
H2 {font-style: italic}
H2 {color: red}
and can also be grouped into one list:
H2 {font-style: italic; color: red}

What is external Style Sheet? How to link?
External Style Sheet is a template/document/file containing style information which can be linked with any number of HTML documents. This is a very convenient way of formatting the entire site as well as restyling it by editing just one file. The file is linked with HTML documents via the LINK element inside the HEAD element. Files containing style information must have extension .css, e.g. style.css. <HEAD> <LINK REL=STYLESHEET HREF=”style.css” TYPE=”text/css”> </HEAD>

Is CSS case sensitive?
Cascading Style Sheets (CSS) is not case sensitive. However, font families, URLs to images, and other direct references with the style sheet may be.
The trick is that if you write a document using an XML declaration and an XHTML doctype, then the CSS class names will be case sensitive for some browsers.

It is a good idea to avoid naming classes where the only difference is the case, for example:

div.myclass { …}
div.myClass { … }

If the DOCTYPE or XML declaration is ever removed from your pages, even by mistake, the last instance of the style will be used, regardless of case.

Three selectors: h1, .warning and #footer, what they do ?
An element points at a HTML-tag somewhere on your page. In the example above we want to style the <h1>-tag. Note that using an element like that affects all tags with that name, so using p { margin-left: 100px; } gives all <p>-tags a left-margin.
Using a class is just as simple. When writing .your_class you style all tags with a class with the name ?your_class?. In the example above we have .warning which will style e.g. <div class=”warning”> and <em class=”warning”>, that is, any element with the class warning. Classes are used when you want to style just a few of your tags in a way, perhaps you want some of your links red? Add a class to all those links.
You need one more building block: the id. This time you style an element with the attribute ?id? set to the id you have chosen. Ids work exactly like classes except for one thing; you can only have one id with a certain name in each of your HTML documents. In the example above we style <div id=”footer”>. If you look at the example it does make sense: a HTML document may contain several warnings but only one footer. Ids should be used when you want to style just one specific tag.
Using those three building blocks will take you far but when you get to more advanced layouts you might want to combine the building blocks into more advanced selectors. Just to give you two examples of what you can do: em.warning to style only those <em>-tags with the class .warning set. You can also use #footer a to style only the links that are nested inside the tag with id ?footer.
Each of the selectors has a set of declarations tied to them. Each declaration has a property, describing what we want to change and a value, what we should change it to. An example: a { color: Blue; font-size: 3em; }. You have the selector a there, so all links in your document will be styled. We have two declarations: color: Blue and font-size: 3em;. Lastly each declaration consists of two parts: the property color and the value Blue.
there is a LOT of things you can style and play with. Additionally (close to) all tags are equal in CSS, so you can set e.g. borders and colors of any element just like you could with a table if you used only HTML.

What are Style Sheets?
Style Sheets are templates, very similar to templates in desktop publishing applications, containing a collection of rules declared to various selectors (elements).

What is CSS rule ‘ruleset’?
There are two types of CSS rules: ruleset and at-rule. Ruleset identifies selector or selectors and declares style which is to be attached to that selector or selectors. For example P {text-indent: 10pt} is a CSS rule. CSS rulesets consist of two parts: selector, e.g. P and declaration, e.g. {text-indent: 10pt}.

P {text-indent: 10pt} – CSS rule (ruleset)
{text-indent: 10pt} – CSS declaration
text-indent – CSS property
10pt – CSS value

what is ‘Fixed’ Background?
There is the possibility to use the HTML tag bgproperties=”fixed”, but that is IE proprietary, and dependent upon the ‘background’ attribute (deprecated in HTML4).

With CSS, you can declare the background like:

BODY {
font-family : “Trebuchet MS”, Verdana, Arial, Helvetica, sans-serif;
background-image: url(images/yourimage.gif);
background-repeat: no-repeat; /*no-tiling background*/
background-position: center;
background-attachment: fixed;
background-color: #hexcolor;
color : #hexcolor;
margin: 10px;
}

that shows a background-image in the center of the <BODY> element, non-scrolling and non-repeating – in IE or NN6. NN 4.xx gets the non-repeat-part right, but stuffs the picture in the upper left corner and scrolls …

What is embedded style? How to link?
Embedded style is the style attached to one specific document. The style information is specified as a content of the STYLE element inside the HEAD element and will apply to the entire document.

<HEAD>
<STYLE TYPE=”text/css”>
<!–
P {text-indent: 10pt}
–>
</STYLE>
</HEAD>

Note: The styling rules are written as a HTML comment, that is, between <!– and –> to hide the content in browsers without CSS support which would otherwise be displayed.

What is ID selector?
ID selector is an individually identified (named) selector to which a specific style is declared. Using the ID attribute the declared style can then be associated with one and only one HTML element per document as to differentiate it from all other elements. ID selectors are created by a character # followed by the selector’s name. The name can contain characters a-z, A-Z, digits 0-9, period, hyphen, escaped characters, Unicode characters 161-255, as well as any Unicode character as a numeric code, however, they cannot start with a dash or a digit.

#abc123 {color: red; background: black}

<P ID=abc123>This and only this element can be identified as abc123 </P>

What is contextual selector?
Contextual selector is a selector that addresses specific occurrence of an element. It is a string of individual selectors separated by white space, a search pattern, where only the last element in the pattern is addressed providing it matches the specified context.

TD P CODE {color: red}

The element CODE will be displayed in red but only if it occurs in the context of the element P which must occur in the context of the element TD.

TD P CODE, H1 EM {color: red}

The element CODE will be displayed in red as described above AND the element EM will also be red but only if it occurs in the context of H1

P .footnote {color: red}

Any element with CLASS footnote will be red but only if it occurs in the context of P

P .footnote [lang]{color: red}

Any element with attribute LANG will be red but only if it is classed as “footnote” and occurs in the context of P

How do I have a background image that isn’t tiled?
Specify the background-repeat property as no-repeat. You can also use the background property as a shortcut for specifying multiple background-* properties at once. Here’s an example:

BODY {background: #FFF url(watermark.jpg) no-repeat;}

What does \ABCD (and \ABCDE) mean?
CSS allows Unicode characters to be entered by number. For example, if a CLASS value in some Russian document contains Cyrillic letters EL PE (Unicode numbers 041B and 041F) and you want to write a style rule for that class, you can put that letter into the style sheet by writing:

.41B41F {font-style: italic;}
This works on all keyboards, so you don’t need a Cyrillic keyboard to write CLASS names in Russian or another language that uses that script.

The digits and letters after the backslash (\) are a hexadecimal number. Hexadecimal numbers are made from ordinary digits and the letters A to F (or a to f). Unicode numbers consist of four such digits.

If the number starts with a 0, you may omit it. The above could also be written as:

.\41B\41F {font-style: italic;}
But be careful if the next letter after the three digits is also a digit or a letter a to f! This is OK: .\41B-\41F, since the dash (-) cannot be mistaken for a hexadecimal digit, but .\41B9\41F is only two letters, not three.

Four digits is the maximum, however, so if you write:
.41B941F {font-style: italic;}

Why do style sheets exist?
SGML (of which HTML is a derivative) was meant to be a device-independent method for conveying a document’s structural and semantic content (its meaning.) It was never meant to convey physical formatting information. HTML has crossed this line and now contains many elements and attributes which specify visual style and formatting information. One of the main reasons for style sheets is to stop the creation of new HTML physical formatting constructs and once again separate style information from document content.

What are the advantages/disadvantages of the various style methods?
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

Disadvantages

* This method can not control styles for multiple documents at once

Inline Styles
Advantages

* Useful for small quantities of style definitions
* Can override other style specification methods at the local level so only exceptions need to be listed in conjunction with other style methods

Disadvantages

* Does not distance style information from content (a main goal of SGML/HTML)
* Can not control styles for multiple documents at once
* Author can not create or control classes of elements to control multiple element types within the document
* Selector grouping methods can not be used to create complex element addressing scenarios

What is inline style? How to link?
Inline style is the style attached to one specific element. The style is specified directly in the start tag as a value of the STYLE attribute and will apply exclusively to this specific element occurrence.

<P STYLE=”text-indent: 10pt”>Indented paragraph</P>

What is imported Style Sheet? How to link?
Imported Style Sheet is a sheet that can be imported to (combined with) another sheet. This allows creating one main sheet containing declarations that apply to the whole site and partial sheets containing declarations that apply to specific elements (or documents) that may require additional styling. By importing partial sheets to the main sheet a number of sources can be combined into one.
To import a style sheet or style sheets include the @import notation or notations in the STYLE element. The @import notations must come before any other declaration. If more than one sheet is imported they will cascade in order they are imported – the last imported sheet will override the next last; the next last will override the second last, and so on. If the imported style is in conflict with the rules declared in the main sheet then it will be overridden.

<LINK REL=STYLESHEET HREF=”main.css” TYPE=”text/css”>
<STYLE TYPE=”text=css”>
<!–
@import url(http://www.and.so.on.partial1.css);
@import url(http://www.and.so.on.partial2.css);
…. other statements
–>
</STYLE>

What is a Style Sheet?
Style sheets are the way that standards-compliant Web designers define the layout, look-and-feel, and design of their pages. They are called Cascading Style Sheets or CSS. With style sheets, a designer can define many aspects of a Web page:

* fonts
* colors
* layout
* positioning
* imagery
* accessibility

Style sheets give you a lot of power to define how your pages will look. And another great thing about them is that style sheets make it really easy to update your pages when you want to make a new design. Simply load in a new style sheet onto your pages and you’re done.

What is alternate Style Sheet? How to link?
Alternate Style Sheet is a sheet defining an alternate style to be used in place of style(s) declared as persistent and/or preferred .
Persistent style is a default style that applies when style sheets are enabled but can disabled in favor of an alternate style, e.g.:

<LINK REL=Stylesheet HREF=”style.css” TYPE=”text/css”>

Preferred style is a default style that applies automatically and is declared by setting the TITLE attribute to the LINK element. There can only be one preferred style, e.g.:

<LINK REL=Stylesheet HREF=”style2.css” TYPE=”text/css” TITLE=”appropriate style description”>

Alternate style gives an user the choice of selecting an alternative style – a very convenient way of specifying a media dependent style. Note: Each group of alternate styles must have unique TITLE, e.g.:

<LINK REL=”Alternate Stylesheet” HREF=”style3.css” TYPE=”text/css” TITLE=”appropriate style description” MEDIA=screen>
<LINK REL=”Alternate Stylesheet” HREF=”style4.css” TYPE=”text/css” TITLE=”appropriate style description” MEDIA=print>

Alternate style sheet are not yet supported.

How can you set a minimum width for IE?

To set a minimum width, the CSS property is ‘min-width’. This can be very useful and works well in good browsers. IE doesn’t understand ‘min-width’. However, it has a proprietary property called ‘expression’ which allows us to feed it javascript via a stylesheet. Below is how to set a (780px) minimum width for IE…

<!–[if gte IE 5]> <style type=”text/css”>
body {
width:expression(documentElement.clientWidth < 780 ? (documentElement.clientWidth == 0 ? (body.clientWidth < 780 ? “780px” : “auto”) : “780px”) : “auto” );
}
</style>
<![endif]–>

As the property is non-standard, it won’t validate with the W3C validator, so if we put it in the head like this (above) – in an IE conditional comment – the validator will ignore it and the page will get a clean bill of health.

Which browsers support CSS?
It depends on your definition of “support.” If you are interested in those browsers which makes some attempt at supporting CSS, no matter how partial or bug-ridden, then the list is:

* Internet Explorer 3.0 and above
* Navigator 4.0 and above
* Opera 3.6 and above
* Konqueror
* Arena
* Emacs-w3
* Amaya
* Lexicon
* XPublish by Media Design in?Progress

If instead you’re interested in those browsers which are known to do a credible job of bug-free and mostly complete support for CSS1, then the list narrows somewhat dramatically:

* Internet Explorer 5.0 for Macintosh and above
* Internet Explorer 5.5 for Windows and above
* Netscape Navigator 6.0 and above
* Opera 4.0 and above

While none of these browser can be claimed to have a perfect implementation of CSS1, they are all quite good and can be relied upon to operate in a consistent fashion for most of CSS1.

How do I place text over an image?
To place text or image over an image you use the position property. The below exemple is supported by IE 4.0. All you have to do is adapt the units to your need.

<div style=”position: relative; width: 200px; height: 100px”>
<div style=”position: absolute; top: 0; left: 0; width: 200px”>
<image>
</div>
<div style=”position: absolute; top: 20%; left: 20%; width: 200px”>
Text that nicely wraps
</div>
</div>

what CSS is, why not start coding?
CSS is sort of like scripting language made for the web. In contrary with HTML, DHTML, JavaScript, VBScript and many others. CSS is strictly for formatting your web-page and now many new browser support it. (NOTE: Older browser do not support CSS, so please check your browser version and make sure whether it supports it or not. You may have to update your current Browser.)

The way the code goes into your Web-page is through a variety of ways. The way CSS works is that is the code is set between the<head></head> tags. You can put the CSS code after </title> which is what most people do. Now, here are the following ways of making your webpage with CSS enabled features:

1.) Writing your CSS code within your HTML source code. This is how it would look like:

<html><head><title>My First CSS!</title>
<!– Now begin the CSS coding! –>
<STYLE TYPE = “text/css”>
<!–
body {
background-color: #eeeee;
}
p {
text-align: left;
color: black;
font: Verdana;
font-size: 80%;
}
a {
text-decoration: none;
color: black;
font-weight: bold;
}
a:hover {
text-decoration: underline;
color: red;
font-weight: bold;
}
–>
</STYLE>
<!– End CSS code –>
</head><body></body></html>

2.) Linking to your CSS file. This tells the webpage to find the .css file and use it as the CSS code. Here is the code that would allow you to do:

<html><head><title>CSS</title>
<link href=”style.css” rel=”stylesheet” type=”text/css” />
</head><body /></html>

As you can see from the code above, the <link> tag is pretty helpful. What it does is that it links to the style.css file which has all the css code. Just like embedding an image throught he <img> tag.

Now to explain a bit from the first example. CSS code isn’t very hard to understand.Take for example the body { ..} part. What it does is that it formats how the <body> tag in HTML would work. That is a very simple way of formatting the body tag with the CSS. To help you understand better, here is a simple syntax for CSS:

selector { property1: value1; property2: value2;}

The “selector” sort of relates to the html tags used for outputting etc…

We all know that <a> is a tag used for links. You will see in the example about a:hover and a itself. <br>What a does it just sets the characteristics of the format. You can set how you want a link to appear using the font size, weight etc..

Then comes the “a:hover”. What does is also pretty self explanatory. It acts on when a person moves the mouse cursor over the links.

ADVANCED CSS FEATURES:

CSS can be even used to change the appearance of the scroll bar at your right side. Unfortunately, that only works with IE. You have to be using IE in order for this to work. Here is how to change some appearances of your scroll bar:

The CSS statements for doing this are:
1) scrollbar-3dlight-color
2)scrollbar-arrow-color
3) scrollbar-base-color
4) scrollbar-dark shadow-color
5) scrollbar-face-color
6) scrollbar-highlight-color
7) scrollbar-shadow-color
8) scrollbar-track-color

<style type=”text/css”>
<!–
BODY {
scrollbar-arrow-color: green;
scrollbar-face-color: #FFFFFF;
scrollbar-track-color: rgb(12,35,244);
}
// –>
</style>

How to customize your text boxes.
Here is the code on how to do it:

<style type=”text/css”>
<!–
BODY {
scrollbar-arrow-color: green;
scrollbar-face-color: #FFFFFF;
scrollbar-track-color: rgb(12,35,244);
}
TEXTAREA {
scrollbar-arrow-color: green;
scrollbar-face-color: #FFFFFF;
scrollbar-track-color: rgb(12,35,244);
}
// –>
</style>

That above code, has some similarities. The textbox area is treated with the same function statements as for the scrollbar. The scrollbar statements goes in the BODY selector.

Why does my content shift to the left on some pages (in FF)?
That’ll be the pages with more content? The ones that have a vertical scrollbar? If you look in IE there’s probably a white space on the right where there would be a scrollbar if there were enough content to require one. In Firefox, the scrollbar appears when it’s needed and the viewport becomes about 20px smaller, so the content seems to shift to the left when you move from a page with little content to one with lots of content. It’s not a bug or something that needs to be fixed, but it does confuse and irritate some developers.

If, for some reason, you’d like Firefox to always have scrollbars – whether they’re needed or not – you can do this :

CSS html {
height:100.1%;
}

How do I combine multiple sheets into one?
To combine multiple/partial style sheets into one set the TITLE attribute taking one and the same value to the LINK element. The combined style will apply as a preferred style, e.g.:

<LINK REL=Stylesheet HREF=”default.css” TITLE=”combined”>
<LINK REL=Stylesheet HREF=”fonts.css” TITLE=”combined”>
<LINK REL=Stylesheet HREF=”tables.css” TITLE=”combined”>

What is attribute selector?
Attribute selector is a selector defined by 1) the attribute set to element(s), 2) the attribute and value(s), 3) the attribute and value parts:

1a) A[title] {text-decoration: underline}
All A elements containing the TITLE attribute will be underlined

1b) A[class=name] {text-decoration: underline}
The A elements classed as ‘name’ will be underlined

2) A[title=”attribute element”] {text-decoration: underline}
The A elements containing the TITLE attribute with a value that is an exact match of the specified value, which in this example is ‘attribute element’, will be underlined

3) A[title~=”attribute”] {text-decoration: underline}
The A elements containing the TITLE attribute with a value containing the specified word, which in this example is ‘attribute’, will be underlined

What is parent-child selector?
Parent-child selector is a selector representing the direct descendent of a parent element. Parent-child selectors are created by listing two or more tilde (~) separated selectors.

BODY ~ P {background: red; color: white}
The P element will be declared the specified style only if it directly descends from the BODY element:
<BODY> <P>Red and white paragraph </P> </BODY>

BODY ~ P ~ EM {background: red; color: white}
The EM element will be declared the specified style only if it directly descends from the P element which in its turn directly descends from the BODY element:

< <P> <EM>Red and white EM </EM> </P> </BODY>

How can I specify background images?
With CSS, you can suggest a background image (and a background color, for those not using your image) with the background property. Here is an example:

body {
background: white url(example.gif) ;
color: black ;
}
If you specify a background image, you should also specify text, link, and background colors since the reader’s default colors may not provide adequate contrast against your background image. The background color may be used by those not using your background image. Authors should not rely on the specified background image since browsers allow their users to disable image loading or to override document-specified backgrounds.

How do I have a fixed (non-scrolling) background image?
With CSS, you can use the background-attachment property. The background attachment can be included in the shorthand background property, as in this example:

body {
background: white url(example.gif) fixed ;
color: black ;
}

Note that this CSS is supported by Internet Explorer, Mozilla, Firefox Opera, Safari, and other browsers. In contrast, Microsoft’s proprietary BGPROPERTIES attribute is supported only by Internet Explorer.

What are inline, block, parent, children, replaced and floating elements?
Inline
elements which do not have line breaks. Can occur in block elements or other inline elements, cannot contain block elements.
Inline elements in HTML 3.2; EM, STRONG, DFN, CODE, SAMP, KBD, VAR, CITE, TT, I, B, U, STRIKE, BIG, SMALL, SUB, SUP, A, IMG, APPLET, FONT, BASEFONT, BR, SCRIPT, MAP, INPUT, SELECT, TEXTAREA.

Inline elements in HTML 4.0; EM, STRONG, DFN, CODE, SAMP, KBD, VAR, CITE, ABBR, ACRONYM, TT, I, B, BIG, SMALL, SUB, SUP, A, IMG, OBJECT, BR, SCRIPT, MAP, Q, SPAN, BDO, INPUT, SELECT, TEXTAREA, LABEL, BUTTON, (INS, DEL).

Inline elements in HTML 4.0 Transitional; EM, STRONG, DFN, CODE, SAMP, KBD, VAR, CITE, ABBR, ACRONYM, TT, I, B, U, S, STRIKE, BIG, SMALL, SUB, SUP, A, IMG, APPLET, OBJECT, FONT, BASEFONT, BR, SCRIPT, MAP, Q, SPAN, BDO, IFRAME, INPUT, SELECT, TEXTAREA, LABEL, BUTTON, (INS, DEL).

Block
elements which do have line breaks. May occur in other block elements, cannot occur in inline elements, may contain both block and inline elements.

Block elements in HTML 3.2; H1, H2, H3, H4, H5, H6, ADDRESS, P, DL, DT, DD, UL, OL, DIR, MENU, LI, DIV, CENTER, BLOCKQUOTE, PRE, HR, ISINDEX, TABLE, FORM.

Block elements in HTML 4.0; P, H1, H2, H3, H4, H5, H6, UL, OL, PRE, DL, DIV, NOSCRIPT, BLOCKQUOTE, FORM, HR, TABLE, FIELDSET, ADDRESS, (INS, DEL).

Block elements in HTML 4.0 Transitional; P, H1, H2, H3, H4, H5, H6, UL, OL, DIR, MENU, PRE, DL, DIV, CENTER, NOSCRIPT, NOFRAMES, BLOCKQUOTE, FORM, ISINDEX, HR, TABLE, FIELDSET, ADDRESS, (INS, DEL).

Parents and children
elements which either contain (parents) or are in the content of (children) other elements, e.g. <P>text<STRONG>text</STRONG>text</P>. P is a parent of STRONG. STRONG is a child of P. If not specified otherwise, children will inherit parent’s properties.
Replaced
elements which content is replaced. For example content of the IMG element is replaced with an image, content of the INPUT element is replace with a field.
Floating
elements which follow the flow of a parent – inline elements.

PHP interview questions & ANSWERS

Q:1 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?
A:1
When to use GET or  POST

The HTML 2.0 specification says, in section Form
Submission (and the HTML 4.0 specification repeats this with minor
stylistic changes):

–>If the processing of a form is idempotent
(i.e. it has no lasting observable effect on the state of the
world), then the form method should be GET. Many database searches
have no visible side-effects and make ideal applications of query
forms.

–>If the service associated with the processing of a form has side
effects (for example, modification of a database or subscription to
a service), the method should be POST.
How the form data is transmitted?

quotation from the HTML 4.0 specification

–> If the method is “get” – -, the user agent
takes the value of action, appends a ? to it, then appends the form
data set, encoded using the application/x-www-form-urlencoded
content type. The user agent then traverses the link to this URI. In
this scenario, form data are restricted to ASCII codes.
–> If the method is “post” –, the user agent conducts an HTTP post
transaction using the value of the action attribute and a message
created according to the content type specified by the enctype
attribute.
Quote from CGI FAQ

Firstly, the the HTTP protocol specifies
differing usages for the two methods. GET requests should always be
idempotent on the server. This means that whereas one GET request
might (rarely) change some state on the Server, two or more
identical requests will have no further effect.

This is a theoretical point which is also good
advice in practice. If a user hits “reload” on his/her browser, an
identical request will be sent to the server, potentially resulting
in two identical database or
guestbook entries, counter increments, etc. Browsers may reload a
GET URL automatically, particularly if cacheing is disabled (as is
usually the case with CGI output), but will typically prompt the
user before
re-submitting a POST request. This means you’re far less likely to
get inadvertently-repeated entries from POST.

GET is (in theory) the preferred method for
idempotent operations, such as querying a database, though it
matters little if you’re using a form. There is a further practical
constraint that many systems have built-in limits to the length of a
GET request they can handle: when the total size of a request (URL+params)
approaches or exceeds 1Kb, you are well-advised to use POST in any
case.

I would prefer POST when I don’t want the status to
be change when user resubmits. And GET
when it does not matter.

Q:2 Who is the father of PHP and explain the changes in PHP versions?
A:2 Rasmus Lerdorf is known as the father of PHP.PHP/FI 2.0 is an early and no longer supported version of PHP. PHP 3
is the successor to PHP/FI 2.0 and is a lot nicer. PHP 4 is the current
generation of PHP, which uses the
Zend engine
under the
hood. PHP 5 uses
Zend engine 2 which,
among other things, offers many additionalOOP features

Q:3 How can we submit a form without a submit button?
A:3 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).

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

A:4 You can do it by 4 Ways1. mysql_fetch_row.
2. mysql_fetch_array
3. mysql_fetch_object
4. mysql_fetch_assoc

Q:5 What is the difference between mysql_fetch_object and
mysql_fetch_array?

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

Q:6 What is the difference between $message and $$message?
A:6 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.

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

A:7 preg_match(”/^http:\/\/.+@(.+)$/”,’http://info@abc.com’,$found);
echo $found[1];

Q:8 How can we create a database using PHP and MySQL?
A:8 We can create MySQL database with the use of
mysql_create_db(“Database Name”)

Q:9 What are the differences between require and include,
include_once and require_once?
A:9

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 handle
failure. include() produces a
Warning while require() results
in a Fatal Error. In other words, use
require() if you want a missing
file 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 difference
being 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 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.

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.

Q:10 Can we use include (”abc.PHP”) two times in a PHP page “makeit.PHP”?
A:10 Yes we can use include() more than one time in any page though it is
not a very good practice.

Q:11 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)) ?

A:11 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 and as a result if
we do not specify the table name explicitly it will be assigned to the
default engine.

Q:12 Functions in IMAP, POP3 AND LDAP?
A:12 These functions enable you to operate with the IMAP protocol, as well as the NNTPPOP3 and local mailbox access methods  You can find these specific information in PHP Manual.

Q:13 How can I execute a PHP script using command line?
A:13 As of version 4.3.0, PHP supports a new SAPI type (Server
Application Programming Interface) named CLI which means Command Line
Interface. 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.

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

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

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

A:15 We can find the detail documentation about different paypal
integration process at the following site

PayPal PHP
SDK : http://www.paypaldev.org

Q:16 What is meant by nl2br()?
A:16 Inserts HTML line breaks (
) before all newlines in a string
string nl2br (string); Returns string with ” inserted before all
newlines. For example: echo nl2br(”god bless\n you”) will output “god
bless
you” to your browser.

Q:17 Draw the architecture of Zend engine?
A:17 The Zend Engine is the internal compiler and runtime engine used by
PHP4. Developed by Zeev Suraski and Andi Gutmans, the Zend Engine is an
abbreviation of their names. In the early days of PHP4, it worked as
follows:
The PHP script was loaded by the Zend Engine and compiled into Zend
opcode. Opcodes, short for operation codes, are low level binary
instructions. Then the opcode was executed and the HTML generated sent
to the client. The opcode was flushed from memory after execution.Today, there are a multitude of products and techniques to help you
speed up this process. In the following diagram, we show the how modern
PHP scripts work; all the shaded boxes are optional.
PHP Scripts are loaded into memory and compiled into Zend opcodes.

Q:18 What are the current versions of apache, PHP, and MySQL?
A:18 As of February, 2007 the current versions arePHP: php5.2.1
MySQL: MySQL 5.2
Apache: Apache 2.2.4Note: visit http://www.php.net,

http://dev.mysql.com/downloads/mysql/,
http://www.apache.org to get current
versions.

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

A:19 All of those are open source resource. Security of Linux is very
very more than windows. Apache is a better server that IIS both in
functionality and security. MySQL is world most popular open source
database. PHP is more faster that asp or any other scripting language.

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

A:20 AES_ENCRYPT () and AES_DECRYPT ()

Q:21 How can we encrypt the username and password using PHP?
A:21 The functions in this section perform encryption and decryption, and
compression and uncompression:

encryption decryption
AES_ENCRYT() AES_DECRYPT()
ENCODE() DECODE()
DES_ENCRYPT() DES_DECRYPT()
ENCRYPT() Not available
MD5() Not available
OLD_PASSWORD() Not available
PASSWORD() Not available
SHA() or SHA1() Not available
Not available UNCOMPRESSED_LENGTH()

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

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

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

A:23 Traditional programming has the following characteristics:Functions are written sequentially, so that a change in programming can
affect any code that follows it.
If a function is used multiple times in a system (i.e., a piece of code
that manages the date), it is often simply cut and pasted into each
program (i.e., a change log, order function, fulfillment system, etc).
If a date change is needed (i.e., Y2K when the code needed to be changed
to handle four numerical digits instead of two), all these pieces of
code must be found, modified, and tested.
Code (sequences of computer instructions) and data (information on which
the instructions operates on) are kept separate. Multiple sets of code
can access and modify one set of data. One set of code may rely on data
in multiple places. Multiple sets of code and data are required to work
together. Changes made to any of the code sets and data sets can cause
problems through out the system.Object-Oriented programming takes a radically different approach:Code and data are merged into one indivisible item – an object (the
term “component” has also been used to describe an object.) An object is
an abstraction of a set of real-world things (for example, an object may
be created around “date”) The object would contain all information and
functionality for that thing (A date
object it may contain labels like January, February, Tuesday, Wednesday.
It may contain functionality that manages leap years, determines if it
is a business day or a holiday, etc., See Fig. 1). Ideally, information
about a particular thing should reside in only one place in a system.
The information within an object is encapsulated (or hidden) from the
rest of the system.
A system is composed of multiple objects (i.e., date function, reports,
order processing, etc., See Fig 2). When one object needs information
from another object, a request is sent asking for specific information.
(for example, a report object may need to know what today’s date is and
will send a request to the date object) These requests are called
messages and each object has an interface that manages messages.
OO programming languages include features such as “class”, “instance”,
“inheritance”, and “polymorphism” that increase the power and
flexibility of an object.

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

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

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

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

Q:27 What is the functionality of the function strstr and stristr?
A:27 strstr:

Returns part of haystack
string from the first occurrence of
needle to the end of
haystack.If needle is not found,
returns FALSE.

If needle is not a
string, it is converted to an integer and applied as the
ordinal value of a character.

This function is case-sensitive. For
case-insensitive searches, use
stristr().

Q:28 What are the differences between PHP 3 and PHP 4 and PHP 5?
A:28 Please read the release notes at
http://www.php.net.

Q:29 How can we convert asp pages to PHP pages?
A:29 there are lots of tools available for asp to PHP conversion. you can
search Google for that. the best one is available athttp://asp2php.naken.cc./

Q:30 What is the functionality of the function htmlentities?
A:30 Convert all applicable characters to HTML entities
This function is identical to htmlspecialchars() in all ways, except
with htmlentities(), all characters which have HTML character entity
equivalents are translated into these entities.

Q:31 How can we get second of the current time using date function?
A:31 $second = date(”s”);

Q:32 How can we convert the time zones using PHP?
A:32 By using date_default_timezone_get and
date_default_timezone_set function on PHP 5.1.0

// Discover what 8am in Tokyo relates to on the East Coast of the US

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

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

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

// Output the date in a standard format (RFC1123), this will print:
// Fri, 31 Dec 1999 18:00:00 EST
echo ‘

‘, date(DATE_RFC1123, $stamp) ,’

‘;?>

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

urldecode decodes any %##
encoding in the given string.

Q:34 What is the difference between the functions unlink and unset?
A:34 unlink() deletes the given file from the file system.
unset() makes a variable undefined.

Q:35 How can we register the variables into a session?
A:35 $_SESSION[’name’] = “Mizan”;

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

A:36 To know the Image type use exif_imagetype () function
To know the Image size use getimagesize () function
To know the image width use imagesx () function
To know the image height use imagesy() function t

Q:37 How can we get the browser properties using PHP?
A:37 By using
$_SERVER[‘HTTP_USER_AGENT’]
variable.

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

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

Q:39 How can we increase the execution time of a PHP script?
A:39 by changing the following setup at php.inimax_execution_time = 30
; Maximum execution time of each script, in seconds

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

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

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

A:41

* first of all instead of using select * from table1, use select
column1, column2, column3.. from table1
* Look for the opportunity to introduce index in the table you are
querying.
* use limit keyword if you are looking for any specific number of
rows from the result set.

Q:42 How many ways can we get the value of current session id?
A:42 session_id() returns the session id for the current session.

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

A:43 session_unregister — Unregister a global variable from the current
session
session_unset — Free all session variables

Q:44 How can we destroy the cookie?
A:44 Set the cookie in past.

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

A:45

* GET/QueryString
* POST

Q:46 What is the difference between ereg_replace() and eregi_replace()?
A:46 eregi_replace() function is identical to ereg_replace() except that
this ignores case distinction when matching alphabetic
characters.eregi_replace() function is identical to ereg_replace()
except that this ignores case distinction when matching alphabetic
characters.

Q:47 What are the different functions in sorting an array?
A:47 Sort(), arsort(),
asort(), ksort(),
natsort(), natcasesort(),
rsort(), usort(),
array_multisort(), and
uksort().

Q:48 How can we know the count/number of elements of an array?
A:48 2 ways
a) sizeof($urarray) This function is an alias of count()
b) count($urarray)

Q:49 What is the PHP predefined variable that tells the What types of
images that PHP supports?

A:49 Though i am not sure if this is wrong or not, With the exif
extension you are able to work with image meta data.

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

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

Q:51 List out some tools through which we can draw E-R diagrams for
mysql.

A:51 Case Studio
Smart Draw

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

A:52 we can always fetch from one database and rewrite to another. here
is a nice solution of it.$db1 = mysql_connect(”host”,”user”,”pwd”)
mysql_select_db(”db1″, $db1);
$res1 = mysql_query(”query”,$db1);$db2 = mysql_connect(”host”,”user”,”pwd”)
mysql_select_db(”db2″, $db2);
$res2 = mysql_query(”query”,$db2);At this point you can only fetch records from you previous ResultSet,
i.e $res1 – But you cannot execute new query in $db1, even if you
supply the link as because the link was overwritten by the new db.so at this point the following script will fail
$res3 = mysql_query(”query”,$db1); //this will failSo how to solve that?

take a look below.
$db1 = mysql_connect(”host”,”user”,”pwd”)
mysql_select_db(”db1″, $db1);
$res1 = mysql_query(”query”,$db1);

$db2 = mysql_connect(”host”,”user”,”pwd”, true)
mysql_select_db(”db2″, $db2);
$res2 = mysql_query(”query”,$db2);

So mysql_connect has another optional boolean parameter which
indicates whether a link will be created or not. as we connect to the
$db2 with this optional parameter set to ‘true’, so both link will
remain live.

now the following query will execute successfully.
$res3 = mysql_query(”query”,$db1);

Thanks goes to Hasan and Hasin for this solution.

Q:53 List out the predefined classes in PHP?
A:53 Directory
stdClass
__PHP_Incomplete_Class
exception
php_user_filter

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

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

Q:55 What are the difference between abstract class and interface?
A:55 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.

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

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

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

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

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

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

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

Q:60 How many values can the SET function of MySQL take?
A:60 MySQL set can take zero or more values but at the maximum it can
take 64 values

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

A:61 describe Table-Name;

Q:62 How many tables will create when we create table, what are they?
A:62 The ‘.frm’ file stores the table definition.
The data file has a ‘.MYD’ (MYData) extension.
The index file has a ‘.MYI’ (MYIndex) extension,

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

A:63 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,

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

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

Q:66 Explain Normalization concept?
A:66 The normalization process involves getting our data to conform to
three progressive normal forms, and a higher level of normalization
cannot be achieved until the previous levels have been achieved (there
are actually five normal forms, but the last two are mainly academic and
will not be discussed).First Normal FormThe First Normal Form (or 1NF) involves removal of redundant data
from horizontal rows. We want to ensure that there is no duplication of
data in a given row, and that every column stores the least amount of
information possible (making the field atomic).Second Normal FormWhere the First Normal Form deals with redundancy of data across a
horizontal row, Second Normal Form (or 2NF) deals with redundancy of
data in vertical columns. As stated earlier, the normal forms are
progressive, so to achieve Second Normal Form, your tables must already
be in First Normal Form.Third Normal Form

I have a confession to make; I do not often use Third Normal Form. In
Third Normal Form we are looking for data in our tables that is not
fully dependant on the primary key, but dependant on another value in
the table

Q:67 How can we find the number of rows in a table using MySQL?
A:67 Use this for mysql
>SELECT COUNT(*) FROM table_name;

Q:68 How can we find the number of rows in a result set using PHP?
A:68 $result = mysql_query($sql, $db_link);
$num_rows = mysql_num_rows($result);
echo “$num_rows rows found”;

Q:69 How many ways we can we find the current date using MySQL?
A:69 SELECT CURDATE();
CURRENT_DATE() = CURDATE()
for time use
SELECT CURTIME();
CURRENT_TIME() = CURTIME()

Q:70 What are the advantages and disadvantages of Cascading Style
Sheets?

A:70 External Style SheetsAdvantagesCan control styles for multiple documents at once. Classes can be
created for use on multiple HTML element types in many documents.
Selector and grouping methods can be used to apply styles under complex
contextsDisadvantagesAn extra download is required to import style information for each
document The rendering of the document may be delayed until the external
style sheet is loaded Becomes slightly unwieldy for small quantities of
style definitionsEmbedded Style Sheets

Advantages

Classes can be created for use on multiple tag types in the document.
Selector and grouping methods can be used to apply styles under complex
contexts. No additional downloads necessary to receive style information

Disadvantages

This method can not control styles for multiple documents at once

Inline Styles

Advantages

Useful for small quantities of style definitions. Can override other
style specification methods at the local level so only exceptions need
to be listed in conjunction with other style methods

Disadvantages

Does not distance style information from content (a main goal of
SGML/HTML). Can not control styles for multiple documents at once.
Author can not create or control classes of elements to control multiple
element types within the document. Selector grouping methods can not be
used to create complex element addressing scenarios

Q:71 What type of inheritance that PHP supports?
A:71 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’.

Q:72 What is the difference between Primary Key and
Unique key?

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

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

Q:73 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 the last row 999 then What will happen in
the following conditions?

Condition1: Delete all the rows and insert another row then.
What is the starting value for this auto incremented field user_pri_id ,
Condition2: Delete the last row(having the field value 999) and
insert another row then. What is the value for this auto incremented
field user_pri_id
A:73 In both cases let the value for auto increment field be n then next
row will have value n+1 i.e. 1000

Q:74 What are the advantages/disadvantages of MySQL and PHP?
A:74 Both of them are open source software (so free of cost), support
cross platform. php is faster then ASP and JSP.

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

Q:76 What is the difference between char and varchar data types?
A:76 Set char to occupy n bytes and it will take n bytes even if u r
storing a value of n-m bytes
Set varchar to occupy n bytes and it will take only the required space
and will not use the n bytes
eg. name char(15) will waste 10 bytes if we store ‘mizan’, if each char
takes a byte
eg. name varchar(15) will just use 5 bytes if we store ‘mizan’, if each
char takes a byte. rest 10 bytes will be free.

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

Q:78 How can I load data from a text file into a table?
A:78 you can use LOAD DATA INFILE file_name; syntax to load data
from a text file. but you have to make sure thata) data is delimited
b) columns and data matched correctly

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

A:79 SELECT DATEDIFF(’2007-03-07′,’2005-01-01′);

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

A:80 $date1 = date(’Y-m-d’);
$date2 = ‘2006-08-15′;
$days = (strtotime($date1) – strtotime($date2)) / (60 * 60 * 24);

 

Q:81 What is ‘float’ property in CSS?

A:81 The float property sets where an image or a text will appear in another element.

    

Q:82 What is descendant structure in CSS?

A:82 Descendant selectors are used to select elements that are descendants of another element in the document tree.For example, you may wish to target a specific <em> element on the page, but not all <em> elements. A sample document could contain the following code: <body>

<h1>Heading <em>here</em> </h1>

<p>Lorem ipsum dolor <em>sit</em> amet.</p>

</body> The document tree diagram (with the <em> element to be targeted) would be:Document tree showing descendant selectorsIf you use a type selector like the example below, you will select all <em> elements on the page:

 

em {color: blue; } However, if you use a descendant selector, you can refine the <em> elements that you select. The rule below will only select <em> elements that are descendants of <p> elements. If this rule is applied, the <em> element within the <h1> will not be colored blue.

 

p em {color: blue; } You can also jump levels in the document tree structure to select descendants. For example, the following code:

 

<body>

<p>Lorem ipsum dolor <em>sit</em> amet.</p>

<ul>

<li>item 1</li>

<li>item 2</li>

<li><em>item 3</em></li>

</ul>

</body> The document tree (with a third-level <em> element highlighted) would be:

 

Document tree showing descendant selectors

 

Using the following rule you can isolate any <em> element inside a <ul> element, without having to describe the <li> element. If this rule is applied, any <em> element within a <ul> element will be colored blue. However, the <em> element within the <p> will not be colored blue:

 

ul em {color: blue; } Descendant selectors are well supported across standards-compliant browsers.

    

Q:83 What is Child Descendant structure in CSS?

A:83

Child selectors

 

A child selector is used to select an element that is a direct child of another element (parent). Child selectors will not select all descendants, only direct children.

 

For example, you may wish to target an <em> that is a direct child of a <div>, but not other <em> elements that are descendants of the <div>. A sample document could contain the following code:

 

<body>

<h1>Heading <em>text</em></h1>

<div>

This is some <em>text</em>

<p>This is a paragraph of <em>text</em></p>

</div>

</body>

The document tree (highlighting the <em> that is a child of the <div>) would be:

 

Document tree showing child selector

 

Using the following rule you can target any <em> element that is a child of the <div>. Other <em> elements that are descendants but not direct children of the <div> will not be targeted.

 

div > em { color: blue; }

 

OR

 

div>em { color: blue; }

Child selectors are not supported by Windows Internet Explorer 5, 5.5 and 6, but are supported by most other standards-compliant browsers.

    

Q:84 How to create a class in JavaScript?

A:84 Classes can seem off-putting at first, but once you see the point of them, their use can be invaluable.We have already met objects. A computer object is a representation of a real object. For an estate agent the object may be a house, including information about the number of rooms and the price.An estate agent may have a lot of houses available. These houses all have different characteristics, and as objects they all go through the same processes. They are viewed, surveyed and bought, and so on.A full estate agent program would be difficult to demonstrate here, but we can introduce the use of classes.In this example, we have the house class. The house class produces house objects, all with object properties, such as number of rooms and price, and all having access to the same methods, such as sold and bought.

 

So a class can create objects with a group of properties and methods.

 

JavaScript doesn’t have a keyword specific to class, so we must go back to basics and develop classes in a different way. This isn’t very difficult.

Class Properties

 

Let us examine a very small estate agent program.

 

<HTML>

<HEAD>

<TITLE>Estate Agent</TITLE>

<SCRIPT>

function House(rooms,price,garage) {

this.rooms=rooms;

this.price=price;

this.garage=garage;

}

house1=new House(4,100000,false);

house2=new House(5,200000,true);

with (house1) document.write(’House 1 has ‘+rooms+’ rooms, ‘+(garage?’a’:’no’)+’ garage, and costs £’+price+’<BR>’);

with (house2) document.write(’House 2 has ‘+rooms+’ rooms, ‘+(garage?’a’:’no’)+’ garage, and costs £’+price+’<BR>’);

</SCRIPT>

</HEAD>

</HTML>

 

We define a House function that takes three parameters, rooms, price and garage. The function uses the this keyword to create an object.

 

When we call the House function, we assign the result to our variable, which becomes an object.

 

So, identical code would be:

 

house1=new Object();

house1.rooms=4;

house1.price=100000;

house1.garage=false;

 

We would have to type this in for all houses, which would be very tedious and is why we use the class structure instead.

 

When we display the details for a house, I have introduced the ternary operator, ‘?:’. The ternary operator is a compacted version of:

 

if (garage) str=’a’; else str=’no’;

 

(garage?’a’:’no’) means if garage is true, return ‘a’ else return ‘no’. Using the ternary operator removes a line of code, and avoids having to create a new variable.

Class Methods

 

The House class we have so far defined only contains object properties. We could add a method to replace the document.write() action we used before. (See example)

 

<HTML>

<HEAD>

<TITLE>Estate Agent 2</TITLE>

<SCRIPT>

function House(name,rooms,price,garage) {

this.name=name;

this.rooms=rooms;

this.price=price;

this.garage=garage;

this.view=view;

}

function view() {

with (this) document.write(name+’ has ‘+rooms+’ rooms, ‘+(garage?’a’:’no’)+’ garage, and costs £’+price+’<BR>’);

}

house1=new House(’House 1′,4,100000,false);

house2=new House(’Big House’,5,200000,true);

house1.view();

house2.view();

</SCRIPT>

</HEAD>

</HTML>

 

Much better!

 

Note how we must add another property, name, so that we can identify the house in question. This offers more flexibility than re-using the variable name, and the variable name is inaccessible anyway, i.e. it is very difficult, if not impossible, to get the view() function to use the string ‘house1′.

    

Q:85 Are namespaces are there in JavaScript?

A:81 A namespace is a container and allows you to bundle up all your functionality using a unique name. In JavaScript, a namespace is really just an object that you’ve attached all further methods, properties and objects. But it is not always necessary to use namespace.

    

Q:86 What is JSON? What are the notations used in JSON?

A:86 JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

    

Q:87 How to get Query String in PHP for http request?

A:87 $_GET[] and $_REQUEST[]

    

Q:88 How to get the http Request in PHP?

A:88 When PHP is used on a Web server to handle a HTTP request, it converts information submitted in the HTTP request as predefined variables:

 

    * $_GET – Associate array of variables submitted with GET method.

    * $_POST – Associate array of variables submitted with POST method.

    * $_COOKIE – Associate array of variables submitted as cookies.

    * $_REQUEST – Associate array of variables from $_GET, $_POST, and $_COOKIE.

    * $_SERVER – Associate array of all information from the server and the HTTP request.

 

    

Q:89 How you provide security for PHP application?

A:89 There are many ways to accomplish the security tasks but the most common 7 ways are1. Validate Input. Never trust your user and always filter input before taking it to any operation.2. Provide access control.3. Session ID protection4. preventing Cross Site Scripting (XSS) flaws

 

5. SQL injection vulnerabilities.

 

6. Turning off error reporting and exposing to the site for hackers. Instead use log file to catch exceptions

 

7. Effective Data handling

    

Q:90 What is SQL Injection in PHP security?

A:90 SQL injection attacks are extremely simple to defend against, but many applications are still vulnerable. Consider the following SQL statement:

 

<?php

$sql = “INSERT

        INTO   users (reg_username,

                      reg_password,

                      reg_email)

        VALUES (‘{$_POST[‘reg_username’]}’,

                ‘$reg_password’,

                ‘{$_POST[‘reg_email’]}’)”;

?>

 

This query is constructed with $_POST, which should immediately look suspicious.

 

Assume that this query is creating a new account. The user provides a desired username and an email address. The registration application generates a temporary password and emails it to the user to verify the email address. Imagine that the user enters the following as a username:

 

bad_guy’, ‘mypass’, ”), (‘good_guy

 

This certainly doesn’t look like a valid username, but with no data filtering in place, the application can’t tell. If a valid email address is given (shiflett@php.net, for example), and 1234 is what the application generates for the password, the SQL statement becomes the following:

 

<?php

 

$sql = “INSERT

        INTO   users (reg_username,

                      reg_password,

                      reg_email)

        VALUES (‘bad_guy’, ‘mypass’, ”),

          (‘good_guy’,

                ‘1234’,

                ‘shiflett@php.net’)”; ?>

 

Rather than the intended action of creating a single account (good_guy) with a valid email address, the application has been tricked into creating two accounts, and the user supplied every detail of the bad_guy account.

 

While this particular example might not seem so harmful, it should be clear that worse things could happen once an attacker can make modifications to your SQL statements.

 

For example, depending on the database you are using, it might be possible to send multiple queries to the database server in a single call. Thus, a user can potentially terminate the existing query with a semicolon and follow this with a query of the user’s choosing.

 

MySQL, until recently, does not allow multiple queries, so this particular risk is mitigated. Newer versions of MySQL allow multiple queries, but the corresponding PHP extension (ext/mysqli) requires that you use a separate function if you want to send multiple queries (mysqli_multi_query() instead of mysqli_query()). Only allowing a single query is safer, because it limits what an attacker can potentially do.

 

Protecting against SQL injection is easy:

 

    * Filter your data.This cannot be overstressed. With good data filtering in place, most security concerns are mitigated, and some are practically eliminated.

    * Quote your data.If your database allows it (MySQL does), put single quotes around all values in your SQL statements, regardless of the data type.

    * Escape your data.Sometimes valid data can unintentionally interfere with the format of the SQL statement itself. Use mysql_escape_string() or an escaping function native to your particular database. If there isn’t a specific one, addslashes() is a good last resort.

 

    

Q:91 What is cross site Scripting?

A:91 To understand what Cross Site Scripting is, let’s see a usual situation, common to many sites. Let’s say we are taking some information passed in on a querystring (the string after the (?) character within a URL), with the purpose of displaying the content of a variable, for example, the visitor’s name:

 

http://www.yourdomain.com/welcomedir/welcomepage.php?name=John

As we can see in this simple querystring, we are passing the visitor’s name as a parameter in the URL, and then displaying it on our “welcomepage.php” page with the following PHP code:

 

<?php

 

echo ‘Welcome to our site ’ . stripslashes($_GET[‘name’]);

 

?>

The result of this snippet is shown below:

 

Welcome to our site John

This is pretty simple and straightforward. We’re displaying the content of the “name” variable, by using the $_GET superglobal PHP array, as we have done probably hundreds of times. Everything seems to be fine. Now, what’s wrong with this code? Nothing really. But let’s modify the querystring by replacing our visitor’s name passed in the URL:

 

http://www.yourdomain.com/welcomedir/

welcomepage.php?name=John

with something like this:

 

http://www.yourdomain.com/welcomedir/

welcomepage.php?name=

<script language=javascript>alert

(‘Hey, you are going to be hijacked!’);</script>

Do you remember the PHP code included in our “welcome.php” page? Yes, you’re correct. When we modify the querystring, the following code is executed:

 

<?php

 

echo ‘Welcome to our site ‘ .

<script language=javascript> alert(‘Hey, you are going

to be hijacked!’);</script>

 

?>

The output of this code is an alert JavaScript box telling you “Hey, you are going be hijacked!” after the “Welcome to our site” phrase.

 

Very ugly stuff, right? That’s a simple example of the Cross Site Scripting vulnerability. This means that any pasted JavaScript code into the URL will be executed happily with no complaints at all.

 

    

Q:92 Which method do you follow to get a record from a million records? (Searching, …. not from database, from an array in php)

A:92 use array_search(), array_keys(), array_values(), array_key_exists(), and in_array().

    

Q:93 Which sorting method is lowest time consumable?

A:93 HeapSort, Merge sort are the lowest time consumable sorting algorithm.

    

Q:94 Which sorting method is lowest memory consumable?

A:9412341

Freshers PHP/MySQL Technical Interview Questions & Answers

Freshers PHP Technical Interview Questions & Answers

Question : 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?

Answer : When to use GET or POST

The HTML 2.0 specification says, in section Form Submission (and the HTML 4.0 specification repeats this with minor stylistic changes):

–>If the processing of a form is idempotent (i.e. it has no lasting observable effect on the state of the
world), then the form method should be GET. Many database searches have no visible side-effects and make ideal applications of query forms.

–>If the service associated with the processing of a form has side effects (for example, modification of a database or subscription to a service), the method should be POST.

How the form data is transmitted?

quotation from the HTML 4.0 specification

–> If the method is “get” – -, the user agent takes the value of action, appends a ? to it, then appends the form data set, encoded using the application/x-www-form-urlencoded content type. The user agent then traverses the link to this URI. In this scenario, form data are restricted to ASCII codes.
–> If the method is “post” –, the user agent conducts an HTTP post transaction using the value of the action attribute and a message created according to the content type specified by the enctype
attribute.

Quote from CGI FAQ

Firstly, the the HTTP protocol specifies differing usages for the two methods. GET requests should always be idempotent on the server. This means that whereas one GET request might (rarely) change some state on the Server, two or more identical requests will have no further effect.

This is a theoretical point which is also good advice in practice. If a user hits “reload” on his/her browser, an identical request will be sent to the server, potentially resulting in two identical database or guestbook entries, counter increments, etc. Browsers may reload a GET URL automatically, particularly if cacheing is disabled (as is usually the case with CGI output), but will typically prompt the user before re-submitting a POST request. This means you’re far less likely to get inadvertently-repeated entries from POST.

GET is (in theory) the preferred method for idempotent operations, such as querying a database, though it matters little if you’re using a form. There is a further practical constraint that many systems have built-in limits to the length of a GET request they can handle: when the total size of a request (URL+params) approaches or exceeds 1Kb, you are well-advised to use POST in any
case.

I would prefer POST when I don’t want the status to be change when user resubmits. And GET
when it does not matter.

Question : Who is the father of PHP and explain the changes in PHP versions?

Answer : Rasmus Lerdorf is known as the father of PHP.PHP/FI 2.0 is an early and no longer supported version of PHP. PHP 3 is the successor to PHP/FI 2.0 and is a lot nicer. PHP 4 is the current generation of PHP, which uses the Zend engine under the hood. PHP 5 uses Zend engine 2 which, among other things, offers many additional OOPs features.

Question : How can we submit a form without a submit button?

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

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

Answer : You can do it by 4 Ways

1. mysql_fetch_row.
2. mysql_fetch_array
3. mysql_fetch_object
4. mysql_fetch_assoc

Question : What is the difference between mysql_fetch_object and
mysql_fetch_array?

Answer : mysql_fetch_object() is similar to mysql_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).

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

Answer : It is a classic example of PHP’s variable variables. take the following example.

$message = “Raghav”;

$$message = “is a owner of https://sharag.wordpress.com/ “;

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

Question : How can we extract string ‘hotmail.com ‘ from a string raghav.cool@hotmail.com using regular expression of PHP?

Answer : preg_match(”/^http://.+@(.+)$/”,’raghav.cool@hotmail.com’,$found);
echo $found[1];

Question : How can we create a database using PHP and MySQL?

Answer : We can create MySQL Database with the use of mysql_create_db(“Database Name”).

Question : What are the differences between require and include, include_once and require_once?

Answer :

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 handle
failure. include() produces a Warning while require() results in a Fatal Error. In other words, use
require() if you want a missing file 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 difference being 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 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. 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.

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

Answer : Yes we can use include() more than one time in any page though it is not a very good practice.

Question : 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)) ?

Answer : 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 and as a result if
we do not specify the table name explicitly it will be assigned to the
default engine.

Question : Functions in IMAP, POP3 AND LDAP?

Answer : You can find these specific information in PHP Manual.

Question : How can I execute a PHP script using command line?

Answer : As of version 4.3.0, PHP supports a new SAPI type (Server Application Programming Interface) named CLI which means Command Line Interface. 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.

Question : Suppose your Zend engine supports the mode <? ?>. Then how can you
configure your PHP Zend engine to support <?php ?>mode ?

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

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

Answer : We can find the detail documentation about different paypal integration process at the following site PayPal PHP
SDK : http://www.paypaldev.org/

Question : What is meant by nl2br()?

Answer : Inserts HTML line breaks
(
)
before all newlines in a string string nl2br (string); Returns string with ” inserted before all newlines.
For example: echo nl2br(”god bless/n you”) will output “god bless
you” to your browser.

Question : Draw the architecture of Zend engine?

Answer : The Zend Engine is the internal compiler and runtime engine used by PHP4. Developed by Zeev Suraski and Andi Gutmans, the Zend Engine is an
abbreviation of their names. In the early days of PHP4, it worked as follows:

The PHP script was loaded by the Zend Engine and compiled into Zend opcode. Opcodes, short for operation codes, are low level binary instructions. Then the opcode was executed and the HTML generated sent to the client. The opcode was flushed from memory after execution.Today, there are a multitude of products and techniques to help you speed up this process. In the following diagram, we show the how modern PHP scripts work; all the shaded boxes are optional.

PHP Scripts are loaded into memory and compiled into Zend opcodes.

Question : What are the current versions of apache, PHP, and MySQL?

Answer : As of Aug 2008 the current versions are PHP: php5.2.6
MySQL: MySQL 5.1.2
Apache: Apache 2.2.9
Note: visit
http://www.php.net/,
http://dev.mysql.com/downloads/mysql/,
http://www.apache.org/ to get current
versions.

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

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

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

Answer : AES_ENCRYPT () and AES_DECRYPT ()

Question : How can we encrypt the username and password using PHP?

Answer : The functions in this section perform encryption and decryption, and
compression and uncompression:

Encryption Decryption
AES_ENCRYT() AES_DECRYPT()
ENCODE() DECODE()
DES_ENCRYPT() DES_DECRYPT()
ENCRYPT() Not available
MD5() Not available
OLD_PASSWORD() Not available
PASSWORD() Not available
SHA() or SHA1() Not available
Not available UNCOMPRESSED_LENGTH()

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

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

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

Answer : Traditional programming has the following characteristics:Functions are written sequentially, so that a change in programming can affect any code that follows it. If a function is used multiple times in a system (i.e., a piece of code that manages the date), it is often simply cut and pasted into each program (i.e., a change log, order function, fulfillment system, etc). If a date change is needed (i.e., Y2K when the code needed to be changed to handle four numerical digits instead of two), all these pieces of code must be found, modified, and tested. Code (sequences of computer instructions) and data (information on which the instructions operates on) are kept separate. Multiple sets of code can access and modify one set of data. One set of code may rely on data in multiple places. Multiple sets of code and data are required to work together. Changes made to any of the code sets and data sets can cause problems through out the system.Object-Oriented programming takes a radically different approach:Code and data are merged into one indivisible item – an object (the term “component” has also been used to describe an object.) An object is an abstraction of a set of real-world things (for example, an object may be created around “date”) The object would contain all information and
functionality for that thing (A date object it may contain labels like January, February, Tuesday, Wednesday.
It may contain functionality that manages leap years, determines if it is a business day or a holiday, etc., See Fig. 1). Ideally, information about a particular thing should reside in only one place in a system.The information within an object is encapsulated (or hidden) from the rest of the system. A system is composed of multiple objects (i.e., date function, reports, order processing, etc., See Fig 2). When one object needs information from another object, a request is sent asking for specific information. (for example, a report object may need to know what today’s date is and will send a request to the date object) These requests are called messages and each object has an interface that manages messages. OO programming languages include features such as “class”, “instance”, “inheritance”, and “polymorphism” that increase the power and
flexibility of an object.

Question : What is the use of friend function?

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

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

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

Question : What are the different types of errors in PHP?

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

Question : What is the functionality of the function strstr and stristr?

Answer : strstr:
Returns part of haystack string from the first occurrence of needle to the end of haystack.If needle is not found, returns FALSE. If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This function is case-sensitive. For case-insensitive searches, use stristr().

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

Answer : PHP 3 is most procedure oriented and , PHP4 and PHP5 aer object oriented. For more details
http://php.net/

Question : How can we convert asp pages to PHP pages?

Answer : There are lots of tools available for asp to PHP conversion. you can search Google for that. the best one is available at http://asp2php.naken.cc/

Question : What is the functionality of the function htmlentities?

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

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

Answer : $second = date(”s”);

Question : How can we convert the time zones using PHP?

Answer : By using date_default_timezone_get and
date_default_timezone_set function on PHP 5.1.0
<!–p// Discover what 8am in Tokyo relates to on the East Coast of the US

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

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

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

// Output the date in a standard format (RFC1123), this will  print:
// Fri, 31 Dec 1999 18:00:00 EST
echo ‘

‘, date(DATE_RFC1123, $stamp) ,’

‘; ?>

Question : What is meant by urlencode and urldecode?

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

Question : What is the difference between the functions unlink and unset?

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

Question : How can we register the variables into a session?

Answer : $_SESSION[’name’] = “RAGHAV”;

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

Answer : To know the Image type use exif_imagetype () function
To know the Image size use getimagesize () function
To know the image width use imagesx () function
To know the image height use imagesy() function

Question : How can we get the browser properties using PHP?

Answer : By using
$_SERVER[’HTTP_USER_AGENT’] variable.

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

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

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

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

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

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

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

Answer : • First of all instead of using select * from table1, use select column1, column2, column3.. from table1
•Look for the opportunity to introduce index in the table you are  querying.
•use limit keyword if you are looking for any specific number of rows from the result set.

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

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

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

Answer : session_unregister — Unregister a global variable from the current session

session_unset — Free all session variables

Question : How can we destroy the cookie?

Answer : Set the cookie in past.

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

Answer : •GET/QueryString
•POST

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

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

Question : What are the different functions in sorting an array?

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

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

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

Question : What is the PHP predefined variable that tells the What types of
images that PHP supports?

Answer : Though i am not sure if this is wrong or not, With the exif extension you are able to work with image meta data.

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

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

Question : List out some tools through which we can draw E-R diagrams for mysql.

Answer :
Case Studio
Smart Draw

Question : How can I retrieve values from one database server and store themin other database server using PHP?

Answer : WeWe can always fetch from one database and rewrite to another. Here is a nice solution of it.
$db1 = mysql_connect(”host”,”user”,”pwd”);
mysql_select_db(”db1?, $db1);
$res1 = mysql_query(”query”,$db1);
$db2 = mysql_connect(”host”,”user”,”pwd”);
mysql_select_db(”db2?, $db2);
$res2 = mysql_query(”query”,$db2);
At this point you can only fetch records from you previous ResultSet, i.e $res1 – But you cannot execute new query in $db1, even if yousupply the link as because the link was overwritten by the new db.so at this point the following script will fail
$res3 = mysql_query(”query”,$db1); //this will failSo how to solve that? take a look below.
$db1 = mysql_connect(”host”,”user”,”pwd”);
mysql_select_db(”db1?, $db1);
$res1 = mysql_query(”query”,$db1);
$db2 = mysql_connect(”host”,”user”,”pwd”, true);
mysql_select_db(”db2?, $db2);
$res2 = mysql_query(”query”,$db2);
So mysql_connect has another optional boolean parameter whichindicates whether a link will be created or not. As we connect to the $db2 with this optional parameter set to ‘true’, so both link willremain live. Now the following query will execute successfully.
$res3 = mysql_query(”query”,$db1);

Question : List out the predefined classes in PHP?

Answer : Directory
stdClass
__PHP_Incomplete_Class
exception
php_user_filter

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

Answer : You can maintain two separate language file for each of the language. All the labels are putted in both language files as variables and assign those variables in the PHP source. On run-time choose the required language option.

Question : What are the difference between abstract class and interface?

Answer : Abstract class: abstract classes are the class where one or moremethods are abstract but not necessarily all method has to be abstract.

Abstract methods are the methods, which are declare in its class but not defined. 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 defined by its implemented class.

Question : How can we send mail using JavaScript?

Answer : JavaScript does not have any networking capabilities as it isdesigned to work on client site. As a result we can not send mails usingJavaScript. But we can call the client side mail protocol mailtovia JavaScript to prompt for an Email  to send. this requires the client to approve it.

Question : How can we repair a MySQL table?

Answer : 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 givenit will create index row by row.

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

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

Question : What is the maximum length of a table name, database name and field name in MySQL?

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

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

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

Question : How many values can the SET function of MySQL take?

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

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

Answer : describe Table-Name;

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

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

Question : What is the purpose of the following files having extensions 1) .frm2) .myd 3) .myi? What do these files contain?

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

Question : What is maximum size of a database in MySQL?

Answer : If the operating system or file system 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 offiles 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 to65536 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 table space that can be created from several files. This allows a table to exceed the maximum individual file size. The table space can include raw disk partitions, which allows extremely large tables. The maximum table space 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 documentationspecific 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

Question : Give the syntax of Grant and Revoke commands?

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

Question : Explain Normalization concept?

Answer : 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 dependent on the primary key, but dependent on another value in the table.

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

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

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

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

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

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

Question : What are the advantages and disadvantages of Cascading Style Sheets?

Answer :
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 eachdocument The rendering of the document may be delayed until the externalstyle sheet is loaded becomes slightly unwieldy for small quantities ofstyle 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 complexcontexts. No additional downloads necessary to receive style information.
Disadvantages : This method can not control styles for multiple documents at once.
Inline Styles
Advantages : Useful for small quantities of style definitions. Can override otherstyle specification methods at the local level so only exceptions needto be listed in conjunction with other style methods.
Disadvantages : Does not distance style information from content (a main goal ofSGML/HTML). Can not control styles for multiple documents at once.Author can not create or control classes of elements to control multipleelement types within the document. Selector grouping methods can not beused to create complex element addressing scenarios

Question : What type of inheritance that PHP supports?

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

Question : What is the difference between Primary Key and Unique key?

Answer : Primary Key: A column in a table whose values uniquely identify therows in the table. A primary key value cannot be NULL. Unique Key: Unique Keys are used to uniquely identify each row in thetable. There can be one and only one row for each unique key value. So NULL can be a unique key.There can be only one primary key for a table but there can be morethan one unique for a table.

Question : 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 the last row 999 then What will happen inthe following conditions?Condition1: Delete all the rows and insert another row then.What is the starting value for this auto incremented field user_pri_id ,Condition2: Delete the last row(having the field value 999) andinsert another row then. What is the value for this auto incremented field user_pri_id.

Answer : In both cases let the value for auto increment field be n then nextrow will have value n+1 i.e. 1000.

Question : What are the advantages/disadvantages of MySQL and PHP?

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

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

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

Question : What is the difference between char and varchar data types?

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

Question : What is the functionality of md5 function in PHP?

Answer : Calculate the md5 hash of a string. The hash is a 32-characterhexadecimal number. I use it to generate keys which I use to identifyusers etc. If I add random no techniques to it the md5 generated nowwill be totally different for the same string I am using.

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

Answer : you can use LOAD DATA INFILE file_name; syntax to load datafrom a text file. but you have to make sure thata) data is delimitedb) columns and data matched correctly.

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

Answer : SELECT DATEDIFF(’2007-03-07?,’2005-01-01?);

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

Answer : $date1 = date(’Y-m-d’);
$date2 = ‘2006-08-15?;
$days = (strtotime($date1) – strtotime($date2)) / (60 * 60 * 24);

PHP OOPS Interview Questions & Answers

PHP OOPS Interview Questions & Answers

1) Explain what is object oriented programming language?
Object oriented programming language allows concepts such as modularity, encapsulation, polymorphism and inheritance.  Objects are said to be the most important part of object oriented language. Concept revolves around making simulation programs around an object. Organize a program around its data (object)& set well define interface to that data. i.e. objects and a set of well defined interfaces to that data. OOP is the common abbreviation for Object-Oriented Programming.  OOps have many properties such as DataHiding,Inheritence,Data Absraction,Data Encapsulation and many more.

2) Name some languages which have object oriented language and characteristics?
Some of the languages which have object oriented languages present in them are ABAP, ECMA Script, C++, Perl, LISP, C#, Tcl, VB, Ruby, Python, PHP, etc. Popularity of these languages has increased considerably as they can solve complex problems with ease.
3) Explain about UML?
UML or unified modeling language is regarded to implement complete specifications and features of object oriented language. Abstract design can be implemented in object oriented programming languages. It lacks implementation of polymorphism on message arguments which is a OOPs feature.
4) Explain the meaning of object in object oriented programming?
Languages which are called as object oriented almost implement everything in them as objects such as punctuations, characters, prototypes, classes, modules, blocks, etc. They were designed to facilitate and implement object oriented methods.
5) Explain about message passing in object oriented programming?
Message passing is a method by which an object sends data to another object or requests other object to invoke method. This is also known as interfacing. It acts like a messenger from one object to other object to convey specific instructions.
6) State about Java and its relation to Object oriented programming?
Java is widely used and its share is increasing considerably which is partly due to its close resemblance to object oriented languages such as C++. Code written in Java can be transported to many different platforms without changing it. It implements virtual machine.
7) What are the problems faced by the developer using object oriented programming language?

These are some of the problems faced by the developer using object oriented language they are: –

a) Object oriented uses design patterns which can be referred to as anything in general.
b) Repeatable solution to a problem can cause concern and disagreements and it is one of the major problems in software design.
8 ) State some of the advantages of object oriented programming?
Some of the advantages of object oriented programming are as follows: –
a) A clear modular structure can be obtained which can be used as a prototype and it will not reveal the mechanism behind the design. It does have a clear interface.
b) Ease of maintenance and modification to the existing objects can be done with ease.
c) A good framework is provided which facilitates in creating rich GUI applications.
9 ) Explain about inheritance in OOPS?
Objects in one class can acquire properties of the objects in other classes by way of inheritance. Reusability which is a major factor is provided in object oriented programming which adds features to a class without modifying it. New class can be obtained from a class which is already present.
10) Explain about the relationship between object oriented programming and databases?
Object oriented programming and relational database programming are almost similar in software engineering. RDBMS will not store objects directly and that’s where object oriented programming comes into play. Object relational mapping is one such solution.
11) Explain about a class in OOP?
In Object oriented programming usage of class often occurs. A class defines the characteristics of an object and its behaviors. This defines the nature and functioning of a specified object to which it is assigned. Code for a class should be encapsulated.

12) Explain the usage of encapsulation?
Encapsulation specifies the different classes which can use the members of an object. The main goal of encapsulation is to provide an interface to clients which decrease the dependency on those features and parts which are likely to change in future. This facilitates easy changes to the code and features.
13) Explain about abstraction?
Abstraction can also be achieved through composition. It solves a complex problem by defining only those classes which are relevant to the problem and not involving the whole complex code into play.
14) Explain what a method is?
A method will affect only a particular object to which it is specified. Methods are verbs meaning they define actions which a particular object will perform. It also defines various other characteristics of a particular object.
15) Name the different Creational patterns in OO design?
There are three patterns of design out of which Creational patterns play an important role the various patterns described underneath this are: –
a) Factory pattern
b) Single ton pattern
c) Prototype pattern
d) Abstract factory pattern
e) Builder pattern
16) Explain about realistic modeling?
As we live in a world of objects, it logically follows that the object oriented approach models the real world accurately. The object oriented approach allows you to identify entities as objects having attributes and behavior.
17) Explain about the analysis phase?
The anlaysis or the object oriented analysis phase considers the system as a solution to a problem in its environment or domain. Developer concentrates on obtaining as much information as possible about the problem. Critical requirements needs to be identified.

************************************************************************************************************

1) Explain the rationale behind Object Oriented concepts?

Object oriented concepts form the base of all modern programming languages. Understanding the basic concepts of object-orientation helps a developer to use various modern day programming languages, more effectively.
2) Explain about Object oriented programming?
Object oriented programming is one of the most popular methodologies in software development. It offers a powerful model for creating computer programs. It speeds the program development process, improves maintenance and enhances reusability of programs.
3) Explain what is an object?
An object is a combination of messages and data. Objects can receive and send messages and use messages to interact with each other. The messages contain information that is to be passed to the recipient object.
4) Explain the implementation phase with respect to OOP?
The design phase is followed by OOP, which is the implementation phase. OOP provides specifications for writing programs in a programming language. During the implementation phase, programming is done as per the requirements gathered during the analysis and design phases.
5) Explain about the Design Phase?
In the design phase, the developers of the system document their understanding of the system. Design generates the blue print of the system that is to be implemented. The first step in creating an object oriented design is the identification of classes and their relationships.
6) Explain about a class?
Class describes the nature of a particular thing. Structure and modularity is provided by a Class in object oriented programming environment. Characteristics of the class should be understandable by an ordinary non programmer and it should also convey the meaning of the problem statement to him. Class acts like a blue print.

7) Explain about instance in object oriented programming?
Every class and an object have an instance. Instance of a particular object is created at runtime. Values defined for a particular object define its State. Instance of an object explains the relation ship between different elements.
8 ) Explain about inheritance?
Inheritance revolves around the concept of inheriting knowledge and class attributes from the parent class. In general sense a sub class tries to acquire characteristics from a parent class and they can also have their own characteristics. Inheritance forms an important concept in object oriented programming.
9) Explain about multiple inheritance?
Inheritance involves inheriting characteristics from its parents also they can have their own characteristics. In multiple inheritance a class can have characteristics from multiple parents or classes. A sub class can have characteristics from multiple parents and still can have its own characteristics.
10) Explain about encapsulation?
Encapsulation passes the message without revealing the exact functional details of the class. It allows only the relevant information to the user without revealing the functional mechanism through which a particular class had functioned.
11) Explain about abstraction?
Abstraction simplifies a complex problem to a simpler problem by specifying and modeling the class to the relevant problem scenario. It simplifies the problem by giving the class its specific class of inheritance. Composition also helps in solving the problem to an extent.
12) Explain the mechanism of composition?
Composition helps to simplify a complex problem into an easier problem. It makes different classes and objects to interact with each other thus making the problem to be solved automatically. It interacts with the problem by making different classes and objects to send a message to each other.
13) Explain about polymorphism?
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.
14) Explain about overriding polymorphism?
Overriding polymorphism is known to occur when a data type can perform different functions. For example an addition operator can perform different functions such as addition, float addition etc. Overriding polymorphism is generally used in complex projects where the use of a parameter is more.
15) Explain about object oriented databases?
Object oriented databases are very popular such as relational database management systems. Object oriented databases systems use specific structure through which they extract data and they combine the data for a specific output. These DBMS use object oriented languages to make the process easier.
16) Explain about parametric polymorphism?
Parametric polymorphism is supported by many object oriented languages and they are very important for object oriented techniques. In parametric polymorphism code is written without any specification for the type of data present. Hence it can be used any number of times.
17) What are all the languages which support OOP?
There are several programming languages which are implementing OOP because of its close proximity to solve real life problems. Languages such as Python, Ruby, Ruby on rails, Perl, PHP, Coldfusion, etc use OOP. Still many languages prefer to use DOM based languages due to the ease in coding.

var gaJsHost = ((“https:” == document.location.protocol) ? “https://ssl.&#8221; : “http://www.&#8221;);
document.write(unescape(“%3Cscript src='” + gaJsHost + “google-analytics.com/ga.js’ type=’text/javascript’%3E%3C/script%3E”));

try {
var pageTracker = _gat._getTracker(“UA-1855756-5”);
pageTracker._trackPageview();
} catch(err) {}