Tuesday, May 22, 2012

CSS Interview Question and Answers

1. Explain in brief about the term CSS.
         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.
2.Can CSS be used with other than HTML documents?
         Yes. CSS can be used with any structured document format. e.g. XML, however, the method of linking CSS with other document types has not been decided yet.
3.Can Style Sheets and HTML stylistic elements be used in the same document?
         Yes. Style Sheets will be ignored in browsers without CSS-support and HTML stylistic elements used.
4.What is CSS rule ‘at-rule’?
There are two types of CSS rules: ruleset and at-rule. At-rule is a rule that applies to the whole style sheet and not to a specific selector only (like in ruleset). They all begin with the @ symbol followed by a keyword made up of letters a-z, A-Z, digits 0-9, dashes and escaped characters, e.g. @import or @font-face.
5.What is selector?
         CSS selector is equivalent of HTML element(s). It is a string identifying to which element(s) the corresponding declaration(s) will apply and as such the link between the HTML document and the style sheet.
For example in P {text-indent: 10pt} the selector is P and is called type selector as it matches all instances of this element type in the document.
in P, UL {text-indent: 10pt} the selector is P and UL (see grouping); in .class {text-indent: 10pt} the selector is .class (see class selector).

6.What is CLASS selector?
         Class selector is a “stand alone” class to which a specific style is declared. Using the CLASS attribute the declared style can then be associated with any HTML element. The class selectors are created by a period followed by the class’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. (Note: in HTML the value of the CLASS attribute can contain more characters).It is a good practice to name classes according to their function than their appearance.
.footnote {font: 70%} /* class as selector */
This element is associated with the CLASS footnote
7.What is CSS declaration?
         CSS declaration is style attached to a specific selector. It consists of two parts; property which is equivalent of HTML attribute, e.g. text-indent: and value which is equivalent of HTML value, e.g. 10pt. NOTE: properties are always ended with a colon.
8.What is ‘important’ declaration?
           Important declaration is a declaration with increased weight. Declaration with increased weight will override declarations with normal weight. If both reader’s and author’s style sheet contain statements with important declarations the author’s declaration will override the reader’s.

BODY {background: white ! important; color: black}
In the example above the background property has increased weight while the color property has normal.

9.What is property?
        Property is a stylistic parameter (attribute) that can be influenced through CSS, e.g. FONT or WIDTH. There must always be a corresponing value or values set to each property, e.g. font: bold or font: bold san-serif.
10.How do I eliminate the blue border around linked images?
in your CSS, you can specify the border property for linked images:
a img { border: none ; }
However, note that removing the border that indicates an image is a link makes it harder for users to distinguish quickly and easily which images on a web page are clickable.
11.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 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 …
12.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}
This and only this element can be identified as abc123.
13.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.
14.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:
.\041B\041F {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:
.\041B9\041F {font-style: italic;}
15.← Top 10 HTML Interview Questions and Answers
Top 10 Best Fonts off All Time →
Top 10 CSS Interview Questions and Answers Edition-1

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

Indented paragraph
16.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.
17.If background and color should always be set together, why do they exist as separate properties?
     There are serveral 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.
18.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}
19.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
20.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...

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






21.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
22.What are pseudo-elements?
         Pseudo-elements are fictional elements that do not exist in HTML. They address the element's sub-part (non-existent in HTML) and not the element itself. In CSS1 there are two pseudo-elements: 'first-line pseudo-element' and 'first-letter pseudo-element'. They can be attached to block-level elements (e.g. paragraphs or headings) to allow typographical styling of their sub-parts. Pseudo-element is created by a colon followed by pseudo-element's name, e.g:
P:first-line
H1:first-letter
and can be combined with normal classes; e.g:
P.initial:first-line
First-line pseudo-element allows sub-parting the element's first line and attaching specific style exclusively to this sub-part; e.g.:
P.initial:first-line {text-transform: uppercase}
The first line of this paragraph will be displayed in uppercase letters

First-letter pseudo-element allows sub-parting the element's first letter and attaching specific style exclusively to this sub-part; e.g.:
P.initial:first-letter { font-size: 200%; color: red}
The first letter of this paragraph will be displayed in red and twice as large as the remaining letters
23.How do I have links of different colours on the same page?
Recommending people to use classes in their 'a' tags like this :
CSS
a.red {
color:red;
}
a.blue {
color:blue;
}

This is a valid way to do it, but usually, this isn't what a page looks like - two links next to each other with different colours - it's usually something like a menu with one kind of link and main body text or another menu with different links. In this (normal) situation, To go higher up the cascade to style the links. Something like this :
CSS
a {
color:red;
}
#menu a {
color:blue;
}
24.What is the importance of Cascade in CSS?
        One doesn't have to declare repeating styles for the child elements. E.g. if has a font-name style set to Arial, by default all the elements in the
HTML document will inherit this property, unless defined separately.
25.What is the cascading order of a CSS style sheet?
Generally speaking we can say that all the styles will "cascade" into a new "virtual" style sheet by the following rules, where number four has the highest priority:
   1. Browser default
   2. External style sheet
   3. Internal style sheet (inside the tag)
   4. Inline style (inside an HTML element)
So, an inline style (inside an HTML element) has the highest priority, which means that it will override a style declared inside the tag, in an external style sheet, or in a browser (a default value).
26. How you define CSS Padding?
         Using CSS Padding we can set the spaces between the border and element.The top, right, bottom and left padding can be changed independently using separate properties
27.How you define CSS Margin?
 Using CSS Margin we can set the spaces around the elements.
28.How do I center block-elements with CSS?
   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.














Monday, May 14, 2012

Mysql Interview questions and answers

1:What's MySQL ?
          
MySQL (pronounced "my ess cue el") is an open source relational database management system (RDBMS) that uses Structured Query Language (SQL), the most popular language for adding, accessing, and processing data in a database. Because it is open source, anyone can download MySQL and tailor it to their needs in accordance with the general public license. MySQL is noted mainly for its speed, reliability, and flexibility.
2:What is DDL, DML and DCL ?
         If you look at the large variety of SQL commands, they can be divided into three large subgroups. Data Definition Language deals with database schemas and descriptions of how the data should reside in the database, therefore language statements like CREATE TABLE or ALTER TABLE belong to DDL. DML deals with data manipulation, and therefore includes most common SQL statements such SELECT, INSERT, etc. Data Control Language includes commands such as GRANT, and mostly concerns with rights, permissions and other controls of the database system.
3:How do you start and stop MySQL on Windows?
        - net start MySQL, net stop MySQL
4: How do you start MySQL on Linux?
         - /etc/init.d/mysql start
5:How do you change a password for an existing user via mysqladmin?                  mysqladmin -u root -p password "newpassword"
6:Explain the difference between MyISAM Static and MyISAM Dynamic.
         In MyISAM static all the fields have fixed width. The Dynamic MyISAM table would include fields such as TEXT, BLOB, etc. to accommodate the data types with various lengths. MyISAM Static would be easier to restore in case of corruption, since even though you might lose some data, you know exactly where to look for the beginning of the next record.
7:What does myisamchk do?
          It compressed the MyISAM tables, which reduces their disk usage.
8:Explain advantages of MyISAM over InnoDB? 
            Much more conservative approach to disk space management - each MyISAM table is stored in a separate file, which could be compressed then with myisamchk if needed. With InnoDB the tables are stored in tablespace, and not much further optimization is possible. All data except for TEXT and BLOB can occupy 8,000 bytes at most. No full text indexing is available for InnoDB. TRhe COUNT(*)s execute slower than in MyISAM due to tablespace complexity.
9:What happens when the column is set to AUTO INCREMENT and you reach the maximum value for that table?
          It stops incrementing. It does not overflow to 0 to prevent data losses, but further inserts are going to produce an error, since the key has been used already.
