Web Design HTML Interview Questions & Answers

Web Design HTML Interview Questions & Answers
1) Intrepret this statement: <strong>Michelle</strong>
a) It makes Michelle strong
b) It highlights Michelle as being strong
c) It will print out Michelle in bold font – correct answer
2) Tables can be nested (table inside of another table).
a) True – correct answer
b) False
3) Which is correct?
a) <b>Click Here<b>
b) <strong>Click Here<strong>
c) <b>Click Here</b> – correct answer
d) </strong>Click Here</strong>
4) Which of the following is a two sided tag?
a) DT
b) LI
c) DD
d) DL – correct answer
5) The Browser applies the feature of a tag until it encounters_____tag.
a) Quit
b) Closing – correct answer
c) Exit
d) Anti
e) Deactivate
6) _______are the HTML codes that control the apearance of the document contents
a) Tags – correct answer
b) Codas
c) Slashes
d) Properties
e) Code
7) What are the genral syntax for inline image?
a) src=img
b) src=image
c) img=file
d) img src=file – correct answer
e) image src=file
8) An HTML_____takes text in one format and changes it to HTML code.
a) Browser
b) Editor
c) Converter – correct answer
d) Processor
e) Parser
9) To create a link to an anchor, you use the______property in A tag.
a) Name
b) Tag
c) Link
d) Href – correct answer
10) HTML Tags are case sensitive.
a) True
b) False – correct answer
11) Relative path make your hypertext links______.
a) Portable – correct answer
b) Discrete
c) Uniform
12) A_____structure starts with a general topic that includes link to more specific topics.
a) Hierarchical – correct answer
b) Linear
c) Mixed
13) Which of the following path is supported by HTML?
a) Ralative
b) Defererenced
c) Absolute and Relative – correct answer
14) You cannot designate an inline image as a hypertext link.
a) True
b) False – correct answer
15) Because each computer differs in terms of what fonts it can display, each individual browser determines how text is to be displayed.
a) True – correct answer
b) False
16) You do not have to connect to the internet to verify changes to a Web page on your computer.
a) True – correct answer
b) False
17) You can combine structures e.g, linear and hierarchical.
a) True – correct answer
b) False
18) What is HTML stands for?
a) Hypertext Mailing List
b) Hypertext Mark Language
c) Hypertext Markup Language – correct answer
19) What is the tag for an inline frame?
a) Iframe – correct answer
b) Inframe
c) frame
d) inlineframe
20) Within the MAP tag, you use the AREA tag to specify the areas of the image that will act as a hotspot.
a) True – correct answer
b) False
21) Can you create an e-mail form with auto responder using form action
a) Yes
b) No – correct answer
22) What is the most widely use e-mail form script?
a) ASP
b) PHP – correct answer
c) Perl CGI
d) JSP
23) There are_____color names recognized by all version of HTML.
a) 6
b) 8
c) 256
d) 16 – correct answer
24) Software programs, like your Web browser, use a mathemathical approach to define color.
a) True – correct answer
b) False
25) If you want to increase the font size by 2 relative to the sorounding text, you enter +2 in the tag.
a) True – correct answer
b) False
26) What operator makes converts 00110011 into 11001100?
a) ~ – correct answer
b) !
c) &
d) |
27) The default statement of a switch is always executed.
a) True
b) False – correct answer
28) H1 is the smallest header tag.
a) True
b) False – correct answer
29) The page title is inside the____tag.
a) Body
b) Head – correct answer
c) Division
d) Table
30) _____refers to the way the GIF file is saved by the graphics software.
a) Dithering
b) Interlacing – correct answer
c) Balancing


MySQL Technical Interview Questions – part 3

What is a Database system?

The database and DBMS software together is called as Database system.


Advantages of DBMS?

  • Redundancy is controlled.
  • Unauthorised access is restricted.
  • Providing multiple user interfaces.
  • Enforcing integrity constraints.
  • Providing backup and recovery.

Disadvantage in File Processing System?

  • Data redundancy & inconsistency.
  • Difficult in accessing data.
  • Data isolation.
  • Data integrity.
  • Concurrent access is not possible.
  • Security Problems.

Describe the three levels of data abstraction?

The are three levels of abstraction:

  • Physical level: The lowest level of abstraction describes how data are stored.
  • Logical level: The next higher level of abstraction, describes what data are stored in database and 

             what relationship among those data.

  • View level: The highest level of abstraction describes only part of entire database.

Define the “integrity rules”