10: What happens if a table has one column defined as TIMESTAMP?               That field gets the current timestamp whenever the row gets altered.
11: But what if you really want to store the timestamp data, such as the publication date of the article?
           Create two columns of type TIMESTAMP and use the second one for your real data.
12:What Is Primary Key?
        A primary key is a single column or multiple columns defined to have unique values that can be used as row identifications.
13:What Is Foreign Key?
       A foreign key is a single column or multiple columns defined to have values that can be mapped to a primary key in another table.
14:What Is Index?
         An index is a single column or multiple columns defined to have values pre-sorted to speed up data retrieval speed.
15:What Is View?
         A view is a logical table defined by a query statement.
16:What Is Transaction?
         A transaction is a logical unit of work requested by a user to be applied to the database objects. MySQL server introduces the transaction concept to allow users to group one or more SQL statements into a single transaction, so that the effects of all the SQL statements in a transaction can be either all committed (applied to the database) or all rolled back (undone from the database).
17:What Is Commit?
          Commit is a way to terminate a transaction with all database changes to be saved permanently to the database server.
18:What Is Rollback?
          Rollback is a way to terminate a transaction with all database changes not saving to the database server.
19:When you create a table, and then run SHOW CREATE TABLE on it, you occasionally get different results than what you typed in. What does MySQL modify in your newly created tables?
1. VARCHARs with length less than 4 become CHARs
2. CHARs with length more than 3 become VARCHARs.
3. NOT NULL gets added to the columns declared as PRIMARY KEYs
4. Default values such as NULL are specified for each column .
20:How do you get the number of rows affected by query?
        SELECT COUNT (user_id) FROM users would only return the number of user_id’s.
21:If the value in the column is repeatable, how do you find out the unique values?
        Use DISTINCT in the query, such as SELECT DISTINCT user_firstname FROM users; You can also ask for a number of distinct values by saying SELECT COUNT (DISTINCT user_firstname) FROM users;
22:How do you return the a hundred books starting from 25th?
          SELECT book_title FROM books LIMIT 25, 100. The first number in LIMIT is the offset, the second is the number.
23:What types of privileges are there in MySQL ?
          There are 4 types of privileges.
i). Global privileges like *.* (all hosts connecting to Mysql db server)
Ex: GRANT SELECT, INSERT ON *.* TO ‘someuser’@'somehost’;
ii). Database privileges like .*
Ex: GRANT SELECT, INSERT ON mydb.* TO ‘someuser’@'somehost’;
iii). Table privileges like SELECT, INSERT, UPDATE, DELETE
Ex: GRANT SELECT, INSERT ON mydb.mytbl TO ‘someuser’@'somehost’;
iv). Column privileges like
Ex: GRANT SELECT (col1), INSERT (col1,col2) ON mydb.mytbl TO ‘someuser’@'somehost’; 
24:How do I grant permission to a specific host ?
Command: GRANT ALL ON *.* TO ‘user_name’@'host_name’ IDENTIFIED BY ‘password’ ;
Ex: GRANT ALL ON *.* TO ‘test_app’@'sustain-75.central’ IDENTIFIED BY ‘testapp123′;
25:Is it possible to insert multiple rows using single command in MySQL ?
         Yes. Please see below example.
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9) ;

26:How do you return the a hundred books starting from 25th?
       SELECT book_title FROM books LIMIT 25, 100. The first number in LIMIT is the offset, the second is the number.
27:When would you use ORDER BY in DELETE statement?
When you’re not deleting by row ID. Such as in DELETE FROM employee ORDER BY timestamp LIMIT 1. This will delete the most recently posted question in the table temployee.
28:How would you delete a column?
        ALTER TABLE employee DROP phone.
29:How do you find out which auto increment was assigned on the last insert?
         SELECT LAST_INSERT_ID() will return the last value assigned by the auto_increment function. Note that you don’t have to specify the table name.
30:What are HEAP tables in MySQL?
        HEAP tables are in-memory. They are usually used for high-speed temporary storage. No TEXT or BLOB fields are allowed within HEAP tables. You can only use the comparison operators = and <=>. HEAP tables do not support AUTO_INCREMENT. Indexes must be NOT NULL.
31:What happens when the column is set to AUTO INCREMENT and you reach the maximum value for that table?
         It stops incrementing. It does not overflow to 0 to prevent data losses, but further inserts are going to produce an error, since the key has been used already.
32: What is REPLCAE statement, and how do I use it?

          The REPLACE statement is the same as using an INSERT INTO command. The syntax is pretty much the same. The difference between an INSERT statement and a REPLACE statement is that MySQL will delete the old record and replace it with the new values in a REPLACE statement, hence the name REPLACE.
33: Do all unique keys have to be primary keys?
         No. MySQL permits only one primary key per table, but there may be a number of unique keys. Both unique keys and primary keys can speed up the selecting of data with a WHERE clause, but a column should be chosen as the primary key if this is the column by which you want to join the table with other tables.
34:How many databases can one MySQL RDBMS contain?
         Because MySQL uses the file system of the operating system, there really is no limit to the number of databases contained within a single MySQL RDBMS. The size of the database is limited by the operating system. The database tables can only be as big as the OS's file system will allow.
35:I want to sort the values of my ENUM and SET columns. How do I do this?
         The sort order depends on the order in which the values were inserted. ENUM and SET types are not case sensitive. The value that is inserted reverts to the value that you used when you created the ENUM or SET.
36:What do I do if I forget the MySQL root password?
         First log in to the system as the same person who is running the mysqld
daemon (probably root). Kill the process, using the kill command.
Restart MySQL with the following arguments:
bin/mysqld Skip-grant
USE mysql;
UPDATE user SET password = password('newpassword') WHERE User = 'root';
Exit
bin/mysqladmin reload
The next time you log in, you will use your new password
37: Where is the data stored in a MySQL database?
         MySQL uses files to store data. These files are under the data/databasename directory, where databasename is the name of the database. There are three file types: .ISM, .FRM, and .ISD. The .FRM file contain the table schema. The .ISD is the file that actually holds the data. The .ISM file is the file that provides quick access between the two of them.
38:Explain "REPAIR TABLE" statement?
     The REPAIR TABLE statement corrects problems in a table that has become corrupted. It works only for MyISAM tables.
39:Explain "OPTIMIZE TABLE" statement?
       The OPTIMIZE TABLE statement cleans up a MyISAM table by defragmenting it. This involves reclaiming unused space resulting from deletes and updates, and coalescing records that have become split and stored non-contiguously. OPTIMIZE TABLE also sorts the index pages if they are out of order and updates the index statistics.
40:What is the difference between CHAR AND VARCHAR?
The CHAR and VARCHAR types are similar, but differ in the way they are stored and retrieved.
The length of a CHAR column is fixed to the length that you declare when you create the table.
The length can be any value between 1 and 255. When CHAR values are stored, they are right-padded with spaces to the specified length. When CHAR values are retrieved, trailing spaces are removed.
41:what is difference between primary key and candidate key?
 Primary Key
- are used to uniquely identify each row of the table. A table can have only one primary Key.
Candidate Key
- primary key is a candidate key. There is no difference. By common convention one candidate key is designated as a “primary” one and that key is used for any foreign key references.
42:What is the difference between mysql_fetch_array and mysql_fetch_object?
mysql_fetch_array(): - returns a result row as a associated array, regular array from database.
mysql_fetch_object: - returns a result row as object from database.
43:Self join in Mysql:
Self join is a method of centralizing relational data to a single table.A self-join joins the table to itself.
Example:
CREATE TABLE employees (
    NAME VARCHAR(20),
    email VARCHAR(20),
    mobile VARCHAR(20),
    sex CHAR(1),
    birth_date DATE,
);
INSERT INTO  employees VALUES ('xyz','xyz@example.com','11212','F','1985-06-05');
INSERT INTO  employees VALUES ('abc','abc@example.com','11111','M','1985-03-05');
INSERT INTO  employees VALUES ('abc1','abc1@example.com','21111','M','1987-03-05');
 SELECT e1.name, e2.name,e1.email