There are two Integrity rules.

  • Entity Integrity: States that “Primary key cannot have NULL value”
  • Referential Integrity: States that “Foreign Key can be either a NULL value or 

               should be Primary Key value of other relation.


    What is Data Independence?

    Data independence means that “the application is independent of the storage structure and access strategy of data”.

    In other words, The ability to modify the schema definition in one level should not affect the schema

    definition in the next higher level.
    Two types of Data Independence:

    • Physical Data Independence: Modification in physical level should not affect the logical level.
    • Logical Data Independence: Modification in logical level should affect the view level.



    What is a view? How it is related to data independence?

    A view may be thought of as a virtual table, that is, a table that does not really exist in its own right

    but is instead derived from one or more underlying base table.

    In other words, there is no stored file that direct represents the view instead a definition of view is stored in data dictionary.
    Growth and restructuring of base tables is not reflected in views.

    Thus the view can insulate users from the effects of restructuring and growth in the database.

    Hence accounts for logical data independence.


    What is Data Model?

    A collection of conceptual tools for describing data, data relationships data semantics and constraints.


    What is E-R model?

    This data model is based on real world that consists of basic objects called entities and of relationship among these objects.

    Entities are described in a database by a set of attributes.


    What is Object Oriented model?

    This model is based on collection of objects. An object contains values stored in instance variables with in the object.

    An object also contains bodies of code that operate on the object. These bodies of code are called methods.

    Objects that contain same types of values and the same methods are grouped together into classes.



    What is an Entity?

    It is a ‘thing’ in the real world with an independent existence.

    What is an Entity type?

    It is a collection (set) of entities that have same attributes.

    What is an Entity set?

    It is a collection of all entities of particular entity type in the database.

    What is Weak Entity set?

    An entity set may not have sufficient attributes to form a primary key, and its primary key compromises of its partial key

    and primary key of its parent entity, then it is said to be Weak Entity set.

    What is an attribute?

    It is a particular property, which describes the entity.

    What is a Relation Schema and a Relation?

    A relation Schema denoted by R(A1, A2, …, An) is made up of the relation name R and the list of attributes Ai that it contains.

    A relation is defined as a set of tuples. Let r be the relation which contains set tuples (t1, t2, t3, …, tn).

    Each tuple is an ordered list of n-values t=(v1,v2, …, vn).

    What is degree of a Relation?

    It is the number of attribute of its relation schema.

    What is Relationship?

    It is an association among two or more entities.

    What is Relationship set?

    The collection (or set) of similar relationships.

    What is Relationship type?

    Relationship type defines a set of associations or a relationship set among a given set of entity types.

    What is DDL (Data Definition Language)?

    A data base schema is specifies by a set of definitions expressed by a special language called DDL.

    What is VDL (View Definition Language)?

    It specifies user views and their mappings to the conceptual schema.

    What is SDL (Storage Definition Language)?

    This language is to specify the internal schema. This language may specify the mapping between two schemas.

    What is Data Storage – Definition Language?

    The storage structures and access methods used by database system are specified by a set of definition

    in a special type of DDL called data storage-definition language.

    What is DML (Data Manipulation Language)?

    This language that enable user to access or manipulate data as organised by appropriate data model.

    • Procedural DML or Low level: DML requires a user to specify what data are needed and how to get those data.
    • Non-Procedural DML or High level: DML requires a user to specify what data are needed without specifying 

                     how to get those data.

      What is DDL Interpreter?

      It interprets DDL statements and record them in tables containing metadata.

      What is normalization?

      It is a process of analysing the given relation schemas based on their Functional Dependencies (FDs)

      and primary key to achieve the properties

      • Minimizing redundancy
      • Minimizing insertion, deletion and update anomalies.
      What is Functional Dependency?

      A Functional dependency is denoted by X Y between two sets of attributes X and Y that are subsets of R specifies a constraint

      on the possible tuple that can form a relation state r of R.

      The constraint is for any two tuples t1 and t2 in r if t1[X] = t2[X] then they have t1[Y] = t2[Y].

      This means the value of X component of a tuple uniquely determines the value of component Y.

      What is Multivalued dependency?

      Multivalued dependency denoted by X Y specified on relation schema R, where X and Y are both subsets of R,

      specifies the following constraint on any relation r of R: if two tuples t1 and t2 exist in r such that t1[X] = t2[X]

      then t3 and t4 should also exist in r with the following properties

      • t3[x] = t4[X] = t1[X] = t2[X]
      • t3[Y] = t1[Y] and t4[Y] = t2[Y]
      • t3[Z] = t2[Z] and t4[Z] = t1[Z]

      where [Z = (R-(X U Y)) ]

      What is Lossless join property?

      It guarantees that the spurious tuple generation does not occur with respect to relation schemas after decomposition.

      What is 1 NF (Normal Form)?

      The domain of attribute must include only atomic (simple, indivisible) values.

      What is Fully Functional dependency?

      It is based on concept of full functional dependency. A functional dependency X Y is full functional dependency

      if removal of any attribute A from X means that the dependency does not hold any more.

      What is 2NF?

      A relation schema R is in 2NF if it is in 1NF and every non-prime attribute A in R is fully functionally dependent

      on primary key.

      What is 3NF?

      A relation schema R is in 3NF if it is in 2NF and for every FD X A either of the following is true

      • X is a Super-key of R.
      • A is a prime attribute of R.

      In other words, if every non prime attribute is non-transitively dependent on primary key.

      What is BCNF (Boyce-Codd Normal Form)?

      A relation schema R is in BCNF if it is in 3NF and satisfies an additional constraint that for every FD X A, X

      must be a candidate key.

      What is 4NF?

      A relation schema R is said to be in 4NF if for every Multivalued dependency X Y that holds over R, one of following is true

        • X is subset or equal to (or) XY = R.
        • X is a super key.
      What is 5NF?

      A Relation schema R is said to be 5NF if for every join dependency {R1, R2, …, Rn} that holds R, one the following is true

        • Ri = R for some i.
        • The join dependency is implied by the set of FD, over R in which the left side is key of R.
      What are partial, alternate,, artificial, compound and natural key?

      Partial Key:
      It is a set of attributes that can uniquely identify weak entities and that are related to same owner entity.

      It is sometime called as Discriminator.
      Alternate Key:
      All Candidate Keys excluding the Primary Key are known as Alternate Keys.
      Artificial Key:
      If no obvious key, either stand alone or compound is available, then the last resort is to simply create a key,

      by assigning a unique number to each record or occurrence. Then this is known as developing an artificial key.

      Compound Key:
      If no single data element uniquely identifies occurrences within a construct, then combining

      multiple elements to create a unique identifier for the construct is known as creating a compound key.
      Natural Key:
      When one of the data elements stored within a construct is utilized as the primary key, then it is called the natural key.

      What is indexing and what are the different kinds of indexing?

      Indexing is a technique for determining how quickly specific data can be found.

      • Binary search style indexing
      • B-Tree indexing
      • Inverted list indexing
      • Memory resident table
      • Table indexing
      What is meant by query optimization?

      The phase that identifies an efficient execution plan for evaluating a query that has the least

      estimated cost is referred to as query optimization.

      What is a Phantom Deadlock?

      In distributed deadlock detection, the delay in propagating local information might cause the deadlock

      detection algorithms to identify deadlocks that do not really exist. Such situations are called phantom deadlocks

      and they lead to unnecessary aborts.

      What is “transparent DBMS”?

      It is one, which keeps its Physical Structure hidden from user.

      What is database Trigger?

      A database trigger is a PL/SQL block that can defined to automatically execute for insert, update,

      and delete statements against a table. The trigger can e defined to execute once for the entire statement

      or once for every row that is inserted, updated, or deleted. For any one table, there are twelve events for

      which you can define database triggers. A database trigger can call database procedures that are also written in PL/SQL.

      A B C is a set of attributes. The functional dependency is as follows

      AB -> B
      AC -> C
      C -> B
      a) is in 1NF
      b) is in 2NF
      c) is in 3NF
      d) is in BCNF

      (a) is in 1NF since (AC)+ = { A, B, C} hence AC is the primary key. Since C B is a FD given, where neither C is a Key

      nor B is a prime attribute, this it is not in 3NF. Further B is not functionally dependent on key AC thus it is not in 2NF.

      Thus the given FDs is in 1NF.

      What is Storage Manager?

      It is a program module that provides the interface between the low-level data stored in database,

      application programs and queries submitted to the system.

      What is Buffer Manager?

      It is a program module, which is responsible for fetching data from disk storage into main memory

      and deciding what data to be cache in memory.

      What is Transaction Manager?

      It is a program module, which ensures that database, remains in a consistent state despite system failures

      and concurrent transaction execution proceeds without conflicting.

      What is File Manager?

      It is a program module, which manages the allocation of space on disk storage and data structure used to

      represent information stored on a disk.

      What are cursors give different types of cursors.

      PL/SQL uses cursors for all database information accesses statements. The language supports the use two types of cursors

      • Implicit
      • Explicit
      how to display duplicate rows in a table? 

      select * from emp
      group by (empid)
      having count(empid)>1
      Difference between VARCHAR and VARCHAR2? 

      varchar means fixed length character data(size) ie., min size-1 and max-2000
      where as varchar2 means variable length character data ie., min-1 to max-4000
      diff b/w oracle and ms-access.
      One of the differences is:
      Oracle is multi-user where MS-Access is not.

      How to get the second Max sal from emp table in Oracle?

      Answer :
      select max(salary)from emp where salary<(select max(salary)from emp)

      how to display duplicate rows in a table?
      select * from emp
      group by (empid)
      having count(empid)>1
      diff b/w oracle and ms-access.
      One of the differences is:
      Oracle is multi-user where MS-Access is not.
      Q: How can you compare a part of the name rather than the entire name?
      A: SELECT * FROM people WHERE empname LIKE ‘%ab%’
      Would return a recordset with records consisting empname the sequence ‘ab‘ in empname .
      Q: How to get the results of a Query sorted in any order?
      A: You can sort the results and return the sorted results to your program by using ORDER BY keyword
      thus saving you the pain of carrying out the sorting yourself. The ORDER BY keyword is used for sorting.

      SELECT empname, age, city FROM emptable ORDER BY empname
      Q: How can I find the total number of records in a table?
      A: You could use the COUNT keyword , example 
      SELECT COUNT(*) FROM emp WHERE age>40
      Q: What is the difference among “dropping a table”, “truncating a table” and “deleting all records” from a table.
      A: Dropping : (Table structure + Data are deleted), Invalidates the dependent objects ,Drops the indexes
      Truncating: (Data alone deleted), Performs an automatic commit, Faster than delete
      Delete : (Data alone deleted), Doesn’t perform automatic commit
      Q: What are the Large object types suported by Oracle?
      A: Blob and Clob.
      Q: Difference between a “where” clause and a “having” clause.
      A: Having clause is used only with group functions whereas Where is not used with.
      Q: What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you avoid cursors?
      A: Cursors allow row-by-row prcessing of the resultsets. 
      Types of cursors: Static, Dynamic, Forward-only, Keyset-driven.
      Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip, where as a normal SELECT query makes only one rowundtrip, however large the resultset is. Cursors are also costly because they require more resources and temporary storage (results in more IO operations). Furthere, there are restrictions on the SELECT statements that can be used with some types of cursors.
      Most of the times, set based operations can be used instead of cursors.
      Q: What are triggers? How to invoke a trigger on demand?
      A: Triggers are special kind of stored procedures that get executed automatically when an INSERT, UPDATE or DELETE operation takes place on a table. 
      Triggers can’t be invoked on demand. They get triggered only when an associated action (INSERT, UPDATE, DELETE) happens on the table on which they are defined.
      Triggers are generally used to implement business rules, auditing. Triggers can also be used to extend the referential integrity checks, but wherever possible, use constraints for this purpose, instead of triggers, as constraints are much faster.
      Q: What is a join and explain different types of joins.
      A: Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table. Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.
      Q: What is a self join?
      A: Self join is just like any other join, except that two instances of the same table will be joined in the query.

      Que : How many types of joins are exists ? explain with example?

      There are three basic types of joins, Cross, Inner & Outer join
      1. Cross Join – A cross join merges two tables on every record in a geometric fashion, every record of
      one table is combined with every record from the other table. Two tables of 10 records each in a cross join will
      create a table of 100 (10 X 10) records.
      2. Inner Join – An Inner join is used to match two tables based on values of a common field.
      It can be thought of as the Intersection of the two sets of data. Inner join is the records that appear in both tables.
      3. Outer Join – The Outer join is a type of join that returns all of the members of one set,
      and any matching members of the other set. Outer join can be Left Outer join or Right Outer join.
      For explaining this we will take two tables Students and Courses
      a. Left Outer join – This join will give a list of Students who are not enrolled in any course.
      b. Right Outer join – This join will give a list of courses which don’t have any Students enrolled.

      What is a transaction and what are ACID properties?
      A transaction is a logical unit of work in which, all the steps must be performed or none.
      ACID stands for Atomicity, Consistency, Isolation, Durability. These are the properties of a transaction.
      For more information and explanation of these properties, see SQL Server books online or any RDBMS fundamentals text book.
      What’s the maximum size of a row?
      8060 bytes. Don’t be surprised with questions like ‘what is the maximum number of columns per table’.
      Check out SQL Server books online for the page titled: “Maximum Capacity Specifications”.
      What are constraints? Explain different types of constraints.
      Constraints enable the RDBMS enforce the integrity of the database automatically, without needing you to create triggers,
      rule or defaults.
      For an explanation of these constraints see books online for the pages titled: “Constraints” and “CREATE TABLE”, “ALTER TABLE”
      What is a deadlock and what is a live lock? How will you go about resolving deadlocks?
      Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire a lock on the other’s piece
      Write down the general syntax for a SELECT statements covering all the options.
      Here’s the basic syntax: (Also checkout SELECT in books online for advanced syntax). 
      SELECT select_list
      [INTO new_table_]
      FROM table_source
      [WHERE search_condition]
      [GROUP BY group_by_expression]
      [HAVING search_condition]
      [ORDER BY order_expression [ASC | DESC] ]

      MySQL Technical Interview Questions – part 2

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

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

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

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

      What is SERIAL data type in MySQL?

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

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

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

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

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

      But what if you really want to store the timestamp data, such as the publication date of the article?
      Create two columns of type TIMESTAMP and use the second one for your real data.

      The column exhibits the same behavior as a single timestamp column in a table with no other timestamp columns.

      On initialization places a zero in that column, on future updates puts the current value of the timestamp in.

      Explain TIMESTAMP DEFAULT ‘2006:09:02 17:38:44? ON UPDATE CURRENT_TIMESTAMP. ?
      A default value is used on initialization, a current timestamp is inserted on update of the row.

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

      MySQL – Stored Procedures and Triggers
      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 reissuing the entire query but can refer to the stored procedure. This provides better 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.
      A trigger is a stored procedure 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 automatically deletes the corresponding customer from a customer table when all his transactions are deleted.
      The planned update language will be able to handle stored procedures, but without triggers. Triggers usually slow down everything, even queries for which they are not needed.

      MySQL – Foreign Keys
      Note that foreign keys in SQL are not used to join tables, but are used mostly for checking referential integrity (foreign key constraints). If you want to get results from multiple tables from a SELECT statement, you do this by joining tables:
      SELECT * from table1,table2 where =;
      The FOREIGN KEY syntax in MySQL exists only for compatibility with other SQL vendors’ CREATE TABLE commands; it doesn’t do anything. The FOREIGN KEY syntax without ON DELETE … is mostly used for documentation purposes. Some ODBC applications may use this to produce automatic WHERE clauses, but this is usually easy to override. FOREIGN KEY is sometimes used as a constraint check, but this check is unnecessary in practice if rows are inserted into the tables in the right order. MySQL only supports these clauses because some applications require them to exist (regardless of whether or not they work).
      In MySQL, you can work around the problem of ON DELETE … not being implemented by adding the appropriate DELETE statement to an application when you delete records from a table that has a foreign key. In practice this is as quick (in some cases quicker) and much more portable than using foreign keys.
      In the near future we will extend the FOREIGN KEY implementation so that at least the information will be saved in the table specification file and may be retrieved by mysqldump and ODBC. At a later stage we will implement the foreign key constraints for application that can’t easily be coded to avoid them.

      MySQL – Reasons NOT to Use Foreign Keys constraints
      There are so many problems with foreign key constraints that we don’t know where to start:
      Foreign key constraints make life very complicated, because the foreign key definitions must be stored in a database and implementing them would destroy the whole “nice approach” of using files that can be moved, copied, and removed. The speed impact is terrible for INSERT and UPDATE statements, and in this case almost all FOREIGN KEY constraint checks are useless because you usually insert records in the right tables in the right order, anyway. There is also a need to hold locks on many more tables when updating one table, because the side effects can cascade through the entire database. It’s MUCH faster to delete records from one table first and subsequently delete them from the other tables.
      You can no longer restore a table by doing a full delete from the table and then restoring all records (from a new source or from a backup).
      If you use foreign key constraints you can’t dump and restore tables unless you do so in a very specific order. It’s very easy to do “allowed” circular definitions that make the tables impossible to re-create each table with a single create statement, even if the definition works and is usable.
      It’s very easy to overlook FOREIGN KEY … ON DELETE rules when one codes an application. It’s not unusual that one loses a lot of important information just because a wrong or misused ON DELETE rule.
      The only nice aspect of FOREIGN KEY is that it gives ODBC and some other client programs the ability to see how a table is connected and to use this to show connection diagrams and to help in building applicatons.
      MySQL will soon store FOREIGN KEY definitions so that a client can ask for and receive an answer about how the original connection was made. The current `.frm’ file format does not have any place for it. At a later stage we will implement the foreign key constraints for application that can’t easily be coded to avoid them.

      MySQL – `–‘ as the Start of a Comment
      MySQL doesn’t support views, but this is on the TODO.


      MySQL Technical Interview Questions – part 1

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

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

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

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

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

      Explain The technical features of MySQL ?
      For advanced technical information, see section 7 MySQL Language Reference. MySQL is a client/server system that consists of a multi-threaded SQL server that supports different backends, several different client programs and libraries, administrative tools, and a programming interface. We also provide MySQL as a multi-threaded library which you can link into your application to get a smaller, faster, easier to manage product. MySQL has a lot of contributed software available.
      It is very likely that you will find that your favorite application/language already supports MySQL. The official way to pronounce MySQL is “My Ess Que Ell” (not MY-SEQUEL). But we try to avoid correcting people who say MY-SEQUEL.

      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.

      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.

      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;

      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.

      You wrote a search engine that should retrieve 10 results at a time, but at the same time you’d like to know how many rows there’re total. How do you display that to the user?
      SELECT SQL_CALC_FOUND_ROWS page_title FROM web_pages LIMIT 1,10; SELECT FOUND_ROWS(); The second query (not that COUNT() is never used) will tell you how many results there’re total, so you can display a phrase “Found 13,450,600 results, displaying 1-10”. Note that FOUND_ROWS does not pay attention to the LIMITs you specified and always returns the total number of rows affected by query.

      How would you write a query to select all teams that won either 2, 4, 6 or 8 games?
      SELECT team_name FROM teams WHERE team_won IN (2, 4, 6, 8 )

      How would you select all the users, whose phone number is null?
      SELECT user_name FROM users WHERE ISNULL(user_phonenumber);

      What does this query mean: SELECT user_name, user_isp FROM users LEFT JOIN isps USING (user_id) ?
      It’s equivalent to saying SELECT user_name, user_isp FROM users LEFT JOIN isps WHERE users.user_id=isps.user_id

      How do you find out which auto increment was assigned on the last insert?

      SELECT LAST_INSERT_ID() will return the last value assigned by the auto_increment function. Note that you don’t have to specify the table name.

      What does –i-am-a-dummy flag to do when starting MySQL?
      Makes the MySQL engine refuse UPDATE and DELETE commands where the WHERE clause is not present.

      On executing the DELETE statement I keep getting the error about foreign key constraint failing. What do I do?
      What it means is that so of the data that you’re trying to delete is still alive in another table. Like if you have a table for universities and a table for students, which contains the ID of the university they go to, running a delete on a university table will fail if the students table still contains people enrolled at that university. Proper way to do it would be to delete the offending data first, and then delete the university in question. Quick way would involve running SET foreign_key_checks=0 before the DELETE command, and setting the parameter back to 1 after the DELETE is done. If your foreign key was formulated with ON DELETE CASCADE, the data in dependent tables will be removed automatically.

      When would you use ORDER BY in DELETE statement?
      When you’re not deleting by row ID. Such as in DELETE FROM techpreparation_com_questions ORDER BY timestamp LIMIT 1. This will delete the most recently posted question in the table techpreparation_com_questions.

      How can you see all indexes defined for a table?
      SHOW INDEX FROM techpreparation_questions;

      How would you change a column from VARCHAR(10) to VARCHAR(50)?
      ALTER TABLE techpreparation_questions CHANGE techpreparation_content techpreparation_CONTENT VARCHAR(50).

      How would you delete a column?
      ALTER TABLE techpreparation_answers DROP answer_user_id.

      How would you change a table to InnoDB?
      ALTER TABLE techpreparation_questions ENGINE innodb;

      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

      How do I find out all databases starting with ‘tech’ to which I have access to?
      SHOW DATABASES LIKE ‘tech%’;

      How do you concatenate strings in MySQL?
      CONCAT (string1, string2, string3)

      How do you get a portion of a string?
      SELECT SUBSTR(title, 1, 10) from techpreparation_questions;

      What’s the difference between CHAR_LENGTH and LENGTH?
      The first is, naturally, the character count. The second is byte count. For the Latin characters the numbers are the same, but they’re not the same for Unicode and other encodings.

      How do you convert a string to UTF-8?

      SELECT (techpreparation_question USING utf8);

      What do % and _ mean inside LIKE statement?
      % corresponds to 0 or more characters, _ is exactly one character.

      What does + mean in REGEXP?
      At least one character. Appendix G. Regular Expressions from MySQL manual is worth perusing before the interview.

      How do you get the month from a timestamp?
      SELECT MONTH(techpreparation_timestamp) from techpreparation_questions;

      How do you offload the time/date handling to MySQL?
      SELECT DATE_FORMAT(techpreparation_timestamp, ‘%Y-%m-%d’) from techpreparation_questions; A similar TIME_FORMAT function deals with time.

      How do you add three minutes to a date?
      ADDDATE(techpreparation_publication_date, INTERVAL 3 MINUTE)

      What’s the difference between Unix timestamps and MySQL timestamps?
      Internally Unix timestamps are stored as 32-bit integers, while MySQL timestamps are stored in a similar manner, but represented in readable YYYY-MM-DD HH:MM:SS format.

      How do you convert between Unix timestamps and MySQL timestamps?
      UNIX_TIMESTAMP converts from MySQL timestamp to Unix timestamp, FROM_UNIXTIME converts from Unix timestamp to MySQL timestamp.

      What are ENUMs used for in MySQL?
      You can limit the possible values that go into the table. CREATE TABLE months (month ENUM ‘January’, ‘February’, ‘March’,…); INSERT months VALUES (’April’);

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

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

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

      Explain the difference between mysql and mysql interfaces in PHP?
      mysqli is the object-oriented version of mysql library functions.

      What’s the default port for MySQL Server?

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

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

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

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

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

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

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

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

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

      Explain advantages of MyISAM over InnoDB?
      Much more conservative approach to disk space management – each MyISAM table is stored in a separate file, which could be compressed then with myisamchk if needed. With InnoDB the tables are stored in tablespace, and not much further optimization is possible. All data except for TEXT and BLOB can occupy 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.


      PHP Interview Questions part 6 [asked in YAHOO interview]

      1. Which of the following will NOT add john to the users array?

        1. $users[ ] = ‘john’;
        2. Successfully adds john to the array

        3. array_add($users,’john’);
        4. Fails stating Undefined Function array_add()

        5. array_push($users,‘john’);
        6. Successfully adds john to the array

        7. $users ||= ‘john’;
        8. Fails stating Syntax Error

      2. What’s the difference between sort(), asort() and ksort? Under what circumstances would you use each of these?

        1. sort()
          Sorts an array in alphabetical order based on the value of each element. The index keys will also be renumbered 0 to length – 1. This is used primarily on arrays where the indexes/keys do not matter.
        2. asort()
          Like the sort() function, this sorts the array in alphabetical order based on the value of each element, however, unlike the sort() function, all indexes are maintained, thus it will not renumber them, but rather keep them. This is particularly useful with associate arrays.
        3. ksort()
          Sorts an array in alphabetical order by index/key. This is typically used for associate arrays where you want the keys/indexes to be in alphabetical order.
      3. What would the following code print to the browser? Why?


        1. $num = 10;
        2. function multiply(){
        3. $num = $num * 10;
        4. }
        5. multiply();
        6. echo $num; // prints 10 to the screen

        Since the function does not specify to use $num globally either by using global $num; or by $_GLOBALS[‘num’] instead of $num, the value remains 10.

      4. What is the difference between a reference and a regular variable? How do you pass by reference and why would you want to?

        Reference variables pass the address location of the variable instead of the value. So when the variable is changed in the function, it is also changed in the whole application, as now the address points to the new value.
        Now a regular variable passes by value, so when the value is changed in the function, it has no affect outside the function.


        1. $myVariable = “its’ value”;
        2. Myfunction(&$myVariable); // Pass by Reference Example

        So why would you want to pass by reference? The simple reason, is you want the function to update the value of your variable so even after you are done with the function, the value has been updated accordingly.

      5. What functions can you use to add library code to the currently running script?

        This is another question where the interpretation could completely hit or miss the question. My first thought was class libraries written in PHP, so include(), include_once(), require(), and require_once() came to mind. However, you can also include COM objects and .NET libraries. By utilizing the com_load and the dotnet_load respectively you can incorporate COM objects and .NET libraries into your PHP code, thus anytime you see “library code” in a question, make sure you remember these two functions.

      6. What is the difference between foo() & @foo()?

        foo() executes the function and any parse/syntax/thrown errors will be displayed on the page.
        @foo() will mask any parse/syntax/thrown errors as it executes.
        You will commonly find most applications use @mysql_connect() to hide mysql errors or @mysql_query. However, I feel that approach is significantly flawed as you should never hide errors, rather you should manage them accordingly and if you can, fix them.

      7. How do you debug a PHP application?

        This isn’t something I do often, as it is a pain in the butt to setup in Linux and I have tried numerous debuggers. However, I will point out one that has been getting quite a bit of attention lately.
        PHP – Advanced PHP Debugger or PHP-APD. First you have to install it by running:
        pear install apd
        Once installed, start the trace by placing the following code at the beginning of your script:
        Then once you have executed your script, look at the log in apd.dumpdir.
        You can even use the pprofp command to format the data as in:
        pprofp -R /tmp/pprof.22141.0
        For more information see

      8. What does === do? What’s an example of something that will give true for ‘==’, but not ‘===’?

        The === operator is used for functions that can return a Boolean false and that may also return a non-Boolean value which evaluates to false. Such functions would be strpos and strrpos.
        I am having a hard time with the second portion, as I am able to come up with scenarios where ‘==’ will be false and ‘===’ would come out true, but it’s hard to think of the opposite. So here is the example I came up with:


        1. if (strpos(“abc”, “a”) == true)
        2. {
        3. // this does not get hit, since “a” is in the 0 index position, it returns false.
        4. }
        5. if (strpos(“abc”, “a”) === true)
        6. {
        7. // this does get hit as the === ensures this is treated as non-boolean.
        8. }
      9. How would you declare a class named “myclass” with no methods or properties?


        1. class myclass
        2. {
        3. }
      10. How would you create an object, which is an instance of “myclass”?


        1. $obj = new myclass();

        It doesn’t get any easier than this.

      11. How do you access and set properties of a class from within the class?

        You use the $this->PropertyName syntax.


        1. class myclass
        2. {
        3. private $propertyName;
        4. public function __construct()
        5. {
        6. $this->propertyName = “value”;
        7. }
        8. }
        1. What is the difference between include, include_once? and require?

          All three allow the script to include another file, be it internal or external depending on if allow_url_fopen is enabled. However, they do have slight differences, which are denoted below.

          1. include()
            The include() function allows you to include a file multiple times within your application and if the file does not exist it will throw a Warning and continue on with your PHP script.
          2. include_once()
            include_once() is like include() except as the name suggests, it will only include the file once during the script execution.
          3. require()
            Like include(), you can request to require a file multiple times, however, if the file does not exist it will throw a Warning that will result in a Fatal Error stopping the PHP script execution.
        2. What function would you use to redirect the browser to a new page?

          1. redir()
            This is not a function in PHP, so it will fail with an error.
          2. header()
            This is the correct function, it allows you to write header data to direct the page to a new location. For example:


            1. header(“Location:”);
          3. location()
            This is not a function in PHP, so it will fail with an error.
          4. redirect()
            This is not a function in PHP, so it will fail with an error.
        3. What function can you use to open a file for reading and writing?

          1. fget()
            This is not a function in PHP, so it will fail with an error.
          2. file_open()
            This is not a function in PHP, so it will fail with an error.
          3. fopen()
            This is the correct function, it allows you to open a file for reading and/or writing. In fact, you have a lot of options, check out for more information.
          4. open_file()
            This is not a function in PHP, so it will fail with an error.
        4. What’s the difference between mysql_fetch_row() and mysql_fetch_array()?

          mysql_fetch_row() returns all of the columns in an array using a 0 based index. The first row would have the index of 0, the second would be 1, and so on. Now another MySQL function in PHP is mysql_fetch_assoc(), which is an associative array. Its’ indexes are the column names. For example, if my query was returning ‘first_name’, ‘last_name’, ’email’, my indexes in the array would be ‘first_name’, ‘last_name’, and ’email’. mysql_fetch_array() provides the output of mysql_fetch_assoc and mysql_fetch_row().

        5. What does the following code do? Explain what’s going on there.


          1. $date=’09/25/2008′;
          2. print ereg_replace(“([0-9]+)/([0-9]+)/([0-9]+)”,\\2/\\1/\\3″,$date);

          This code is reformatting the date from MM/DD/YYYY to DD/MM/YYYY. A good friend got me hooked on writing regular expressions like below, so it could be commented much better, granted this is a bit excessive for such a simple regular expression.


          1. // Match 0-9 one or more times then a forward slash
          2. $regExpression = “([0-9]+)/”;
          3. // Match 0-9 one or more times then another forward slash
          4. $regExpression .= “([0-9]+)/”;
          5. // Match 0-9 one or more times yet again.
          6. $regExpression .= “([0-9]+)”;

          Now the \\2/\\1/\\3 denotes the parentheses matches. The first parenthesis matches the month, the second the day, and the third the year.

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

          First of all why would you write a regular expression when a PHP function already exists? See’s strip_tags function. However, considering this is an interview question, I would write it like so:


          1. $stringOfText = “<p>This is a testing</p>”;
          2. $expression = “/<(.*?)>(.*?)<\/(.*?)>/”;
          3. echo preg_replace($expression, \\2″, $stringOfText);
          4. // It was suggested (by Fred) that /(<[^>]*>)/ would work too.
          5. $expression = “/(<[^>]*>)/”;
          6. echo preg_replace($expression, “”, $stringOfText);
        7. What’s the difference between the way PHP and Perl distinguish between arrays and hashes?

          This is why I tell everyone to, “pick the language for the job!” If you only write code in a single language how will you ever answer this question? The question is quite simple. In Perl, you are required to use the @ sign to start all array variable names, for example, @myArray. In PHP, you just continue to use the $ (dollar sign), for example, $myArray.
          Now for hashes in Perl you must start the variable name with the % (percent sign), as in, %myHash. Whereas, in PHP you still use the $ (dollar sign), as in, $myHash.

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

          The top two options that are used are sessions and cookies. To access a session, you will need to have session_start() at the top of each page, and then you will use the $_SESSION hash to access and store your session variables. For cookies, you only have to remember one rule. You must use the set_cookie function before any output is started in your PHP script. From then on you can use the $_COOKIE has to access your cookie variables and values.
          There are other methods, but they are not as fool proof and most often than not depend on the IP address of the visitor, which is a very dangerous thing to do.

        9. What does the GD library do?

          This is probably one of my favorite libraries, as it is built into PHP as of version 4.3.0 (I am very happy with myself, I didn’t have to look up the version of PHP this was introduced on This library allows you to manipulate and display images of various extensions. More often than not, it is used to create thumbnail images. An alternative to GD is ImageMagick, however, unlike GD, this does not come built in to PHP and must be installed on the server by an Administrator.

        10. Name a few ways to output (print) a block of HTML code in PHP?

          Well you can use any of the output statments in PHP, such as, print, echo, and printf. Most individuals use the echo statement as in:


          1. echo “My test string $variable”;

          However, you can also use it like so:


          1. echo <<<OUTPUT
          2. This text is written to the screen as output and this $variable is parsed too. If you wanted you can have <span> HTML tags in here as well.</span> The END; remarks must be on a line of its own, and can‘t contain any extra white space.
          3. END;
        11. Is PHP better than Perl? – Discuss.

          Come on, let’s not start a flame over such a trivial question. As I have stated many times before,

          “Pick the language for the job, do not fit the job into a particular language.”

          Perl in my opinion is great for command line utilities, yes it can be used for the web as well, but its’ real power can be really demonstrated through the command line. Likewise, PHP can be used on the command line too, but I personally feel it’s more powerful on the web. It has a lot more functions built with the web in mind, whereas, Perl seems to have the console in mind.
          Personally, I love both languages. I used Perl a lot in college and I used PHP and Java a lot in college. Unfortunately, my job requires me to use C#, but I spend countless hours at home working in PHP, Perl, Ruby (currently learning), and Java to keep my skills up to date. Many have asked me what happened to C and C++ and do they still fit into my applications from time to time. The answer is primarily ‘No’. Lately all of my development work has been for the web and though C and C++ could be written for the web, they are hardly the language to use for such tasks. Pick the language for the job. If I needed a console application that was meant to show off the performance differences between a quick sort, bubble sort, and a merge sort, give me C/C++! If you want a Photo Gallery, give me PHP or C# (though I personally find .NET languages better for quick GUI applications than web).


      PHP Interview Questions Part 5

      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?
      get is like query string all the variables will be displayed in he url
      where as post is the standard way of sending th evariables
      When we submit a form, which has the GET method it displays pair of name/value used in the form at the address bar of the browser preceded by url. Post method doesn’t display these values.
      2. Who is the father of PHP and explain the changes in PHP versions?
      Father of php is Rasmus Lerdorf
      3. What is the difference between $message and $$message?
      $message is variable whereas $$message is Dynamic variable.
      is equivalent to
      4. How can we create a database using PHP and mysql?
      mysql_create_db() should work
      5. Can we use include (”abc.PHP”) two times in a PHP page “makeit.PHP”?
      Yes we can include that many times we want, but here are some things to make sure of:
      (including abc.PHP, the file names are case-sensitive)
      there shouldnt be any duplicate function names, means there should not be functions or classes or variables with the same name in abc.PHP and makeit.php
      6. How can I execute a PHP script using command line?
      Through php parse you can execute PHP script using command line. By default location of php parser is /var/www/html so set the path of this directory and just use as following
      7. Suppose your Zend engine supports the mode <? ?> Then how can u configure your PHP Zend engine to support <?PHP ?> mode ?
      In php.ini file:
      set short_open_tag=on to make PHP support
      8. What is meant by nl2br()?
      nl2br() inserts html in string. echo nl2br(”god bless \n you”);
      god bless
      9. What are the different types of errors in PHP?
      Three are three types of errors 1) Fatal errors 2) Parser errors 3) Startup errors.
      10. What is meant by urlencode and urldocode?
      string urlencode(str)
      where str contains a string like this “hello world” and the return value will be URL encoded and can be use to append with URLs, normaly used to appned data for GET like
      string urldocode(str)
      this will simple decode the GET variable’s value
      Like it echo (urldecode($_GET_VARS[var])) will o/p “Hello world”
      11. List out the predefined classes in PHP?
      Predefined Classes
      1. Standard Defined Classes
      These classes are defined in the standard set of functions included in the PHP build.
      a. Directory
      The class from which dir() is instantiated.
      2.Ming Defined Classes
      These classes are defined in the Ming extension, and will only be available when that extension has either been compiled into PHP or dynamically loaded at runtime.
      a.swfshape b. swffill c. swfgradient d. swfbitmap e. swftext f. swftextfield
      g. swffont h. swfdisplayitem i. swfmovie j. swfbutton k. swfaction
      l. swfmorph m. swfsprite

      3. Oracle 8 Defined Classes
      These classes are defined in the Oracle 8 extension, and will only be available when that extension has either been compiled into PHP or dynamically loaded at runtime.
      a. OCI-Lob b. OCI-Collection
      4. qtdom Defined Classes
      These classes are defined in the qtdom extension, and will only be available when that extension has either been compiled into PHP or dynamically loaded at runtime.
      a. QDomDocument b. QDomNode
      12. If you have to work with dates in the following format: “Tuesday, February 14, 2006 @ 10:39 am”, how can you convert them to another format, that is easier to use?
      The strtotime function can convert a string to a timestamp. A timestamp can be converted to date format. So it is best to store the dates as timestamp in the database, and just output them in the format you like.
      So let’s say we have
      $date = “Tuesday, February 14, 2006 @ 10:39 am”;
      In order to convert that to a timestamp, we need to get rid of the “@” sign, and we can use the remaining string as a parameter for the strtotime function.
      So we have
      $date = str_replace(“@ “,””,$date);
      $date = strtotime($date);
      now $date is a timestamp
      and we can say:
      echo date(“d M Y”,$date);
      13. How we know browser properties?
      get_browser() attempts to determine the capabilities of the user’s browser. This is done by looking up the browser’s information in the browscap.ini file.
      echo $_SERVER[‘HTTP_USER_AGENT’] . “\n”;
      $browser = get_browser();
      foreach ($browser as $name => $value) {
      echo “$name $value
      14. How i will check that user is, logged in or not. i want to make it a function and i want to use in each page and after login i want to go in current page(same page. where i was working)?
      For this we can use the session objec($_SESSION)t. When the user login with his/ her user name and password, usually we check those to ensure for correctness. If that user name and password are valid one then we can store that user name in a session and then we can very that session variable has been set or not in a single files and we can include that file in all pages.
      15. How i can get ip address?
      We can use SERVER var $_SERVER[‘SERVER_ADDR’] and getenv(“REMOTE_ADDR”) functions to get the IP address.


      PHP Interview Questions part 4

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

      How many ways I can redirect a PHP page?
      Here are the possible ways of php page redirection.
      1. Using Java script:
      ‘; echo ‘window.location.href=”‘.$filename.’”;’; echo ”; echo ”; echo ”; echo ”; } } redirect(’’); ?>
      2. Using php function: header(”Location: “);

      List out different arguments in PHP header function?
      void header ( string string [, bool replace [, int http_response_code]])

      What type of headers have to be added in the mail function to attach a file?
      $boundary = ‘–’ . md5( uniqid ( rand() ) );
      $headers = “From: \”Me\”\n”;
      $headers .= “MIME-Version: 1.0\n”;
      $headers .= “Content-Type: multipart/mixed; boundary=\”$boundary\””;

      What is the difference between Reply-to and Return-path in the headers of a mail function?
      Reply-to: Reply-to is where to delivery the reply of the mail.
      Return-path: Return path is when there is a mail delivery failure occurs then where to delivery the failure notification.

      How to store the uploaded file to the final location?
      move_uploaded_file ( string filename, string destination)
      This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP’s HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.
      If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.

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

      Explain about Type Juggling in php?
      PHP does not require (or support) explicit type definition in variable declaration; a variable’s type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable $var, $var becomes a string. If you then assign an integer value to $var, it becomes an integer.
      An example of PHP’s automatic type conversion is the addition operator ‘+’. If any of the operands is a float, then all operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does NOT change the types of the operands themselves; the only change is in how the operands are evaluated.
      $foo += 2; // $foo is now an integer (2)
      $foo = $foo + 1.3; // $foo is now a float (3.3)
      $foo = 5 + “10 Little Piggies”; // $foo is integer (15)
      $foo = 5 + “10 Small Pigs”; // $foo is integer (15)
      If the last two examples above seem odd, see String conversion to numbers.
      If you wish to change the type of a variable, see settype().
      If you would like to test any of the examples in this section, you can use the var_dump() function.
      Note: The behavior of an automatic conversion to array is currently undefined.
      Since PHP (for historical reasons) supports indexing into strings via offsets using the same syntax as array indexing, the example above leads to a problem: should $a become an array with its first element being “f”, or should “f” become the first character of the string $a? The current versions of PHP interpret the second assignment as a string offset identification, so $a becomes “f”, the result of this automatic conversion however should be considered undefined. PHP 4 introduced the new curly bracket syntax to access characters in string, use this syntax instead of the one presented above:

      How can I embed a java programme in php file and what changes have to be done in php.ini file?
      There are two possible ways to bridge PHP and Java: you can either integrate PHP into a Java Servlet environment, which is the more stable and efficient solution, or integrate Java support into PHP. The former is provided by a SAPI module that interfaces with the Servlet server, the latter by this Java extension.
      The Java extension provides a simple and effective means for creating and invoking methods on Java objects from PHP. The JVM is created using JNI, and everything runs in-process.
      Example Code:
      getProperty(’java.version’) . ”; echo ‘Java vendor=’ . $system->getProperty(’java.vendor’) . ”; echo ‘OS=’ . $system->getProperty(’’) . ‘ ‘ . $system->getProperty(’os.version’) . ‘ on ‘ . $system->getProperty(’os.arch’) . ‘ ‘; // java.util.Date example $formatter = new Java(’java.text.SimpleDateFormat’, “EEEE, MMMM dd, yyyy ‘at’ h:mm:ss a zzzz”); echo $formatter->format(new Java(’java.util.Date’)); ?>
      The behaviour of these functions is affected by settings in php.ini.
      Table 1. Java configuration options
      Name Default Changeable

      Explain the ternary conditional operator in PHP?
      Expression preceding the ? is evaluated, if it’s true, then the expression preceding the : is executed, otherwise, the expression following : is executed.

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

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


      PHP Interview Questions part 3

      How can we extract string “” from a string “” using regular expression of PHP?
      $text = “”;
      preg_match(’|.*@([^?]*)|’, $text, $output);
      echo $output[1];
      Note that the second index of $output, $output[1], gives the match, not the first one, $output[0].

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

      How can we destroy the session, how can we unset the variable of a session?
      session_unregister() – Unregister a global variable from the current session
      session_unset() – Free all session variables

      What are the different functions in sorting an array?
      Sorting functions in PHP:


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

      How many ways we can pass the variable through the navigation between the pages?
      At least 3 ways:
      1. Put the variable into session in the first page, and get it back from session in the next page.
      2. Put the variable into cookie in the first page, and get it back from the cookie in the next page.
      3. Put the variable into a hidden form field, and get it back from the form in the next page.

      What’s the difference between md5(), crc32() and sha1() crypto on PHP?
      The major difference is the length of the hash generated. CRC32 is, evidently, 32 bits, while sha1() returns a 128 bit value, and md5() returns a 160 bit value. This is important when avoiding collisions.

      How can we find the number of rows in a result set using PHP?
      Here is how can you find the number of rows in a result set in PHP:
      $result = mysql_query($any_valid_sql, $database_link);
      $num_rows = mysql_num_rows($result);
      echo “$num_rows rows found”;

      What is the functionality of MD5 function in PHP?
      string md5(string)
      It calculates the MD5 hash of a string. The hash is a 32-character hexadecimal number.

      How can we know that a session is started or not?
      A session starts by session_start() function.
      This session_start() is always declared in header portion. it always declares first. then we write session_register().

      If we login more than one browser windows at the same time with same user and after that we close one window, then is the session is exist to other windows or not? And if yes then why? If no then why?
      Session depends on browser. If browser is closed then session is lost. The session data will be deleted after session time out. If connection is lost and you recreate connection, then session will continue in the browser.

      What is the difference between PHP4 and PHP5?
      PHP4 cannot support oops concepts and Zend engine 1 is used.
      PHP5 supports oops concepts and Zend engine 2 is used.
      Error supporting is increased in PHP5.
      XML and SQLLite will is increased in PHP5.

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

      What is meant by nl2br()?
      nl2br() inserts a HTML tag <br> before all new line characters \n in a string.
      echo nl2br(”god bless \n you”);
      god bless<br>

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

      What are encryption functions in PHP?

      What is the difference between htmlentities() and htmlspecialchars()?
      htmlspecialchars() – Convert some special characters to HTML entities (Only the most widely used)
      htmlentities() – Convert ALL special characters to HTML entities

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

      How can we get the properties (size, type, width, height) of an image using php image functions?
      To know the image size use getimagesize() function
      To know the image width use imagesx() function
      To know the image height use imagesy() function

      How can we increase the execution time of a php script?
      By the use of void set_time_limit(int seconds)
      Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini. If seconds is set to zero, no time limit is imposed.
      When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.

      How to set cookies?
      variable – name of the cookie variable
      value – value of the cookie variable
      time – expiry time
      Example: setcookie(’Test’,$i,time()+3600);
      Test – cookie variable name
      $i – value of the variable ‘Test’
      time()+3600 – denotes that the cookie will expire after an one hour

      How to reset/destroy a cookie ?
      Reset a cookie by specifying expire time in the past:
      Example: setcookie(’Test’,$i,time()-3600); // already expired time
      Reset a cookie by specifying its name only
      Example: setcookie(’Test’);

      What types of images that PHP supports ?
      Using imagetypes() function to find out what types of images are supported in your PHP engine.

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

      Check if a variable is an integer in JAVASCRIPT ?
      var myValue =9.8;
      if(parseInt(myValue)== myValue)
      alert(’Not an integer’);

      Tools used for drawing ER diagrams.
      Case Studio
      Smart Draw

      How can I know that a variable is a number or not using a JavaScript?
      Answer 1:
      bool is_numeric( mixed var)
      Returns TRUE if var is a number or a numeric string, FALSE otherwise.
      Answer 2:
      Definition and Usage
      The isNaN() function is used to check if a value is not a number.
      Parameter Description
      number Required. The value to be tested

      How can we submit from without a submit button?
      Trigger the JavaScript code on any event ( like onSelect of drop down list box, onfocus, etc ) document.myform.submit(); This will submit the form.

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

      How can we destroy the cookie?
      Set the cookie with a past expiration time.

      What are the current versions of Apache, PHP, and MySQL?
      PHP: PHP 5.2.5
      MySQL: MySQL 5.1
      Apache: Apache 2.1

      What are the reasons for selecting LAMP (Linux, Apache, MySQL, Php) instead of combination of other software programs, servers and operating systems?
      All of those are open source resource. Security of Linux is very more than windows. Apache is a better server that IIS both in functionality and security. Mysql is world most popular open source database. Php is more faster that asp or any other scripting language.

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

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

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

      class mylinkage
      mylinkage * prev;
      mylinkage * next;
      friend void set_prev(mylinkage* L, mylinkage* N);
      void set_next(mylinkage* L);
      mylinkage * succ();
      mylinkage * pred();
      void mylinkage::set_next(mylinkage* L) { next = L; }
      void set_prev(mylinkage * L, mylinkage * N ) { N->prev = L; }
      Friends in other classes
      It is possible to specify a member function of another class as a friend as follows:
      class C
      friend int B::f1();
      class B
      int f1();
      It is also possible to specify all the functions in another class as friends, by specifying the entire class as a friend.
      class A
      friend class B;
      Friend functions allow binary operators to be defined which combine private data in a pair of objects. This is particularly powerful when using the operator overloading features of C++. We will return to it when we look at overloading.

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

      What is the maximum size of a file that can be uploaded using PHP and how can we change this?
      You can change maximum size of a file set upload_max_filesize variable in php.ini file

      How can I make a script that can be bilingual (supports English, German)?
      You can change char set variable in above line in the script to support bi language.

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

      What’s the difference between accessing a class method via -> and via :
      :: is allowed to access methods that can perform static operations, i.e. those, which do not require object initialization.

      What are the advantages and disadvantages of CASCADE STYLE SHEETS?
      External Style Sheets
      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
      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
      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
      This method can not control styles for multiple documents at once
      Inline Styles
      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
      Does not distance style information from content (a main goal of SGML/HTML) Can not control styles for multiple documents at once Author can not create or control classes of elements to control multiple element types within the document Selector grouping methods can not be used to create complex element addressing scenarios

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

      When you want to show some part of a text displayed on an HTML page in red font color? What different possibilities are there to do this? What are the advantages/disadvantages of these methods?
      There are 2 ways to show some part of a text in red:
      1. Using HTML tag <font color=”red”>
      2. Using HTML tag <span style=”color: red”>

      When viewing an HTML page in a Browser, the Browser often keeps this page in its cache. What can be possible advantages/disadvantages of page caching? How can you prevent caching of a certain page (please give several alternate solutions)?
      When you use the metatag in the header section at the beginning of an HTML Web page, the Web page may still be cached in the Temporary Internet Files folder.
      A page that Internet Explorer is browsing is not cached until half of the 64 KB buffer is filled. Usually, metatags are inserted in the header section of an HTML document, which appears at the beginning of the document. When the HTML code is parsed, it is read from top to bottom. When the metatag is read, Internet Explorer looks for the existence of the page in cache at that exact moment. If it is there, it is removed. To properly prevent the Web page from appearing in the cache, place another header section at the end of the HTML document.

      What are the different ways to login to a remote server? Explain the means, advantages and disadvantages?
      There is at least 3 ways to logon to a remote server:
      Use ssh or telnet if you concern with security
      You can also use rlogin to logon to a remote server.

      Please give a regular expression (preferably Perl/PREG style), which can be used to identify the URL from within a HTML link tag.
      Try this: /href=”([^”]*)”/i

      How can I use the COM components in php?
      The COM class provides a framework to integrate (D)COM components into your PHP scripts.
      string COM::COM( string module_name [, string server_name [, int codepage]]) – COM class constructor.
      module_name: name or class-id of the requested component.
      server_name: name of the DCOM server from which the component should be fetched. If NULL, localhost is assumed. To allow DCOM com, allow_dcom has to be set to TRUE in php.ini.
      codepage – specifies the codepage that is used to convert php-strings to unicode-strings and vice versa. Possible values are CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 and CP_UTF8.
      $word->Visible = 1; //open an empty document
      $word->Documents->Add(); //do some weird stuff
      $word->Selection->TypeText(”This is a test…”);
      $word->Documents[1]->SaveAs(”Useless test.doc”); //closing word
      $word->Quit(); //free the object
      $word = null;

      How many ways we can give the output to a browser?
      HTML output
      PHP, ASP, JSP, Servlet Function
      Script Language output Function
      Different Type of embedded Package to output to a browser

      What is the default session time in php and how can I change it?
      The default session time in php is until closing of browser


      PHP Interview Questions part 2

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

      What Is a Session?
      A session is a logical object created by the PHP engine to allow you to preserve data across subsequent HTTP requests.

      There is only one session object available to your PHP scripts at any time. Data saved to the session by a script can be retrieved by the same script or another script when requested from the same visitor.

      Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor.

      What is meant by PEAR in php?
      PEAR is the next revolution in PHP. This repository is bringing higher level programming to PHP. PEAR is a framework and distribution system for reusable PHP components. It eases installation by bringing an automated wizard, and packing the strength and experience of PHP users into a nicely organised OOP library. PEAR also provides a command-line interface that can be used to automatically install “packages”
      PEAR is short for “PHP Extension and Application Repository” and is pronounced just like the fruit. The purpose of PEAR is to provide:
      A structured library of open-sourced code for PHP users
      A system for code distribution and package maintenance
      A standard style for code written in PHP
      The PHP Foundation Classes (PFC),
      The PHP Extension Community Library (PECL),
      A web site, mailing lists and download mirrors to support the PHP/PEAR community
      PEAR is a community-driven project with the PEAR Group as the governing body. The project has been founded by Stig S. Bakken in 1999 and quite a lot of people have joined the project since then.

      How can we know the number of days between two given dates using PHP?
      Simple arithmetic:
      $date1 = date(’Y-m-d’);
      $date2 = ‘2006-07-01′;
      $days = (strtotime() – strtotime()) / (60 * 60 * 24);
      echo “Number of days since ‘2006-07-01′: $days”;

      What is the difference between $message and $$message?
      Anwser 1:
      $message is a simple variable whereas $$message is a reference variable. Example:
      $user = ‘bob’
      is equivalent to
      $holder = ‘user’;
      $$holder = ‘bob’;

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

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

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

      How do you define a constant?
      Via define() directive, like define (”MYCONSTANT”, 100);

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

      But require() and include() will do it as many times they are asked to do.
      Anwser 2:
      The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. The major difference between include() and require() is that in failure include() produces a warning message whereas require() produces a fatal errors.
      Anwser 3:
      All three are used to an include file into the current page.
      If the file is not present, require(), calls a fatal error, while in include() does not.
      The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. It des not call a fatal error if file not exists. require_once() does the same as include_once(), but it calls a fatal error if file not exists.
      Anwser 4:
      File will not be included more than once. If we want to include a file once only and further calling of the file will be ignored then we have to use the PHP function include_once(). This will prevent problems with function redefinitions, variable value reassignments, etc.

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

      Anwser 2:
      string urlencode(str) – Returns the URL encoded version of the input string. String values to be used in URL query string need to be URL encoded. In the URL encoded version:
      Alphanumeric characters are maintained as is.
      Space characters are converted to “+” characters.
      Other non-alphanumeric characters are converted “%” followed by two hex digits representing the converted character.
      string urldecode(str) – Returns the original string of the input URL encoded string.

      For example:
      $discount =”10.00%”;
      $url = “”.urlencode($discount);
      echo $url;

      You will get “″.

      How To Get the Uploaded File Information in the Receiving Script?
      Once the Web server received the uploaded file, it will call the PHP script specified in the form action attribute to process them. This receiving PHP script can get the uploaded file information through the predefined array called $_FILES. Uploaded file information is organized in $_FILES as a two-dimensional array as:
      $_FILES[$fieldName][’name’] – The Original file name on the browser system.
      $_FILES[$fieldName][’type’] – The file type determined by the browser.
      $_FILES[$fieldName][’size’] – The Number of bytes of the file content.
      $_FILES[$fieldName][’tmp_name’] – The temporary filename of the file in which the uploaded file was stored on the server.
      $_FILES[$fieldName][’error’] – The error code associated with this file upload.
      The $fieldName is the name used in the .

      How can I execute a PHP script using command line?
      Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument. For example, “php myScript.php”, assuming “php” is the command to invoke the CLI program.
      Be aware that if your PHP script was written for the Web CGI interface, it may not execute properly in command line environment.

      I am trying to assign a variable the value of 0123, but it keeps coming up with a different number, what’s the problem?
      PHP Interpreter treats numbers beginning with 0 as octal. Look at the similar PHP interview questions for more numeric problems.

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

      How can we encrypt the username and password using PHP?

      You can encrypt a password with the following Mysql>SET PASSWORD=PASSWORD(”Password”);
      You can use the MySQL PASSWORD() function to encrypt username and password. For example,
      INSERT into user (password, …) VALUES (PASSWORD($password”)), …);

      How do you pass a variable by value?
      Just like in C++, put an ampersand in front of it, like $a = &$b

      When are you supposed to use endif to end the conditional statement?
      When the original if was followed by : and then the code block without braces.

      How can we send mail using JavaScript?
      No. There is no way to send emails directly using JavaScript.
      But you can use JavaScript to execute a client side email program send the email using the “mailto” code. Here is an example:
      function myfunction(form)
      return true;

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

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

      How do I find out the number of parameters passed into function9. ?
      func_num_args() function returns the number of parameters passed in.

      If the variable $a is equal to 5 and variable $b is equal to character a, what’s the value of $$b?
      100, it’s a reference to existing variable.

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

      Please click the links below”
      .” to submit comments about

      $comment = ‘I want to say: “It\’s a good site! :->”‘;
      $comment = urlencode($comment);

      .”It’s an excellent site!

      $comment = ‘This visitor said: “It\’s an average site! :-(”‘;
      $comment = urlencode($comment);

      .”It’s an average site.


      Are objects passed by value or by reference?
      Everything is passed by value.

      How do you call a constructor for a parent class?

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

      What’s the special meaning of __sleep and __wakeup?
      __sleep returns the array of all the variables than need to be saved, while __wakeup retrieves them.

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

      Why doesn’t the following code print the newline properly?
      Because inside the single quotes the \n character is not interpreted as newline, just as a sequence of two characters – \ and n.

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

      How can we extract string ‘ ‘ from a string using regular expression of php?
      We can use the preg_match() function with “/.*@(.*)$/” as
      the regular expression pattern. For example:
      echo $data[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?
      Anwser 1:
      When we submit a form, which has the GET method it displays pair of name/value used in the form at the address bar of the browser preceded by url. Post method doesn’t display these values.
      Anwser 2:
      When you want to send short or small data, not containing ASCII characters, then you can use GET” Method. But for long data sending, say more then 100 character you can use POST method.
      Once most important difference is when you are sending the form with GET method. You can see the output which you are sending in the address bar. Whereas if you send the form with POST” method then user can not see that information.
      Anwser 3:
      What are “GET” and “POST”?
      GET and POST are methods used to send data to the server: With the GET method, the browser appends the data onto the URL. With the Post method, the data is sent as “standard input.”
      Major Difference
      In simple words, in POST method data is sent by standard input (nothing shown in URL when posting while in GET method data is sent through query string.
      Ex: Assume we are logging in with username and password.
      GET: we are submitting a form to login.php, when we do submit or similar action, values are sent through visible query string (notice ./login.php?username=…&password=… as URL when executing the script login.php) and is retrieved by login.php by $_GET[’username’] and $_GET[’password’].
      POST: we are submitting a form to login.php, when we do submit or similar action, values are sent through invisible standard input (notice ./login.php) and is retrieved by login.php by $_POST[’username’] and $_POST[’password’].
      POST is assumed more secure and we can send lot more data than that of GET method is limited (they say Internet Explorer can take care of maximum 2083 character as a query string).
      Anwser 4:
      In the get method the data made available to the action page ( where data is received ) by the URL so data can be seen in the address bar. Not advisable if you are sending login info like password etc. In the post method the data will be available as data blocks and not as query string in case of get method.
      Anwser 5:
      When we submit a form, which has the GET method it pass value in the form of query string (set of name/value pair) and display along with URL. With GET we can a small data submit from the form (a set of 255 character) whereas Post method doesn’t display value with URL. It passes value in the form of Object and we can submit large data from the form.
      Anwser 6:
      On the server side, the main difference between GET and POST is where the submitted is stored. The $_GET array stores data submitted by the GET method. The $_POST array stores data submitted by the POST method.
      On the browser side, the difference is that data submitted by the GET method will be displayed in the browser’s address field. Data submitted by the POST method will not be displayed anywhere on the browser.
      GET method is mostly used for submitting a small amount and less sensitive data. POST method is mostly used for submitting a large amount or sensitive data.

      What is the difference between the functions unlink and unset?
      unlink() is a function for file system handling. It will simply delete the file in context.
      unset() is a function for variable management. It will make a variable undefined.

      How come the code works, but doesn’t for two-dimensional array of mine?
      Any time you have an array with more than one dimension, complex parsing syntax is required. print “Contents: {$arr[1][2]}” would’ve worked.

      How can we register the variables into a session?
      $_SESSION[’var’] = ‘value’;

      What is the difference between characters 23 and \x23?
      The first one is octal 23, the second is hex 23.

      With a heredoc syntax, do I get variable substitution inside the heredoc contents?

      How can we submit form without a submit button?
      We can use a simple JavaScript code linked to an event trigger of any form field. In the JavaScript code, we can call the document.form.submit() function to submit the form. For example:

      How can we create a database using PHP and mysql?
      We can create MySQL database with the use of mysql_create_db($databaseName) to create a database.

      How many ways we can retrieve the date in result set of mysql using php?
      As individual objects so single record or as a set or arrays.

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


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

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

      I am writing an application in PHP that outputs a printable version of driving directions. It contains some long sentences, and I am a neat freak, and would like to make sure that no line exceeds 50 characters. How do I accomplish that with PHP?
      On large strings that need to be formatted according to some length specifications, use wordwrap() or chunk_split().

      What’s the output of the ucwords function in this example?
      print $formatted;
      ucwords() makes every first letter of every word capital, but it does not lower-case anything else. To avoid this, and get a properly formatted string, it’s worth using strtolower() first.

      What’s the difference between htmlentities() and htmlspecialchars()?
      htmlspecialchars only takes care of , single quote ‘, double quote ” and ampersand. htmlentities translates all occurrences of character sequences that have different meaning in HTML.


      PHP Interview Questions part 1

      1. Find the output of :
      $a = rand(1,2);
      if($a==0) {
      echo “Red”;
      else if($a>2) {
      echo “White”;
      else if($a) {
      echo “Blue”;
      else if($a=1) {
      echo “Green”;
      echo “Clear”;
      a.) Red
      b.) White
      c.) Blue
      d.) Green
      e.) Clear

      2. Find the output of :
      echo substr(”artichoke”,-3,-2);
      a.) ar
      b.) ho
      c.) rtic
      d.) o
      e.) oke

      3. The PHP syntax is most similar to:
      a.) VB Script
      b.) P
      erl and C
      c.) .Net
      4. What is the output of this PHP code?
      $list = array(”clock”,”scissors”,”pen”,”yak”);
      $list[] = “cow”;
      $list[] = “dragon”;
      print “$list[4]”;
      a.) clock,scissors,pen,yak
      b.) yak
      c.) cow
      d.) dragon
      e.) pen

      5. Find the output:
      if ((string)’-1′)
      print ‘ouch’;
      print ‘echo’;
      a.) None
      b.) echo
      c.) ouch

      6. What is the out of this code?

      if (is_float($x) == TRUE)
      } printf(”%-02s$x”,$y);
      a.) 003.14
      b.) 003
      c.) -02s3.14
      d.) -33.14
      e.) 303.14

      7. In PHP, what is the output here?
      $x = “”;
      switch ($x) {
      case “0″: echo “String”; break;
      case 0: echo “Integer”; break;
      case NULL: echo “NULL”; break;
      case FALSE: echo “Boolean”; break;
      case “”: echo “Empty string”; break;
      default: echo “Something else”; break;
      a.) String
      b.) Integer
      c.) NULL
      d.) Boolean
      e.) Empty string
      f.) Something else

      8. What is the output for:
      $a=htmlspecialchars(”O\’Hare & Max was here!”);
      echo substr_count($a,”&”);
      a.) 5
      b.) 8
      c.) 1
      d.) 0

      9. What is the value of $y after execution:
      do {
      } while($x>0);
      a.) 1
      b.) 5
      c.) 9
      d.) 15
      e.) 17


      1. c.) Blue

      2. d.) o
      3. b.) Perl and C
      4. c.) cow
      5. c.) ouch
      6. a.) 003.14
      7. b.) Integer
      8. c.) 1
      9. e.) 17