FROM employees AS e1, employees AS e2
WHERE e1.email = e2.email AND e1.sex = 'F' AND e2.sex = 'M';
43:How MySQL Optimizes LEFT JOIN and RIGHT JOIN ?
        A LEFT JOIN B in MySQL is implemented as follows:
The table B is set to be dependent on table A and all tables that A is dependent on.
The table A is set to be dependent on all tables (except B) that are used in the LEFT JOIN condition.
All LEFT JOIN conditions are moved to the WHERE clause.
All standard join optimizations are done, with the exception that a table is always read after all tables it is dependent on. If there is a circular dependence then MySQL will issue an error.
All standard WHERE optimizations are done.
If there is a row in A that matches the WHERE clause, but there wasn’t any row in B that matched the LEFT JOIN condition, then an extra B row is generated with all columns set to NULL.
If you use LEFT JOIN to find rows that don’t exist in some table and you have the following test: column_name IS NULL in the WHERE part, where column_name is a column that is declared as NOT NULL, then MySQL will stop searching after more rows (for a particular key combination) after it has found one row that matches the LEFT JOIN condition.
RIGHT JOIN is implemented analogously as LEFT JOIN.
The table read order forced by LEFT JOIN and STRAIGHT JOIN will help the join optimizer (which calculates in which order tables should be joined) to do its work much more quickly, as there are fewer table permutations to check.
Note that the above means that if you do a query of type:
SELECT * FROM a,b LEFT JOIN c ON (c.key=a.key) LEFT JOIN d (d.key=a.key) WHERE b.key=d.key
MySQL will do a full scan on b as the LEFT JOIN will force it to be read before d.
The fix in this case is to change the query to:
SELECT * FROM b,a LEFT JOIN c ON (c.key=a.key) LEFT JOIN d (d.key=a.key) WHERE b.key=d.key

44:Joins in MYSQL
         “JOIN” is a SQL keyword used to query data from two or more related tables.
To very simple example would be users (students) and course enrollments:
‘user’ table:
idnamecourse
1Alice1
2Bob1
3Caroline2
4David5
5Emma(NULL)

‘course’ table:
idname
1HTML5
2CSS3
3JavaScript
4PHP
5MySQL
INNER JOIN (or just JOIN)
         The most frequently used clause is INNER JOIN. This produces a set of records which match in both the user and course tables, i.e. all users who are enrolled on a course:







  

Query
 SELECT user.name, course.name
FROM `user`
INNER JOIN `course` on user.course = course.id;

Result:
user.name         course.name
Alice            HTML5
Bob            HTML5
Carline            CSS3
David              MySQL
LEFT JOIN
        What if we require a list of all students and their courses even if they’re not enrolled on one? A LEFT JOIN produces a set of records which matches every entry in the left table (user) regardless of any matching entry in the right table (course):








Query
SELECT user.name, course.name
FROM `user`
LEFT JOIN `course` on user.course = course.id;
Result:
user.name        course.name
Alice            HTML5
Bob            HTML5
Carline            CSS3
David            MySQL
Emma           (NULL)

RIGHT JOIN
         Perhaps we require a list all courses and students even if no one has been enrolled? A RIGHT JOIN produces a set of records which matches every entry in the right table (course) regardless of any matching entry in the left table (user):








Query
SELECT user.name, course.name
FROM `user`
RIGHT JOIN `course` on user.course = course.id;

Result:
user.namecourse.name
AliceHTML5
BobHTML5
CarlineCSS3
(NULL)JavaScript
(NULL)PHP
DavidMySQL
OUTER JOIN (or FULL OUTER JOIN)
        Our last option is the OUTER JOIN which returns all records in both tables regardless of any match. Where no match exists, the missing side will contain NULL.
        OUTER JOIN is less useful than INNER, LEFT or RIGHT and it’s not implemented in MySQL. However, you can work around this restriction using the UNION of a LEFT and RIGHT JOIN, e.g.








Result:
user.name         course.name
Alice              HTML5
Bob               HTML5
Carline             CSS3
David             MySQL
Emma             (NULL)
(NULL)             JavaScript
(NULL)             PHP

45:Stored procedure in MYSQL
          Stored procedures are set of SQL commands that are stored in the database data server. After the storing of the commands is done, the tasks can be performed or executed continuously, without being repeatedly sent to the server. This also helps in decreasing the traffic.
There are many advantages of using stored procedures, which include:
    * The functionality is application and platform related.
    * Functionality has to be developed only once, and all applications can call the same commands.
    * Task execution becomes easier and less complicated.
    * Network Traffic reduced to a greater extent.
    * Centralization of all commands made possible, which is helpful for various applications that repeatedly call the same set of complicated commands.
     * Runs on any kind of environment.
param_name type
type:
Any valid MySQL data type
characteristic:
LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
| COMMENT 'string'
routine_body:
Valid SQL procedure statement
Application
MySQL Stored Procedures can be applied in absolutely any place. Right from complex applications to simple procedures, these stored procedures can be utilized in absolutely any place.
Few of the many places that MySQL Stored procedures can be used are:
    * When diverse client applications are structured using various languages in different platforms.
    * When security is of highest importance, like in financial institutions, the users and applications would have no direct access to the database tables. This provides excellent secured environment.
    * When very few database servers service the client machines, thereby providing efficient performance.
Though not as mature as Oracle, DB2 or the SQL Server, the MySQL Stored Procedures is definitely worth a try. If the structure of the database is the same, the same stored procedures can be used for all.
A simple example for MySQL Stored Procedure
To calculate the area of a circle with given radius R, the following commands can be given

delimiter //
create function Area (R double) returns double
deterministic
begin
declare A double;
set A = R * R * pi();
return A;
end
//
delimiter ;

And to call it from php code to display the area of a circle with radius 22cm,
$rs_area = mysql_query(“select Area(22)”);
$area = mysql_result($rs_area,0,0);
echo “The area of the circle with radius 22cm is ”.$area.” sq.cm”;
?>
46: What is a Trigger in MySQL Define different types of Trigger?
        A trigger is a named database object that is associated with a table, and that activates when a particular event occurs for the table. Some uses for triggers are to perform checks of values to be inserted into a table or to perform calculations on values involved in an update.
       A trigger is associated with a table and is defined to activate when an INSERT, DELETE, or UPDATE statement for the table executes. A trigger can be set to activate either before or after the triggering statement. For example, you can have a trigger activate before each row that is deleted from a table or after each row that is updated.
An example of the MySQL triggers usage can be found below:
    *   First we will create the table for which the trigger will be set.
mysql> CREATE TABLE people (age INT, name varchar(150));
    *   Next we will define the trigger. It will be executed before every INSERT statement for the people table.
mysql> delimiter //
mysql> CREATE TRIGGER agecheck BEFORE INSERT ON people FOR EACH ROW IF NEW.age < 0 THEN SET NEW.age = 0; END IF;//
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
    *   We will insert two records to check the trigger functionality.
mysql> INSERT INTO people VALUES (-20, 'Sid'), (30, 'Josh');
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
    *   At the end we will check the result.
mysql> SELECT * FROM people;
+-------+-------+
| age | name |
+-------+-------+
| 0 | Sid |
| 30 | Josh |
+-------+-------+
2 rows in set (0.00 sec)

47:WHAT IS A VIEW?
      A view is a pre-compiled virtual table that is generated by a user-defined SELECT statement. Unlike tables, views don't physically store data on the database server, instead they act as aliases to existing tables.
WHY USE VIEWS?
         Views are used to customize the data that gets returned from a SELECT query.
BEFORE WE BEGIN
       The following CREATE TABLE queries should be executed on a test database, if you plan to follow along with my examples:
CREATE TABLE NewsCategories
( catID int not null auto_increment, catName varchar(32), primary key(catID));
CREATE TABLE News
( newsID int not null auto_increment, catID int not null, title
varchar(32) not null, txt blob, primary key(newsID));
INSERT INTO NewsCategories (catName) VALUES ('Main');
INSERT INTO News (catID, title, txt) VALUES (1, 'My Article!', 'Hello World');
CREATING A VIEW
Views are relatively easy to use. The syntax for creating a view is:
CREATE
[OR REPLACE]
[ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]
[DEFINER = { user | CURRENT_USER }]
[SQL SECURITY { DEFINER | INVOKER }]
VIEW view_name [(column_list)]
AS select_statement
[WITH [CASCADED | LOCAL] CHECK OPTION]
The following command will create a simple view that pulls the title and txt field from the News table:
CREATE VIEW newsView AS SELECT title, txt FROM News;
         To see your view in action all you will need to do is run a normal SELECT statement against the view (instead of a table). The following query will run the view you just created, which will select all title and txt fields from the News table.
SELECT * FROM newsView
           To create a view with MySQL Query Browser, simply right click on the database (in the right column) and click Create New View. Enter a view name and click Create View. You will then be presented with a code template for creating a view.
MODIFYING A VIEW
        To get a list of views, you can use the SHOW TABLES command. Here is a SHOW TABLES query that will display only views and filter out tables:
SHOW FULL TABLES WHERE Table_type='VIEW'
To see the code behind the view, run:
SHOW CREATE VIEW newsView
         The code it returns will probably be slightly different than the code you created, but it should do the same thing. It will include all of the optional CREATE VIEW attributes, which you didn't include in the example above. You should be able to copy and paste the code and change the CREATE VIEW to ALTER VIEW. Let's also JOIN the NewsCategories table so that we can see the CatName each news record is associated with, while SELECTing from our view. So it should look something like this:
ALTER ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `newsview` AS
SELECT n.newsID, n.catID, n.title, n.txt, c.catName FROM News AS n JOIN NewsCategories AS c ON c.catID=n.catID
          You can easily create and modify views using the Query Browser tool. If you're using the latest version of MySQL Query Browser, you should see your view listed along with your tables under your selected database in the right column. If this is the case, you can right click on the View and click Edit View.




















Thursday, May 10, 2012

oops interview questions and answers

1:What is Object Oriented Programming ?
       It is a problem solving technique to develop software systems. It is a technique to think real world in terms of objects. Object maps the software model to real world concept. These objects have responsibilities and provide services to application or other objects.  
OR
      Object-oriented programming is a method of programming based on a hierarchy of classes, and well-defined and cooperating objects.
2:What is a Class ? 
         A class describes all the attributes of objects, as well as the methods that implement the behavior of member objects. It is a comprehensive data type which represents a blue print of objects. It’s a template of object.
OR
          Class is a template for a set of objects that share a common structure and a common behavior.
 
3:What is an Object ? 
         It is a basic unit of a system. An object is an entity that has attributes, behavior, and identity. Objects are members of a class. Attributes and behavior of an object are defined by the class definition.
OR
        Object is an instance of a class. It has state,behaviour and identity. It is also called as an instance of a class.

5:What is the relation between Classes and Objects?
           They look very much same but are not same. Class is a definition, while object is instance of the class created. Class is a blue print while objects are actual objects existing in real world. Example we have class CAR which has attributes and methods like Speed, Brakes, Type of Car etc.Class CAR is just a prototype, now we can create real time objects which can be used to provide functionality.
6:What is an Abstract class ? 
         Abstract class defines an abstract concept which can not be instantiated and comparing o interface it can have some implementation while interfaces can not. Below are some
points for abstract class:-
=>We can not create object of abstract class it can only be inherited in a below class.
=> Normally abstract classes have base implementation and then child classes derive from the abstract class to make the class concrete.  
 
7:What is POLYMORPHISM in oop?
           Polymorphism literally means taking more than one form. Polymorphism is a characteristic of being able to assign a different behavior or value in a subclass, to something that was declared in a parent class. 
 for more details 
http://www.youtube.com/watch?v=PAMDmFXou5I&feature=related
8:What is meant by static binding?
     Static binding is a binding in which the class association is made during compile time. This is also called as Early binding.
9:What is meant by Dynamic binding?
     Dynamic binding is a binding in which the class association is not made until the object is created at execution time. It is also called as Late binding.
10: What is the use of friend function?
         Sometimes a function is best shared among a number of different classes. Such functions can be declared either as member functions of one class or as global functions. In either case they can be set to be friends of other classes, by using a friend specifier in the class that is admitting them. Such functions can use all attributes of the class which names them as a friend, as if they were themselves members of that class.
11: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.
12:Static Keyword
    * To implement static keyword functionality to the attributes or the methods will have to be prefix with static keyword.
    * Static properties or methods can be accessible without needing an instantiation of the class.
    * A property declared as static can not be accessed with an instantiated class object.
    * $this is not available inside the method declared as static.
    * Static properties cannot be accessed using the arrow operator ->.
    * Static properties can be accessed using the Scope Resolution Operator (::) operator.
 ClassName::$staticvar= $value;

Example:

class Box
{
   static private $color; 

   function __construct($value)
   {
if($value != "")
{
Box::$color = $value;
}
$this->getColor();
   }

   public function  getColor ()
   {
echo Box::$color;
   }
}

$a = new Box("RED");
$a = new Box("GREEN");
$a = new Box("");
?>

OUTPUT:
RED
GREEN
GREEN
13: What is Inheritance in OOPS?
  • Inheritance, together with encapsulation and polymorphism, is one of the three primary characteristics (concept) of object-oriented programming
  • Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes
  • The Class whose methods and variables are defined is called super class or base class
  • The Class that inherits methods and variables are defined is called sub class or derived class
  • Sometimes base class known as generalized class and derived class known as specialized class.
Benefits of using Inheritance
  • Once a behavior (method) or property is defined in a super class(base class),that behavior or property is automatically inherited by all subclasses (derived class).
  • Code reusability increased through inheritance
  • Inheritance provide a clear model structure which is easy to understand without much complexity
  • Using inheritance, classes become grouped together in a hierarchical tree structure
  • Code are easy to manage and divided into parent and child classes
8. What is Compile Time Polymorphism in OOPS?
         Compile time Polymorphism also known as method overloading
Method overloading means having two or more methods with the same name but with different signatures.

9. What is Run Time Polymorphism in OOPS?
     Run time Polymorphism also known as method overriding
Method overriding means having two or more methods with the same name , same signature but with different implementation.
10:Access modifier:
   OOP provides data-hiding capabilities with public, protected, and private data attributes and methods:
Public : A public variable or method can be accessed directly by any user of the class.
Protected : A protected variable or method cannot be accessed by users of the class but can be accessed inside a subclass that inherits from the class.
Private:A private variable or method can only be accessed internally from the class in which it is defined.
11:Serialization/UnSerialization:
    * Generates a storable representation of a value.
    * serialize() returns a string containing a byte-stream representation of any value that can be stored in PHP.
    * unserialize() can use this string to recreate the original variable values.
    * This process makes a storable representation of a value that is useful for storing or passing PHP values.
    * To make the serialized string into a PHP value again, use unserialize().

Before starting your serialization process, PHP will execute the __sleep function automatically. This is a magic function or method.
Before starting your unserialization process, PHP will execute the __wakeup function automatically. This is a magic function or method.
12:What can you Serialize and Unserialize?

    * Variables
    * Arrays
    * Objects
What cannot you Serialize and Unserialize?
    * Resource-type
13: What is a Virtual Function ?
     Virtual functions are normal member functions of a class, which can be over-ridden in the derived classes. The whole functionality can be replaced in the over-riding function
14:What is a virtual class?
        In multiple inheritance when a class D is derived by two base classes B and C and both base class is also inherite by same class A then then class D will get duplicate copy of uppper most base class A.In this case class A will declare as virtual class.
15:What is the difference between a virtual function and pure virtual function?
          The main difference is the body of function.
Vartual Function have a function body.
We define them as :
 Virtual int virFun();
          A pure virtual functions doesn't have a body.
We define them as:
 Virtual int myFun() = 0;
      Pure virtual functions have no body and MUST be overloaded in the derived classes. You cannot create an instance of a class having a pure virtual function, the need is to inherit from it and overload the all pure virtual functions.
16:Why destructor is not over loaded?
      Normally (in fact almost always) you never explicitly call the destructor, it is automatically called by the C++ frame work when the object is deleted/goes out of scope. Therefore you would not need to overload the destructor because the frame work always calls the default destructor.
17:Diversities between an abstract method & virtual method ?
           An Abstract method does not provide an implementation and forces overriding to the deriving class (unless the deriving class also an abstract class), where as the virtual method has an implementation and leaves an option to override it in the deriving class. Thus Virtual method has an implementation & provides the derived class with the option of overriding it. Abstract method does not provide an implementation & forces the derived class to override the method.
18:Can we declare private class in a Namespace?
          No. If you try to create a private class in a Namespace, Compiler will throw a compile time error “Namespace elements cannot be explicitly declared as private, protected, or protected internal”.
     Reason: The message says it all. Classes can only be declared as private, protected or protected internal when declared as nested classes, other than that, it doesn't make sense to declare a class with a visibility that makes it unusable, even in the same module. Top level classes cannot be private, they are "internal" by default, and you can just make them public to make them visible from outside your DLL.
19:What is the difference between superclass and subclass?
    A super class is a class that is inherited whereas sub class is a class that does the inheriting.
20:What is namespace?
    Namespaces allow us to group a set of global classes, objects and/or functions under a name. To say it somehow, they serve to split the global scope in sub-scopes known as namespaces.
The form to use namespaces is:
namespace identifier { namespace-body }
Where identifier is any valid identifier and namespace-body is the set of classes, objects and functions that are included within the namespace. For example:
namespace general { int a, b; } In this case, a and b are normal variables integrated within the general namespace. In order to access to these variables from outside the namespace we have to use the scope operator ::. For example, to access the previous variables we would have to put:
general::a general::b
The functionality of namespaces is specially useful in case that there is a possibility that a global object or function can have the same name than another one, causing a redefinition error.

22:What is friend function?
        As the name suggests, the function acts as a friend to a class. As a friend of a class, it can access its private and protected members. A friend function is not a member of the class. But it must be listed in the class definition.
Which recursive sorting technique always makes recursive calls to sort subarrays that are about half size of the original array?
Mergesort always makes recursive calls to sort subarrays that are about half size of the original array, resulting in O(n log n) time.

























Wednesday, May 9, 2012

php interview questions and answers for experienced

1:What is the value of $b in the following code?
    $a="5 USD";
    $b=10+$a;
    echo $b;
?>

Ans:15
2: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?
  In the get method the data made available to the action page ( where data is received ) by the URL so data can be seen in the address bar. Not advisable if you are sending login info like password etc.

In the post method the data will be available as data blocks and not as query string.
3:What is GPC?
G – Get
P – Post
C – Cookies
4:What are super global arrays?
All variables that come into PHP arrive inside one of several special arrays known collectively as the superglobals. They're called superglobal because they are available everywhere in your script, even inside classes and functions.
5:Give some example for super global arrays?
$GLOBALS
$_GET
$_POST
$_SESSION
$_COOKIE
$_REQUEST
$_ENV
$_SERVER
6:What's the difference between COPY OF A FILE & MOVE_UPLOAD_FILE in file uploading?

MOVE_UPLOAD_FILE :   This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.
If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.
Copy :Makes a copy of a file. Returns TRUE if the copy succeeded, FALSE otherwise.
7:When I do the following, the output is printed in the wrong order:

function myfunc($argument) {
        echo $argument + 10;
      }
      $variable = 10;
 echo "myfunc($variable) = " . myfunc($variable);

What's going on?
To be able to use the results of your function in an expression (such as concatenating it with other strings in the example above), you need to return the
value, not echo it.
8:What are the Formatting and Printing Strings available in PHP?
     
Function                     Description
printf()    :                 Displays a formatted string
sprintf()   :                 Saves a formatted string in a variable
fprintf()   :                 Prints a formatted string to a file
number_format()  :   Formats numbers as strings
9:Explain the types of string comparision function in PHP.
    
      Function              Descriptions
strcmp()             :Compares two strings (case sensitive)
strcasecmp()      :Compares two strings (not case sensitive)
strnatcmp(str1, str2) :Compares two strings in ASCII order, but
                                    any numbers are compared numerically
strnatcasecmp(str1, str2):Compares two strings in ASCII order,
                                          case insensitive, numbers as numbers
strncasecomp()  : Compares two strings (not case sensitive)
                            and allows you to specify how many characters
                             to compare
strspn()             : Compares a string against characters represented
                             by a mask
strcspn()           : Compares a string that contains characters not in
                            the mask
10:Explain soundex() and metaphone().
      soundex()
The soundex() function calculates the soundex key of a string. A soundex key is a four character long alphanumeric string that represent English pronunciation of a word. he soundex() function can be used for spelling applications.
$str = "hello";
echo soundex($str);
?>
metaphone()
The metaphone() function calculates the metaphone key of a string. A metaphone key represents how a string sounds if said by an English speaking person. The metaphone() function can be used for spelling applications.
echo metaphone("world");
?>
11:What do you mean range()?
      Starting from a low value and going to a high value, the range() function creates an array of consecutive integer or character values. It takes up to three arguments: a starting value, an ending value, and an increment value. If only two arguments are given, the increment value defaults to 1.
Example :
echo range(1,10); // Returns 1,2,3,4,5,6,7,8,9,10
?>
12:How to read and display a HTML source from the website url?
      $filename="http://www.kaptivate.in/";
$fh=fopen("$filename", "r");
while( !feof($fh) ){
$contents=htmlspecialchars(fgets($fh, 1024));
print "
$contents
";
}
fclose($fh);
?>13:What is properties of class?
Class member variables are called "properties". We may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
14:How to use HTTP Headers inside PHP? Write the statement through which it can be added?
                HTTP headers can be used in PHP by redirection which is written as:
The headers can be added to HTTP response in PHP using the header(). The response headers are sent before any actual response being sent. The HTTP headers have to be sent before taking the output of any data. The statement above gets included at the top of the script.
15:Why we used PHP?
Because of several main reason we have to use PHP. These are:
1.PHP runs on many different platforms like that Unix,Linux and Windows etc.
2.It codes and software are free and easy to download.
3.It is secure because user can only aware about output doesn't know how that comes.
4.It is fast,flexible and reliable.
5.It supports many servers like: Apache,IIS etc.
16:Arrays  in PHP?
 Create array in PHP to solved out the problem of writing same variable name many time.In this we create a array of variable name and enter the similar variables in terms of element.Each element in array has a unique key.Using that key we can easily access the wanted element.Arrays are essential for storing, managing and operating on sets of variables effectively. Array are of three types:
1.Numeric array
2.Associative array
3.Multidimensional array
 Numeric array is used to create an array with a unique key.Associative array is used to create an array where each unique key is associated with their value.Multidimensional array is used when we declare multiple arrays in an array.
17:What is foreach loop in  php?
foreach:Uses, When When we want execute a block of code for each element in an array.
Syntax:
foreach (array as value)
{
    code will be executed;
}
eg:
$arr=array("one", "two", "three");
foreach ($arr as $value)
{
  echo "Value: " . $value . "
";
}

?>
18:How we used $_get and $_post variable in PHP?
   We know that when we use $_GET variable all data_values are display on our URL.So,using this we don't have to send secret data (Like:password, account code).But using we can bookmarked the importpage.
 We use $_POST variable when we want to send data_values without display on URL.And their is no limit to send particular amount of character.
Using this we can not bookmarked the page.
19:Why we use $_REQUEST variable?
We use $_REQUEST variable in PHP to collect the data_values from $_GET,$_POST and $_COOKIE variable.
Example:
R4R Welcomes You .

You are years old!
20:How we handle errors in PHP?Explain it?
In PHP we can handle errors easily.Because when error comes it gives error line with their respective line and send error message to the web browser.
When we creating any web application and scripts. We should handle errors wisely.Because when this not handle properly it can make bg hole in security.
In PHP we handle errors by using these methods:
1.Simple "die()" statements
2.Custom errors and error triggers
3.Error reporting
21: How we use Custom errors and error triggers error handling method in PHP?
In Custom errors and error triggers,we handle errors by
using self made functions.
1.Custom errors : By using this can handle the multiple
errors that gives multiple message.
Syntax:
set_error_handler(\\\"Custom_Error\\\");
In this syntax if we want that our error handle, handle
only one error than we write only one argument otherwise
for handle multiple errors we can write multiple arguments.

Example:
//function made to handle errorfunction
custom_Error($errorno, $errorstr) 
{  
   echo \\\"Error: [$errorno] $errorstr\\\";  }
//set error handler like that
set_error_handler(\\\"custom_Error\\\");
//trigger to that error
echo($verify);?>

2.error trigger : In PHP we use error trigger to handle
those kind of error when user enter some input data.If
data has an error than handle by error trigger function.
Syntax:

$i=0;if ($i<=1)
{
trigger_error(\\\"I should be greater than 1 \\\");
}
?>
In this trigger_error function generate error when i is
less than or greater than 1.
22:What do you understand about Exception Handling in PHP?
In PHP 5 we introduce a Exception handle to handle run time exception.It is used to change the normal flow of the code execution if a specified error condition occurs.
An exception can be thrown, and caught("catched") within PHP. Write code in try block,Each try must have at least one catch block. Multiple catch blocks can be used to catch different classes of exceptions.
Some error handler methods given below:
1.Basic use of Exceptions
2.Creating a custom exception handler
3.Multiple exceptions
4.Re-throwing an exception
5.Setting a top level exception handler
23: What is the difference b/n 'action' and 'target' in form tag?
Action:
    Action attribute specifies where to send the form-data when
a form is submitted.
    Syntax:
    Example:
action="formValidation.php">
Target:
    The target attribute specifies where to open the action URL.
     Syntax:
        Value:
         _blank – open in new window
        _self- Open in the same frame as it was clicked
        _parent- Open in the parent frameset
        _top- Open in the full body of the window
        Framename- Open in a named frame24:What do you understand about PHP accelerator ?
Basically PHP accelerator is used to boost up the performance of PHP programing language.We use PHP accelerator to reduce the server load and also use to enhance the performance of PHP code near about 2-10 times.In one word we can say that PHP accelertator is code optimization technique.
26:How we use ceil() and floor() function in PHP?
ceil() is use to find nearest maximum values of passing value.
Example:
$var=6.5;
$ans_var=ceil($var);
echo $ans_var;
Output:
7
floor() is use to find nearest minimum values of passing value.
Example:
$var=6.5
$ans_var=floor($var);
echo $ans_var; 
Output:
6
27:What is the answer of following code
echo 1< 2 and echo 1 >2 ?

Output of the given code are given below:
echo 1<2
output: 1
echo 1>2
output: no output
28: What is the difference b/w isset and empty?
The main difference b/w isset and empty are given below:
isset: This variable is used to handle functions and checked a variable is set even through it is empty.
empty: This variable is used to handle functions and checked either variable has a value or it is an empty string,zero0 or not set at all.


 










 






 

Tuesday, May 8, 2012

php interview qustion and answer part3


58:What is the use of “Final class” and can a final class be an abstract?
The “Final” keyword is used to make the class uninheritable. So the class or it’s methods can not be overridden.
final class Class1 {
    // ...
}
class FatalClass extends Class1 {
    // ...
}
 $out= new FatalClass();
An Abstract class will never be a final class as an abstract class must be extendable.
59:What are the two new error levels introduced in PHP5.3?
      E_DEPRECATEDThe E_DEPRECATED error level is used to indicate that a function or feature has been deprecated.E_USER_DEPRECATED
The E_USER_DEPRECATED level is intended for indicating deprecated features in user code, similarly to the E_USER_ERROR and E_USER_WARNING levels.
60:Where is the sessions are stored?
      Sessions are stored in server side and it is accessed by a unique id which is known as the session-id where each user/visitor is assigned when they access your website.
61:How the session-id is propagated within your website?
Basically, there are 2 methods either store it in a cookie or propagated in the URL.

62:which of the following will not combine string $s1 and $s2 into a single string?
$s1 = 'a';
$s2 = 'b';
A. $s1 + $s2
B. "{$s1}{$s2}"
C. $s1.$s2
D. implode('', array($s1,$s2))
E. All of the above combine the strings
You can not concatenate 2 string using “+”. The answer will be “0″; so here the answer is A.

63:Consider the following script. What line of code should be inserted in the marked location in order to display the string php when this script is executed?
$alpha = 'abcdefghijklmnopqrstuvwxyz';
$letters = array(15, 7, 15);
foreach($letters as $val) {
/* What should be here */
}
A. echo chr($val);
B. echo asc($val);
C. echo substr($alpha, $val, 2);
D. echo $alpha{$val};
E. echo $alpha{$val+1}

An array can be accessed like this as well. $alpha{$val} 
64:Using variable interpolation how we can print the following String?

“I am visiting the php interview questions website”.
The word “question” is inside a variable,
$a = ‘question’;
Answer is just,
echo “I am visiting the php interview {$a}s website”;

strings and variable interpolation
Basically there are 2 methods how we can define strings,
- Simple strings
- Complex strings
 65:Which will print correctly in to the browser as “Hello World” followed by a new line.

a) echo “Hello $what\n”;
b) echo ‘Hello $what\n’;
$what = “World”;

Is it a) or b) ?

The answer is “a”. That is because simple string will print almost all characters literally, where complex string allows special escape sequences to insert special characters.
66:What are the steps that you can take to prevent form hijacking/sql injection in PHP?
Make register_globals to off to prevent Form Injection with malicious data.
Set Error_reporting to E_ALL so that all variables will be intialized before using them.
Practice of using htmlentities(), strip_tags(), utf8_decode() and addslashes() for filtering malicious data in php
Make practice of using mysql_escape_string() in mysql.
Sql injection ->  is an attack that can be made directly to a database table, where the attacker can edit the original intended sql statement to one of his own. This is caused by lack of unverified or unsanitized user input.
67:Predefined  classes in php ?
Directory
stdClass
__PHP_Incomplete_Class
exception
php_user_filter

Directory 

The class from which dir is instantiated.
stdClass
Created by typecasting to object.
__PHP_Incomplete_Class
Possibly created by unserialize().
Predefined classes as of PHP 5
These additional predefined classes were introduced in PHP 5.0.0.
exception
php_user_filter
Closure
The predefined final class Closure was introduced in PHP 5.3.0. It is used for internal implementation of anonymous functions.
The class has a constructor forbidding the manual creation of the object (issues E_RECOVERABLE_ERROR) and the __invoke method with the calling magic.
68:How do we get to know about browser properties?
     get_browser() attempts to determine the capabilities of the user’s browser.
or echo $_SERVER['HTTP_USER_AGENT']]
69:What is the difference between split() vs explode()?
    Split() is used to split a string using a regular expression while explode() is used to split a string using another string.
 70:What is the method we can use to hold the output to the browser?
Ob_start(), This will redirect the out put to a buffer until ob_end_flush() or any other out put supportive method will be called.
 71:What is the difference between session_register and $_session?
session_register() is used for register one or more global variables with the current session. While $_SESSION[] array is used for storing one or more variables with in the current session array. session_register() depends upon register_global is enable.
72:Which is the best way to determine of an array element’s existence?
array_key_exists()

It is because isset returns false even though if an array element is defined as a NULL.
73:What methods can be used to determine whether an array element exits or not?
array_key_exist or isset() methods can be used.
74:How to identify whether a variable contains an array?
is_array() function can be used.
75:Which will execute faster POST or GET?.
       GET transfer data to the server using URL whereas POST transfer data using form collection which is added to the request by the browser. We can send at most 1024 bytes using URL hence there is upper limit for GET method POST method can transfer large amount of data where upper limit is imposed by web server which is about 2MB data is shown to the user in GET method.
Get is faster but not safe.
76. How can I make a script that can be bilanguage (supports Eglish, German)?
         You can change charset variable in above line in the script to support bilanguage
77:What is a CAPTCHA and when do you use it? 
       CAPTCHA is the short form of Completely Automated Public Turing Test. It’s a step taken to ensure that a feature is not abused in a way it’s not meant to be used. We use CAPTCHAS for general form submissions, registrations, user generated content etc.
78:Will comparison of string “10″ and integer 11 work in PHP?
         Yes, internally PHP will cast everything to the integer type, so numbers 10 and 11 will be compared.
79:How can we increase the execution time of a php script?
         By the use of void set_time_limit(int seconds)
Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini. If seconds is set to zero, no time limit is imposed.
       When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.
80:What is the difference between echo and print?
echo:
Is a command only.
Faster than print
print:
Is a function.
It will return true(1) or false(0) or some values.
81:Why do we put @ symbol before any variable?
       @ symbol when placed before any variable will hide notices and warnings  which are generated when trying to access an undefined variable.
82:How can you avoid execution time out error while fetching record from mysql?
         set_time_limit -- Limits the maximum execution time. It must be increased.
set_time_limit(0);If you set to 0 you say that there is not limit.
83:What do you need to do to improve the performance (speedy execution) for the script you have written?
       There are many things to be considered.If your application based on Database you should think about re-factoring queries try to use high performance queries (Use EXPLAIN to monitor the amount of records retrieved for each query. You can use UNIQUE LIMITWHERE to filter the no of records returned).And also you should be aware of fine tuning configuration for your needs.
In PHP you should use native functions instead of aliases. And also you should choose best function for the job. If you are going to do simple string replace use str_replace than ereg_replace. Use is_int() instead ofis_integer().Use DBG or xdebug to profile your scripts find the bottle neck function and try to re factor if possible.
 84: What Is a Session?
     HTTP is a stateless protocol. This means that each
request is handled independently of all the other
requests and it means that a server or a script cannot
remember if a user has been there before. However,
knowing if a user has been there before is often
required and therefore something known as cookies
and sessions have been implemented in order to cope
with that problem.
A session is a logical object created by the PHP engine to allow
you topreserve data across subsequent HTTP requests.There is
only one session object available to your PHP scripts at anytime.
Data saved to the session by a script can be retrieved by the
same script or another script when requested from the same visitor.
Sessions are commonly used to store temporary data to allow
multiplePHP pages to offer a complete functional transaction for the same visitor.
85 :The Difference Between Cookies and Sessions
     The main difference between cookies and sessions is that cookies are stored in the user's browser, and sessions are not.
A cookie can keep information in the user's browser until deleted. If a person has a login and password, this can be set as a cookie in their browser so they do not have to re-login to your website every time they visit. You can store almost anything in a browser cookie. The trouble is that a user can block cookies or delete them at any time. If, for example, your website's shopping cart utilized cookies, and a person had their browser set to block them, then they could not shop at your website.
Sessions are not reliant on the user allowing a cookie. They work instead like a token allowing access and passing information while the user has their browser open. The problem with sessions is that when you close your browser you also lose the session. So, if you had a site requiring a login, this couldn't be saved as a session like it could as a cookie, and the user would be forced to re-login every time they visit.
The Key difference would be cookies are stored in your hard disk whereas a session aren't stored in your hard disk. Sessions are basically like tokens, which are generated at authentication. A session is available as long as the browser is opened.
Ans2:
1. Cookies can store only "string" datatype
2. They are stored at Client side
3. Cookie is non-secure since stored in text format at
client side
4. Cookies may or may not be individual for every
client
5. Due to cookies network traffic will increase.Size
of cookie is limited to 40 and number of cookies to be used
is restricted to 20.
6. Only in few situations we can use cookies because
of no security
7. We can disable cookies
8. Since the value is string there is no security
9. We have persistent and non-persistent cookies
Session
1. Session can store any type of data because the
value is of datatype of "object"
2. These are stored at Server side
3. Session are secure because it is stored in binary
format/encrypted form and it gets decrypted at server

4. Session is independent for every client i.e
individual for every client

5. There is no limitation on size or number of
sessions to be used in an application

6. For all conditions/situations we can use sessions
7. we cannot disable the sessions.Sessions can be used
without cookies also(by disabling cookies)

8. The disadvantage of session is that it is a
burden/overhead on server

9. Sessions are called as Non-Persistent cookies
because its life time can be set manually
Imp Note:
        The session ID is stored in two places:on the client using a
temporary cookie, and on the server in a flat file or a database.
By using the session ID to put a name to every request
received, a developer can identify which client initiated which
request,and track and maintain client-specific information
in session variables..
             Typically,  use a session to store values that are
required over the course of a single visit, and a cookie
to store more persistent data that is used over multiple visits.
If you open up two browser windows and request the  same
page in each one, PHP will maintain and increment individual
session counters for each browser instance. The session ID is
used to identify which client made which request, and
recreate the prior saved environment for each individual session.
         It’s important to note that the call to session_start()
must appear first, This is because the PHP session handler
internally uses in-memory cookies to store session data, and the
cookie creation headers must be transmitted to the client
browser before any output.If you ever see an error like
this in one of your session-enabled pages:
       Remember that $_SESSION is a superglobal, so you can use
it inside and outside functions without needing to declare it as
global first
85:How session will work?
    When a user first enters the session-based application by making a request to a page that starts a session, PHP generates a session ID and creates a file that stores the session-related variables. PHP sets a cookie to hold the session ID in the response the script generates. The browser then records the cookie and includes it in subsequent requests.

Starting a Session

  PHP provides a session_start( ) function that creates a new session and subsequently identifies and establishes an existing one. Either way, a call to the session_start( ) function initializes a session.
 The first time a PHP script calls session_start( ), a session identifier is generated, and, by default, a Set-Cookie header field is included in the response.The response sets up a session cookie in the browser with the name PHPSESSID and the value of the session identifier. The PHP session management automatically includes the cookie without the need to call to the setcookie( ) or header( ) functions.
The session identifier (ID) is a random string of 32 hexadecimal digits, such as fcc17f071bca9bf7f85ca281094390b4. As with other cookies, the value of the session ID is made available to PHP scripts in the $HTTP_COOKIE_VARS associative array and in the $PHPSESSID variable.
When a new session is started, PHP creates a session file. With the default configuration, session files are written in the /tmp directory using the session identifier, prefixed with sess_, for the filename. The filename associated with our example session ID is /tmp/sess_fcc17f071bca9bf7f85ca281094390b4.

 Using Session Variables

    Variables need to be registered with the session_register( ) function that's used in a session. If a session has not been initialized, the session_register( ) function calls session_start( ) to open the session file. Variables can be registered -- added to the session file -- with the session_register( ) call as follows:
session_register("foo");
$foo = "bar"
Note that it is the name of the variable that is passed to the session_register( ) function, not the variable itself. Once registered, session variables are made persistent and are available to scripts that initialize the session. PHP tracks the values of session variables and saves their values to the session file: there is no need to explicitly save a session variable before a script ends. In the previous example, the variable $foo is automatically saved in the session store with its value bar.
Variables can be removed from a session with the session_unregister( ) function call; 

Ending a Session

At some point in an application, sessions may need to be destroyed. For example, when a user logs out of an application, a call to the session_destroy( ) function can be made. A call to session_destroy( ) removes the session file from the system but doesn't remove the PHPSESSID cookie from the browser

Boolean session_is_registered(string variable_name)
Returns true if the named variable has been registered with the current session and false otherwise. Using this function to test if a variable is registered is a useful way to determine if a script has created a new session or initialized an existing one. 
 session_unset( )
Unsets the values of all session variables. This function doesn't unregister the actual session variables. A call to session_is_registered( ) still returns true for the session variables that have been unset.

Security issues

     Because the cookies are transferred unencrypted (unless you are using SSL) and because they will be stored in plain text on the client computer, it is not advised that you store any sensitive information in the cookies.a malicious user will be able to execute any arbitrary Javascript code on the client machine without the user or you knowing it. The reason why this is a problem regarding cookie and session security is that cookies will be default be able to be viewed by Javascript.
here are a number of different ways you could deal with this. The first and most obvious one is to properly escape all output coming from a user. The function htmlentities() can take care of that. Another way is by setting the httponly parameter for your cookies. In that way the browser will not give Javascript access to the information that cookie holds.
If you are using sessions, then you can call session_regenerate_id() on every request. By doing that the user will get a new session ID each time and it means that if a malicious user ever gets a session id, chances are it will be invalid by the time he gets to try it because it changes often


85:How do I find out the number of parameters passed into function. ?

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

86:How to set cookies?

setcookie('variable','value','time');
variable - name of the cookie variable
value - value of the cookie variable
time - expiry time
Example: setcookie('Test',$i,time()+3600);
Test - cookie variable name
$i - value of the variable 'Test'
time()+3600 - denotes that the cookie will expire after an one hour 

87: what is Magic methods in php?

_construct( ):Called when instantiating an object
__destruct( ):Called when deleting an object
__get( ):Called when reading from a nonexistent property
__set( ):Called when writing to a nonexistent property
__call( ):Called when invoking a nonexistent method
__toString( ):Called when printing an object (for eg:  converting an object to strings)
__clone( ):Called when cloning an object (copying object) 

88:Explain Constructors and Destructors in php?

__construct( )
Called when instantiating an object

__destruct( )
Called when deleting an object


Constructors and destructors are functions that are called when a new instance of an object is created (constructors) and/or destroyed (destructors). Their

primary purpose is to allow for a means to initialize and clean up after an object during its use.
Constructors can accept parameters, which are assigned to specific object fields at
creation time.

Constructors can call class methods or other functions.
constructors are intuitively useful for initializing class properties,

Class constructors can call on other constructors, including those from the class parent.

One classic example is a class to access a database back end, where a constructor could make the connection to the database while the destructor closes it.

PHP 4  Constructors
In PHP 4, only constructors were available and were created by defining a function whose name was the same as the class itself:

     class MyClass {
          function MyClass($param) {
               echo "Created a new instance of MyClass !";
          }
     }
     $Myinstance = new MyClass;
?>


In PHP 5, this concept has been changed PHP 5 or (5>=) now uses a unified constructor function named __construct(). PHP 5 or (5>=) also uses a unified

__destruct() method for its destructors.

PHP 5 Constructors and Destructors


     class MyClass {
          function __construct($p) {
               echo "Created a new instance of MyClass!";
          }
          function __destruct() {
               echo "Destroyed this instance of MyClass";
          }
     }
     $Myinstance = new MyClass("value");
   
?>

89:How many HTTP headers will send to a web page(client side) from server when you use sessions  (session_start()) in php ?
  
There are three HTTP headers included in the response:
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
90:what are the advantages of storing sessions in database?
If you store a session in a database you have several advantages:

@ Improving the security because on many hosting packages (shared host)
PHP uses the same path for storing sessions for all the users,
somewhere that is not in your folders.
@ You can track who is online etc.
@ For application that are running on multiple servers, you can store
all the session data in one database.
The real beauty of this approach is that you don't have to modify your code or the way you use sessions in any way. $_SESSION still exists and behaves the
same way, PHP still takes care of generating and propagating the session identifier, and changes made to session configuration directives still apply. All
you have to do is call this one function.
You must call session_set_save_handler() prior to calling session_start(), but you can define the functions themselves anywhere.
The function is called session_set_save_handler(), and it takes six arguments,

1. Opening the session data store
2. Closing the session data store
3. Reading session data
4. Writing session data
5. Destroying all session data
6. Cleaning out old session data
91: what are the security tips you should know before developing php/mysql web pages ?
 1. Do not trust user input.
2. Validate user input on the server side.
3. Do not use user input directly in your MySQL queries.
4. Don't put integers in quotes In your MySQL queries.
5. Always escape the output using php built in functions.
6. When uploading files, validate the file mime type using php.
7. If you are using 3rd party code libraries, be sure to keep them up to date.
8. Give your database users just enough permissions.
9. Do not allow hosts other than localhost to connect to your database.
10. Your library file extensions should be PHP.
11. Have register globals off or define your variables first
12. Keep PHP itself up to date (use latest version php5 or above)

92:What is curl?  

CURL is Client URL Library. u need the libcurl package in the server
PHP supports libcurl, a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.

93:How will u initialize a curl session? 

curl_init() - parameter source URL
curl_setopt(),
curl_exec(),
curl_close()
See also,
curl_multi_init  ( void  )
curl_multi_add_handle($mh,$ch1);

94:what is GD?
PHP is not limited to creating just HTML output. It can also be used to create and manipulate image files in a variety of different image formats, includinggif, png, jpg, wbmp, and xpm. Even more convenient, PHP can output image streams directly to a browser. You will need to compile PHP with the GD library ofimage functions for this to work. GD and PHP may also require other libraries, depending on which image formats you want to work with.

95:How can I send variables from a PHP script to another URL using POST without using forms and hidden variables?

You can open an HTTP socket connection and send HTTP POST commands. Here is
an example :
// Generate the request header
$ReqHeader =
"POST $URI HTTP/1.1n".
"Host: $Hostn".
"Content-Type: application/x-www-form-urlencodedn".
"Content-Length: $ContentLengthnn".
"$ReqBodyn";
// Open the connection to the host
$socket fsockopen($Host80, &$errno, &$errstr);
if (!
$socket)

$Result["errno"] = $errno;
$Result["errstr"] = $errstr;
return 
$Result;
}
$idx 0;
fputs($socket$ReqHeader);
while (!
feof($socket))

$Result[$idx++] = fgets($socket128);
}
//-------------------------------------------
?>

Or you can use the cURL extensions for PHP (http://curl.haxx.se). Once you build it and compile their support into PHP, it is fairly easy to do posting stuff (even over https):
$URL="www.mysite.com/test.php";
$ch curl_init();   
curl_setopt($chCURLOPT_URL,"https://$URL"); 
curl_setopt($chCURLOPT_POST1);
curl_setopt($chCURLOPT_POSTFIELDS"Data1=blah&Data2=blah");curl_exec ($ch);    
curl_close ($ch);
?>

This will have the net effect of posting your data to the $URL site, without any header hacking.
You can also do other nifty things with cURL, like retrieve the HTML into variables and scrape through it for neat functionality.

95: How to count number of parameters given in URL by POST?

echo count ($_POST);
?>

95:How to output a number with leading zero's?

$number = 15;
printf("%05d", $number);
?>