php oops interview questions

130
PHP OOPS Interview Questions & Answers 1) Explain what is object oriented programming language? Object oriented programming language allows concepts such as modularity, encapsulation, polymorphism and inheritance. Objects are said to be the most important part of object oriented language. Concept revolves around making simulation programs around an bject. Organize a program around its data (object)& set well define interface to that data. i.e. objects and a set of well defined interfaces to that data. OOP is the common abbreviation for Object- Oriented Programming. OOps have many properties such as DataHiding,Inheritence,Data Absraction,Data Encapsulation and many more. 2) Name some languages which have object oriented language andcharacteristics? Some of the languages which have object oriented languages present in them are ABAP, ECMA Script, C++, Perl, LISP, C#, Tcl, VB, Ruby, Python, PHP, etc. Popularity of these languages has increased considerably as they can solve complex problems with ease. 3) Explain about UML? UML or unified modeling language is regarded to implement complete specifications and features of object oriented language. Abstract design can be implemented in object oriented programming languages. It lacks implementation of polymorphism on message arguments which is a OOPs feature. 4) Explain the meaning of object in object oriented programming? Languages which are called as object oriented almost implement everything in them as objects such as punctuations, characters, prototypes, classes, modules, blocks, etc. They were designed to facilitate and implement object oriented methods.

Upload: nadeem-shaikh

Post on 29-Nov-2014

546 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: PHP OOPS Interview Questions

PHP OOPS Interview Questions & Answers 1) Explain what is object oriented programming language?

Object oriented programming language allows concepts such as modularity, encapsulation, polymorphism and inheritance. Objects are said to be the most important part of object oriented language. 

 Concept revolves around making simulation programs around an bject. Organize a program around its data (object)& set well define interface to that data. i.e. objects and a set of well defined interfaces to that data. OOP is the common abbreviation for Object-Oriented Programming. OOps have many properties such as DataHiding,Inheritence,Data Absraction,Data Encapsulation and many more. 

 2) Name some languages which have object oriented language

andcharacteristics?

Some of the languages which have object oriented languages present in them are ABAP, ECMA Script, C++, Perl, LISP, C#, Tcl, VB, Ruby, Python, PHP, etc. Popularity of these languages has increased considerably as they can solve complex problems with ease. 

3) Explain about UML?

UML or unified modeling language is regarded to implement complete specifications and features of object oriented language. 

 Abstract design can be implemented in object oriented programming languages. 

 It lacks implementation of polymorphism on message arguments which is a OOPs feature. 

4) Explain the meaning of object in object oriented programming? 

Languages which are called as object oriented almost implement everything in them as objects such as punctuations, characters, prototypes, classes, modules, blocks, etc. They were designed to facilitate and implement object oriented methods. 

 

 

 5) Explain about message passing in object oriented programming?

Message passing is a method by which an object sends data to another object or requests other object to invoke method. This is also known as interfacing.

Page 2: PHP OOPS Interview Questions

 It acts like a messenger from one object to other object to convey specific instructions.

6) State about Java and its relation to Object oriented programming? 

Java is widely used and its share is increasing considerably which is partly due to its close resemblance to object oriented languages such as C and C++. Code written in Java can be transported to many different platforms without changing it. It implements virtual machine. 

 

7) What are the problems faced by the developer using object oriented programming language? 

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

 a) Object oriented uses design patterns which can be referred to as anything in

general.

b) Repeatable solution to a problem can cause concern and disagreements and it is one of the major problems in software design. 

 

8 ) State some of the advantages of object oriented programming?

Some of the advantages of object oriented programming are as follows: -

a) A clear modular structure can be obtained which can be used as a prototype and it will not reveal the mechanism behind the design. It does have a clear interface. 

b) Ease of maintenance and modification to the existing objects can be done with ease.

c) A good framework is provided which facilitates in creating rich GUI applications. 

 

9 ) Explain about inheritance in OOPS? 

Objects in one class can acquire properties of the objects in other classes by way of inheritance. Reusability which is a major factor is provided in object oriented programming which adds features to a class without modifying it. New class can be obtained from a class which is already present.

Page 3: PHP OOPS Interview Questions

 

10) Explain about the relationship between object oriented programming anddatabases?

Object oriented programming and relational database programming are almost similar in software engineering. RDBMS will not store objects directly and that’s where object oriented programming comes into play. Object relational mapping is one such solution. 

 

11) Explain about a class in OOP? 

In Object oriented programming usage of class often occurs. A class defines the characteristics of an object and its behaviors. 

 This defines the nature and functioning of a specified object to which it is assigned. Code for a class should be encapsulated. 

 

 12) Explain the usage of encapsulation? 

Encapsulation specifies the different classes which can use the members of an object. 

 The main goal of encapsulation is to provide an interface to clients which decrease the dependency on those features and parts which are likely to change in future. This facilitates easy changes to the code and features. 

 

 

13) Explain about abstraction?

Abstraction can also be achieved through composition. It solves a complex problem by defining only those classes which are relevant to the problem and not involving the whole complex code into play. 

14) Explain what a method is? 

A method will affect only a particular object to which it is specified. Methods are verbs meaning they define actions which a particular object will perform. It also defines various other characteristics of a particular object.

Page 4: PHP OOPS Interview Questions

 

15) Name the different Creational patterns in OO design? 

There are three patterns of design out of which Creational patterns play an important role the various patterns described underneath this are: - 

a) Factory pattern

b) Single ton pattern

c) Prototype pattern

d) Abstract factory pattern

e) Builder pattern

16) Explain about realistic modeling?

As we live in a world of objects, it logically follows that the object oriented approach models the real world accurately. The object oriented approach allows you to identify entities as objects having attributes and behavior. 

 

17) Explain about the analysis phase? 

The anlaysis or the object oriented analysis phase considers the system as a solution to a problem in its environment or domain. Developer concentrates on obtaining as much information as possible about the problem. Critical requirements needs to be identified. 

 

 

 

 1) Explain the rationale behind Object Oriented concepts?

Object oriented concepts form the base of all modern programming languages. Understanding the basic concepts of object-orientation helps a developer to use various modern day programming languages, more effectively.

2) Explain about Object oriented programming?

Object oriented programming is one of the most popular methodologies in software development. It offers a powerful model for creating computer programs. It speeds the program development process, improves maintenance and enhances reusability of programs. 

Page 5: PHP OOPS Interview Questions

3) Explain what is an object?

An object is a combination of messages and data. Objects can receive and send messages and use messages to interact with each other. The messages contain information that is to be passed to the recipient object. 

 

 

4) Explain the implementation phase with respect to OOP? 

The design phase is followed by OOP, which is the implementation phase. OOP provides specifications for writing programs in a programming language. During the implementation phase, programming is done as per the requirements gathered during the analysis and design phases. 

 

5) Explain about the Design Phase? 

In the design phase, the developers of the system document their understanding of the system. Design generates the blue print of the system that is to be implemented. The first step in creating an object oriented design is the identification of classes and their relationships. 

 

6) Explain about a class?

Class describes the nature of a particular thing. Structure and modularity is provided by a Class in object oriented programming environment. Characteristics of the class should be understandable by an ordinary non programmer and it should also convey the meaning of the problem statement to him. Class acts like a blue print. 

 

 7) Explain about instance in object oriented programming? 

Every class and an object have an instance. Instance of a particular object is created at runtime. Values defined for a particular object define its State. Instance of an object explains the relation ship between different elements. 

8 ) Explain about inheritance? 

Inheritance revolves around the concept of inheriting knowledge and class attributes

Page 6: PHP OOPS Interview Questions

from the parent class. In general sense a sub class tries to acquire characteristics from a parent class and they can also have their own characteristics. Inheritance forms an important concept in object oriented programming. 

9) Explain about multiple inheritance? 

Inheritance involves inheriting characteristics from its parents also they can have their own characteristics. In multiple inheritance a class can have characteristics from multiple parents or classes. A sub class can have characteristics from multiple parents and still can have its own characteristics. 

 

 

10) Explain about encapsulation? 

Encapsulation passes the message without revealing the exact functional details of the class. It allows only the relevant information to the user without revealing the functional mechanism through which a particular class had functioned. 

11) Explain about abstraction? 

 

 Abstraction simplifies a complex problem to a simpler problem by specifying and modeling the class to the relevant problem scenario. It simplifies the problem by giving the class its specific class of inheritance. Composition also helps in solving the problem to an extent.

12) Explain the mechanism of composition?

Composition helps to simplify a complex problem into an easier problem. It makes different classes and objects to interact with each other thus making the problem to be solved automatically. It interacts with the problem by making different classes and objects to send a message to each other. 

 

 

13) Explain about polymorphism?

Polymorphism helps a sub class to behave like a parent class. When an object belonging to different data types respond to methods which have a same name, the only condition being that those methods should perform different function. 

Page 7: PHP OOPS Interview Questions

14) Explain about overriding polymorphism? 

Overriding polymorphism is known to occur when a data type can perform different functions. For example an addition operator can perform different functions such as addition, float addition etc. Overriding polymorphism is generally used in complex projects where the use of a parameter is more. 

15) Explain about object oriented databases? 

Object oriented databases are very popular such as relational database management systems. Object oriented databases systems use specific structure through which they extract data and they combine the data for a specific output. These DBMS use object oriented languages to make the process easier. 

 

 16) Explain about parametric polymorphism?

Parametric polymorphism is supported by many object oriented languages and they are very important for object oriented techniques. In parametric polymorphism code is written without any specification for the type of data present. Hence it can be used any number of times. 

17) What are all the languages which support OOP? 

There are several programming languages which are implementing OOP because of its close proximity to solve real life problems. Languages such as Python, Ruby, Ruby on rails, Perl, PHP, Coldfusion, etc use OOP. Still many languages prefer to use DOM based languages due to the ease in coding. 

 var gaJsHost = ((”https:” == document.location.protocol) try {

var pageTracker = _gat._getTracker(”UA-1855756-5?);

pageTracker._trackPageview(); 

} catch(err) {}

Page 8: PHP OOPS Interview Questions

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?Ans : 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 100character you can use “POST” method. Once most imp diff is when you are sending the form with“Get” method. You can see the output which you are sendingin the addressbar. Whereas if you send the form with “POST”method then user can not see that information. Get is an Idompotent method. (Idompotent: The side-effects of N > 0 identical requests is the same as for a single request. The methods GET, HEAD, PUT and DELETE share this property.)”GET” is basically for just getting (retrieving: quering db for data & retriving) data whereas “POST” may involve anything, like storing or updating data, or ordering a product, or sending E-mail. In GET form data is to be encoded (by a browser) into a URL while the latter means that the form data is to appear within a message body. For GET in IE, Maximum URL Length Is 2,083 Characters in Internet Explorer (Q208427) or approximatly 1k. 

 2 In simple words, in POST method data is sent by standered 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 similaraction to post the form values are sent through ‘visible’ query string andis retrieved by login.php by $_GET[’username’] and $_GET[’password’].POST :we are submitting a form to login.php, when we do ’submit’ orsimilar action to post the form, values are sent through ‘invisible’ standeredinput (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 GETmethod is limited(they say Internet Explorer can take care of maximum 2083 characteras a query string). 

 3. Who is the father of PHP and explain the changes in PHP versions? Ans : Rasmus Lerdorf is the father of PHP.

PHP 5.1. Beta

MySQL 5.0

4. How can we submit a form without a submit button?

Ans : I can submit a form in many ways, for e.g.

1. When user click on checkbox, or drop down.

2. When user click on radio button.

3. At the end of the form I will type “Click here.

to submit” & link text to the processing file.

Page 9: PHP OOPS Interview Questions

 form.submit(); Trigger the JavaScript code on any event ( like onselect of drop down list box, onfocus, etc ) document.myform.submit();This will submit the form. We can submit a from without a submit button help ho javascript like. <a href=”void(0)” rel=”nofollow”>Submit Me</a> 5. In how many ways we can retrieve the date in the result set of mysql using PHP? mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both.

mysql_fetch_assoc — Fetch a result row as an associative array.

mysql_fetch_object — Fetch a result row as an object.

mysql_fetch_row — Get a result row as an enumerated array. 6.What is the difference between mysql_fetch_object and mysql_fetch_array? mysql_fetch_array — Fetch a result row as an associative ARRAY, a numeric array, or bothmysql_fetch_object — Fetch a result row as an OBJECT. mysql_fetch_object() is similar to mysql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names). Speed-wise, the function is identical to mysql_fetch_array(),and almost as quick as mysql_fetch_row() (the difference isinsignificant). mysql_fetch_object() is similar to mysql_fetch_array(),with one difference - an object is returned,instead of an array. Indirectly, that means that you can onlyaccess the data by the field names, and not by their offsets(numbers are illegal property names).

7 What is the difference between $message and $$message? Both are variables only$message is a variable and if used with print statement, the content of the $message variable will be displayed. Where as with $$message variable, the content of the $message will also be treated as variable and the content of that variable will be displayed. For ex: If $message contains “var”, then it displays the content of $var on the screen. 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$message is a variable

$$message is a variable variable.

Page 10: PHP OOPS Interview Questions

A variable variable allows us to change the name of a variable dynamically. $message is variable whereas $$message is dynamic varibale. $message is variable whereas $$message is Dynamic variable.

eg.

$user=”bob” is equivalent to $holder=”user”;

$$holder=”bob”; 8.How can we extract string ‘abc.com ‘ from a string ‘http:// [email protected]’ using regular expression of PHP? preg_match(”|[^@]*@(.*)|im”, $text, $output); $output will give result in second index of array, means $output[1] is answer. or $exploded[1] should have abc.com or echo mailto:substr(">substr); or preg_match(”/^(http:\/\/info@)?([^\/]+)/i”, $data); orecho $data[2]; preg_match(’/^http:\/\/.+@(.+)$/’,$found); orecho $found[1]; Use the function split split which returns an array any second element of the returned array will hold the value as abc.com. 9 .How can we create a database using PHP and mysql? $sql = ‘CREATE DATABASE my_db’;

if (mysql_query($sql, $link))

{

echo “Database my_db created successfully\n”;

}

else

{

echo ‘Error creating database: ‘ . mysql_error() . “\n”;

Page 11: PHP OOPS Interview Questions

} mysql_create_db() should work

10.What are the differences between require and include, include_once? require_once(),include_once() both the functions include and evalute the specified file only onceand if the specified file is opened previous to the present call occurrance, it will not be done again.But require() and include() will do it as many times they are asked to do. 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. 11.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 12. What are the different tables present in mysql, which type of table is generated when we are creating a table in the following syntax: create table employee(eno int(2),ename varchar(10)) ? Total 5 types of tables we can create

1. MyISAM

2. Heap

3. Merge

4. INNO DB

5. ISAM

MyISAM is the default storage engine as of MySQL 3.23.Table Types are

· ISAM(Index Sequential Access Method)

· MyISAM

o Static

o Dynamic

Page 12: PHP OOPS Interview Questions

o Compress

· Merge

· Heap (Fastest tables because it stores in to the RAM)

· BDB

· InnoDB (Transaction safe table) When you fire the above create query MySQL will create the Dynamic table.

MyISAM Table Type is created, if u not specified any table type then default will be applied and MyISAM is defaultOrTable Types are

· ISAM(Index Sequential Access Method)

· MyISAM

o Static

o Dynamic

o Compress

· Merge

· Heap (Fastest tables because it stores in to the RAM)

· BDB

· InnoDB (Transaction safe table) When you fire the above create query MySQL will create the Dynamic table. Total 5 types of tables we can create

1. MyISAM

2. Heap

3. Merge

4. INNO DB

5. ISAM

MyISAM is the default storage engine as of MySQL 3.23. MyISAM: This is default. Based on Indexed Sequntial Access Method. The above SQL will create a MyISA table.

Page 13: PHP OOPS Interview Questions

ISAM : same.

HEAP : Fast data access, but will loose data if there is a crash. Cannot have BLOB, TEXT & AUTO INCRIMENT fields.

BDB : Supports Transactions using COMMIT & ROLLBACK. Slower that others.

InoDB : same as BDB

13 Functions in IMAP, POP3 AND LDAP? 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. 

 14 How can I execute a PHP script using command line? PHP can be executed from Command Line, using the SAP Interface (SAPI) or Server Application Programming Interface named CLI which means Command Line Interface.

The CLI SAPI was released for the first time with PHP 4.2.0, but was still experimental and had to be explicitly enabled with –enable-cli when running ./configure. Since PHP 4.3.0 the CLI SAPI is no longer experimental and the option –enable-cli is on by default. You may use –disable-cli to disable it. Through php parse you can execute PHP script using command line. By default location of php parser is so set the path of this directory and just use as following

#php sample.phpAs of version 4.3.0, PHP supports a new SAPI type (Server Application Programming Interface) named CLI which means Command Line Interface. Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument. For example, "php myScript.php", assuming "php" is the command to invoke the CLI program.

Be aware that if your PHP script was written for the Web CGI interface, it may not execute properly in command line environment. 15 Suppose your Zend engine supports the mode <? ?> Then how can u configure your PHP Zend engine to support <?PHP ?> mode ? Its already supported. In php.ini file: set

Page 14: PHP OOPS Interview Questions

 short_open_tag=on to make PHP support

16 Shopping cart online validation i.e. how can we configure Paypal, etc.? Returns string with after inserting HTML line breaks before all newlines in a string 

 17 What is meant by nl2br()? AES_ENCRYPT(str,key_str) , AES_DECRYPT(crypt_str,key_str) nl2br — Inserts HTML line breaks before all newlines in a string

Description

string nl2br ( string string) Returns string with ‘’ inserted before all newlines. Note: Starting with PHP 4.0.5, nl2br() is now XHTML compliant. All versions before 4.0.5 will return string with ‘’ inserted before newlines instead of ‘’. Example 1. using nl2br() this will output : foo isn’t

bar 18 Draw the architecture of Zend engine?CRYPT()

MD5()

19 What are the current versions of apache, PHP, and mysql? or information about latest version of Apache, Php and Mysql please visits the following sites respectively. PHP: php5.1.2

MySQL: MySQL 5.1

Apache: Apache 2.1

20 What are the reasons for selecting lamp (linux, apache, mysql, PHP) instead of combination of other software programmes, servers and operating systems? All of those are open source resource. Security of linux is very very more than windows. Apache is a better server that IIS both in functionality and security.

Page 15: PHP OOPS Interview Questions

 Mysql is world most popular open source database. Php is more faster that asp or any other scripting language. 21 How can we encrypt and decrypt a data present in a mysql table using mysql? AES_ENCRYPT () and AES_DECRYPT ()

22 How can we encrypt the username and password using PHP? You can encrypt a password with the following

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

We can encode data using base64_encode($string) and can decode using base64_decode($string); 23 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. 24 What are the differences between procedure-oriented languages and object-oriented languages? Traditional programming has the following characteristics: Functions are written sequentially, so that a change in programming can affect any code that follows it.If a function is used multiple times in a system (i.e., a piece of code that manages the date), it is often simply cut and pasted into each program (i.e., a change log, order function, fulfillment system, etc). If a date change is needed (i.e., Y2K when the code needed to be changed to handle four numerical digits instead of two), all these pieces of code must be found, modified, and tested. 

Code (sequences of computer instructions) and data (information on which the

Page 16: PHP OOPS Interview Questions

instructions operates on) are kept separate. Multiple sets of code can access and modify one set of data. One set of code may rely on data in multiple places. Multiple sets of code and data are required to work together. Changes made to any of the code sets and data sets can cause problems through out the system. Object-Oriented programming takes a radically different approach: Code and data are merged into one indivisible item – an object (the term "component" has also been used to describe an object.) An object is an abstraction of a set of real-world things (for example, an object may be created around "date"). The object would contain all information and functionality for that thing (A dateobject it may contain labels like January, February, Tuesday, Wednesday. It may contain functionality that manages leap years, determines if it is a business day or a holiday, etc., See Fig. 1). Ideally, information about a particular thing should reside in only one place in a system. The information within an object is encapsulated (or hidden) from the rest of the system. 

A system is composed of multiple objects (i.e., date function, reports, order processing, etc., See Fig 2). When one object needs information from another object, a request is sent asking for specific information. (for example, a report object may need to know what today’s date is and will send a request to the date object) These requests are called messages and each object has an interface that manages messages.OO programming languages include features such as "class", "instance", "inheritance", and "polymorphism" that increase the power and flexibility of an object.

25 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 whichnames 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

{

Page 17: PHP OOPS Interview Questions

private:

mylinkage * prev;

mylinkage * next; protected:

friend void set_prev(mylinkage* L, mylinkage* N);

void set_next(mylinkage* L); public:

mylinkage * succ();

mylinkage * pred();

mylinkage();

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

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

class C

{

friend int B::f1();

};

class B

{

int f1();

};

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

Page 18: PHP OOPS Interview Questions

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. 26 What are the differences between public, private, protected, static, transient, final and volatile? element Class Interface.

Data field Method Constructor.

modifier top level nested top level nested.

(outer) (inner) (outer) (inner).

final yes yes no yes yes no no.

private yes yes yes no yes no yes.

protected yes yes yes no yes no yes.

public yes yes yes yes yes yes yes.

static yes yes no no yes no yes.

transient yes no no no no no no.

volatile yes no no no no no no. 27 What are the different types of errors in PHP? here are three basic types of runtime errors in PHP: Three are three types of errors 1) Fatal errors 2) Parser errors 3) Startup errors. 1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script - for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all - although you can change this default behaviour. 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. 

Page 19: PHP OOPS Interview Questions

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 behaviour is to display them to the user when they take place.Internally, these variations are represented by twelve different error types Three are three types of errors: 1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script - for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all - although, as you will see, you can change this default behaviour. 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 behaviour is to display them to the user when they take place.

28 What is the functionality of the function strstr and stristr? string strstr ( string haystack, string needle )

Returns part of haystack string from the first occurrence of needle to the end of haystack. $domain = strstr($email, ‘@’);

echo $domain; // prints @example.com stristr() is the case insensitive version of strstr() strstr() returns part of a given string from the first occurrence of a given substring to the end of the string. For example: strstr.

stristr() is idential to strstr() except that it is case insensitive. 29 How can we convert asp pages to PHP pages? You can download asp2php front end application from the site http://asp2php.naken.cc/">http://asp2php.naken.cc/. 30 What is the functionality of the function htmlentities() and htmlsecialchars()? htmlspecialchars : Convert some special characters to HTML entities (Only the most widley used)

htmlentities : Convert ALL special characters to HTML entities. 

Page 20: PHP OOPS Interview Questions

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.

31 How can we get second of the current time using date function? $second = date("s"); 32 What is meant by urlencode and urldocode? urlencode : Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. urldocode : Decodes URL-encoded string string urlencode(str)

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

string urldocode(str)

this will simple decode the GET variable’s value

Like it echo (urldecode($_GET_VARS[var])) will output “Hello world” 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. 33 What is the difference between the functions unlink and unset? unlink is a function for file system handling. It will simply delete the file in context

unset will set UNSET the variable. e.g unlink() deletes the given file from the file system.

unset() makes a variable undefined. unlink: is used to delete a file

unset is used to destroy an eralier declared variable

34 How can we register the variables into a session? $_SESSION[’name’] = “Chinmay”;

Page 21: PHP OOPS Interview Questions

 To destroy a session: unset($_SESSION[’name’]); $_SESSION[’var’] = ‘value’; or Old way (deprecated):

$var = ‘value’;

session_register(’var’); or session_register($ur_session_var); We can use the session_register ($ur_session_var) function.35 How can we get the properties (size, type, width, height) of an image using PHP image functions?To know the Image type use exif_imagetype () function.

To know the Image size use getimagesize () function.

To know the image width use imagesx () function.

To know the image height use imagesy() function. getimagesize — Get the size of an image.

image_type_to_extension — Get file extension for image type.

imagesx — Get image width.

imagesy — Get image height. 

 36 What is the maximum size of a file that can be uploaded using PHP and how can we change this? In Php.ini file: upload_max_filesize integer. The maximum size of an uploaded file.

When an integer is used, the value is measured in bytes. You can change maximum size of a file set upload_max_filesize variable in php.ini file

37 How can we increase the execution time of a PHP script? Use set_time_limit(int) where int is the number of seconds forexecution of the script. If it’s set to 0 it’s unlimited. Default valueis 30. 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. 

Page 22: PHP OOPS Interview Questions

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. Set max_execution_time variable in php.ini file to your desired time in second. 

 38 How can we take a backup of a mysql table and how can we restore it. ? To backup: BACKUP TABLE tbl_name[,tbl_name…] TO ‘/path/to/backup/directory’RESTORE TABLE tbl_name[,tbl_name…] FROM ‘/path/to/backup/directory’ mysqldump: Dumping Table Structure andData Utility to dump a database or a collection of database for backup or for transferring the data to another SQL server (not necessarily a MySQL server). The dump will contain SQL statements to create the table and/or populate the table.

-t, –no-create-info.

Don’t write table creation information (the CREATE TABLE statement).

-d, –no-data.

Don’t write any row information for the table. This is very useful if you just want to get a dump of the structure for a table.

PHP / MySQL Tutorial MySQL is currently the most popular open source database server in existence. On top of that, it is very commonly used in conjunction with PHP scripts to create powerful and dynamic server-side applications. 

 MySQL has been criticized in the past for not supporting all the features of other popular and more expensive DataBase Management Systems. However, MySQL continues to improve with each release (currently version 5), and it has become widely popular with individuals and businesses of many different sizes. What is a Database? A database is a structure that comes in two flavors: a flat database and a relational database. A relational database is much more oriented to the human mind and is often preferred over the gabble-de-gook flat database that are just stored on hard drives like a text file. MySQL is a relational database. In a relational structured database there are tables that store data. The columns define which kinds of information will be stored in the table. An individual column must be created for each type of data you wish to store (i.e. Age, Weight, Height). On the other hand, a row contains the actual values for these specified columns. 

Page 23: PHP OOPS Interview Questions

Each row will have 1 value for each and every column. For example a table with columns (Name, Age, Weight-lbs) could have a row with the values (Bob, 65, 165). If all this relational database talk is too confusing, don't despair. We will talk about and show a few examples in the coming lessons.

Why Use a Database? Databases are most useful when it comes to storing information that fits into logical categories. For example, say that you wanted to store information of all the employees in a company. With a database you can group different parts of your business into separate tables to help store your information logically. Example tables might be: Employees, Supervisors, and Customers. Each table would then contain columns specific to these three areas. To help store information related to each employee, the Employees table might have the following columns: Hire, Date, Position, Age, and Salary. Learn MySQL Before you begin this tutorial you should have a basic knowledge of the information covered in our PHP and HTML tutorials. This tutorial focuses heavily on using MySQL in a PHP environment. It is aimed at teaching those who have web hosts with PHP and MySQL already installed. If you are unsure, please contact your web host.

MySQL Admin This lesson covers the different options you have available to you for administering your MySQL service after it is successfully installed. If you already have that base covered feel free to skip on to the next lesson. 

 MySQL Command Line If you are an old-school programmer that has no need for a graphical user interface, then you can simply use any command line interface to execute MySQL queries. Those of you with MySQL installed on your Microsoft Windows operating system can reach the command line by going to the Start Menu and choosing "Run...". Type the keyword "cmd" into the text field and press Enter to launch Window's command line interface.

MySQL GUI With so many free MySQL administration tools available, many developers favor these free Graphical User Interfaces over the command line. The most popular options include: phpMyAdmin - A popular web interface that is included with almost every type of Shared, Virtual or Dedicated hosting solution. MySQL Administrator - A powerful tool developed by the folks at MySQL.com

Navicat - A purchasable MySQL admin tool for Windows, Mac and Linux.

Page 24: PHP OOPS Interview Questions

 MySQL phpMyAdmin As previously mentioned, the very popular phpMyAdmin tool should come with your web hosting plan.

MySQL Syntax The great thing about everything you do in MySQL is that the "code" is very easy for humans to read, as opposed to harder programming languages like C or C++. Very few special characters and symbols are required to create a MySQL query, and most queries consist entirely of English words! 

 Strategies to Learn MySQL The MySQL language is not as complicated as most programming languages, so the best way to learn is with direct examples. Because this tutorial focuses on the combination of MySQL and PHP, most of the examples are ready for you to copy, paste, and run on your web server.

CAPITALIZATION in MySQL Queries There are many keywords in MySQL, and a good programming habit when using ANY of these words is to capitalize them. This helps draw them out from the rest of the code and makes them much easier to read. Below is an example of a MySQL query written in PHP that retrieves all the data from a MySQL table named "example". $result = mysql_query("SELECT * FROM example") That line of code is valid PHP, but it also contains valid MySQL. The text that appears between the quotations "SELECT * FROM example", is the MySQL code. As you probably can tell "SELECT" and "FROM" are the MySQL keywords used in this query. Capitalizing them allows you to tell from a quick glance that this query selects data from a table. You can view a complete list of MySQL keywords at List of Reserved MySQL Words, but don't worry about memorizing them. You could program relentlessly in MySQL for years without ever using all of the MySQL keywords. Learn at Your Own PaceWhen learning MySQL, it is best to take it one lesson at a time and stop when you feel frustrated. Do not worry if it takes you more than a week to finish this tutorial. If you take the time to progress slowly, you will be much more well-informed about the MySQL database system than if you rushed through it in one sitting.

MySQL Database A MySQL database is nothing in itself. Rather a MySQL database is a way of organizing a group of tables. If you were going to create a bunch of different tables that shared a common theme, you would group them into one database to make the management process easier.

Page 25: PHP OOPS Interview Questions

 

 Creating Your First Database Most web hosts do not allow you to create a database directly through a PHP script. Instead they require that you use the PHP/MySQL administration tools on the web host control panel to create these databases. Create a database and assign a new user to this database. For all of our beginning examples we will be using the following information: Server – localhost Database – test Table – example Username – admin Password - 1admin Note: The table may change in the advanced lessons, but everything else will remain the same! The server is the name of the server we want to connect to. Because all of our scripts are going to be placed on the server where MySQL is located the correct address is localhost. If the MySQL server was on a different machine from where the script was running, then you would need to enter the correct url (ask your web host for specifics on this). Your database, table, username, and password do not have to match ours. If you choose a different set of login information, remember to insert your own information when copying the scripts in this tutorial.

Status CheckSo far, you should have created a new database and assigned a user to it. You should not have created a table yet. If you are up-to-date, then continue the tutorial. We will be making our first table in an upcoming lesson.

MySQL Connect Before you can do anything with MySQL in PHP you must first establish a connection to your web host's MySQL database. This is done with the MySQL connect function. 

 MySQL localhost If you've been around the internet a while, you'll know that IP addresses are used as identifiers for computers and web servers. In this example of a connection script, we assume that the MySQL service is running on the same machine as the script. When the PHP script and MySQL are on the same machine, you can use localhost as the address you wish to connect to. localhost is a shortcut to just have the machine connect to itself. If your MySQL service is running at a separate location you will need

Page 26: PHP OOPS Interview Questions

to insert the IP address or URL in place of localhost. Please contact your web host for more details if localhost does not work.

PHP & MySQL Code:<?php

mysql_connect("localhost", "admin", "1admin") or die(mysql_error());

echo "Connected to MySQL<br />";

?> Display: Connected to MySQL If you load the above PHP script to your webserver and everything works properly, then you should see "Connected to MySQL" displayed when you view the .php page. The mysql_connect function takes three arguments. Server, usernam ame, and password. In our example above these arguments were: Server - localhost Username - admin Password - 1admin The "or die(mysql..." code displays an error message in your browser if --you've probably guessed it -- there is an error in processing the connection! Double-check your username, password, or server if you receive this error. Choosing the Working Database After establishing a MySQL connection with the code above, you then need to choose which database you will be using with this connection. This is done with the mysql_select_db function.

PHP & MySQL Code: <?php

mysql_connect("localhost", "admin", "1admin") or die(mysql_error());

echo "Connected to MySQL<br />"; mysql_select_db("test") or die(mysql_error());

echo "Connected to Database";

?> Display:

Page 27: PHP OOPS Interview Questions

 Connected to MySQL Connected to Database 

MySQL Tables A MySQL table is completely different than the normal table that you eat dinner on. In MySQL and other database systems, the goal is to store information in an orderly fashion. The table gets this done by making the table up of columns and rows. 

 The columns specify what the data is going to be, while the rows contain the actual data. Below is how you could imagine a MySQL table. (C = Column, R = Row) 

C1 (Name) C2 (Age) C3 (Weight)

R1 R1 C1 (John) R1 C2 (21) R1 C3 (120)

R2 R2 C1 (Big Sally) R2 C2 (27) R2 C3 (400)

R3 R3 C1 (Tiny Tim) R3 C2 (6) R3 C3 (35)

R4 R4 C1 (Normal Ned) R4 C2 (35) R4 C3 (160)

 We added the row and column number (R# C#) so that you can see that a row is side-to-side, while a column is up-to-down. In a real MySQL table only the value would be stored, not the R# and C#! This table has three categories, or "columns", of data: Name, Age, and Weight. This table has four entries, or in other words, four rows.

Create Table MySQL Before you can enter data (rows) into a table, you must first define what kinds of data will be stored (columns). We are now going to design a MySQL query to summon our table from database land. In future lessons we will be using this table, so be sure to enter this query correctly! PHP & MySQL Code: <?php

// Make a MySQL Connection

mysql_connect("localhost", "admin", "1admin") or die(mysql_error());

mysql_select_db("test") or die(mysql_error());

// Create a MySQL table in the selected database

mysql_query("CREATE TABLE example(

Page 28: PHP OOPS Interview Questions

id INT NOT NULL AUTO_INCREMENT,

PRIMARY KEY(id),

name VARCHAR(30),

age INT)")

or die(mysql_error());

echo "Table Created!";

Display:

Wow! That's a lot of code all at once! Let's get down in the dirt and figure this stuff out. We will be going through the code line by line. 'mysql_query ("CREATE TABLE example' The first part of the mysql_query told MySQL that we wanted to create a new table. The two capitalized words are reserved MySQL keywords. The word "example" is the name of our table, as it came directly after "CREATE TABLE". It is a good idea to use descriptive names when creating a table, such as: employee_information, contacts, or customer_orders. Clear names will ensure that you will know what the table is about when revisiting it a year after you make it. 'id INT NOT NULL AUTO_INCREMENT' Here we create a column "id" that will automatically increment each time a new entry is added to the table. This will result in the first row in the table having an id = 1, the second row id = 2, the third row id = 3, and so on. The column "id" is not something that we need to worry about after we create this table, as it is all automatically calculated within MySQL.

Reserved MySQL Keywords:

Here are a few quick definitions of the reserved words used in this line of code: INT - This stands for integer or whole number. 'id' has been defined to be an integer. NOT NULL - These are actually two keywords, but they combine together to say that this column cannot be null. An entry is NOT NULL only if it has some value, while something with no value is NULL. AUTO_INCREMENT - Each time a new entry is added the value will be incremented by 1. 'PRIMARY KEY (id)' 

Page 29: PHP OOPS Interview Questions

PRIMARY KEY is used as a unique identifier for the rows. Here we have made "id" the PRIMARY KEY for this table. This means that no two ids can be the same, or else we will run into trouble. This is why we made "id" an auto-incrementing counter in the previous line of code. 'name VARCHAR(30),' Here we make a new column with the name "name"! VARCHAR stands for "variable character". "Character" means that you can put in any kind of typed information in this column (letters, numbers, symbols, etc). It's "variable" because it can adjust its size to store as little as 0 characters and up to a specified maximum number of characters. We will most likely only be using this name column to store characters (A-Z, a-z). The number inside the parentheses sets the maximum number of characters. In this case, the max is 30. 'age INT,' Our third and final column is age, which stores an integer. Notice that there are no parentheses following "INT". MySQL already knows what to do with an integer. The possible integer values that can be stored in an "INT" are -2,147,483,648 to 2,147,483,647, which is more than enough to store someone's age! 'or die(mysql_error());' This will print out an error if there is a problem in the table creation process.

MySQL Insert When data is put into a MySQL table it is referred to as inserting data. When inserting data it is important to remember the exact names and types of the table's columns. If you try to place a 500 word essay into a column that only accepts integers of size three, you will end up with a nasty error! 

 Inserting Data Into Your Table Now that you have created your table, let's put some data into that puppy! Here is the PHP/MySQL code for inserting data into the "example" table we created in the previous lesson. PHP & MySQL Code: <?php

// Make a MySQL Connection

mysql_connect("localhost", "admin", "1admin") or die(mysql_error());

mysql_select_db("test") or die(mysql_error());

// Insert a row of information into the table "example"

Page 30: PHP OOPS Interview Questions

mysql_query("INSERT INTO example

(name, age) VALUES('Timmy Mellow man', '23' ) ")

or die(mysql_error());

mysql_query("INSERT INTO example

(name, age) VALUES('Sandy Smith', '21' ) ")

or die(mysql_error()); mysql_query("INSERT INTO example

(name, age) VALUES('Bobby Wallace', '15' ) ")

or die(mysql_error());

echo "Data Inserted!";

?> Display:

 This code is much simpler to understand than the create table code, as will be most of the MySQL queries you will learn in the rest of this tutorial. Once again, we will cover the code line by line. 'mysql_query("INSERT INTO example' Again we are using the mysql_query function. "INSERT INTO" means that data is going to be put into a table. The name of the table we specified to insert data into was "example". '(name, age) VALUES('Timmy Mellow man', '23' ) ")' "(name, age)" are the two columns we want to add data into. "VALUES" means that what follows is the data to be put into the columns that we just specified. Here we enter the name Timmy Mellow man for "name", and 23 for "age". Be sure to note the location and number of apostrophes and parentheses in the PHP code, as this is where a lot of beginner PHP/MySQL programmers run into problems.

MySQL Query So far we have seen a couple different uses of PHP's mysql_query function and we'll be seeing more of it as nearly all MySQL in PHP is done through the MySQL Query

Page 31: PHP OOPS Interview Questions

function. We have already created a new table and inserted data into that table. In this lesson we will cover the most common MySQL Query that is used to retrieve information from a database. 

 Retrieving Data With PHP & MySQL Usually most of the work done with MySQL involves pulling down data from a MySQL database. In MySQL, data is retrieved with the "SELECT" keyword. Think of SELECT as working the same way as it does on your computer. If you wanted to copy some information in a document, you would first select the desired information, then copy and paste. Using MySQL SELECT & FROM Before attempting this lesson, be sure that you have created a table that contains some data, preferably the same data that we had in the MySQL Insert lesson. In this example, we will output the first entry of our MySQL "examples" table to the web browser.

PHP & MySQL Code:<?php

// Make a MySQL Connection

mysql_connect("localhost", "admin", "1admin") or die(mysql_error());

mysql_select_db("test") or die(mysql_error());

// Retrieve all the data from the "example" table

$result = mysql_query("SELECT * FROM example")

or die(mysql_error()); 

// store the record of the "example" table into $row $row = mysql_fetch_array( $result );

// Print out the contents of the entry

echo "Name: ".$row['name'];

echo " Age: ".$row['age'];

?> Display: Name: Tim Mellowman Age: 23 

Page 32: PHP OOPS Interview Questions

This is an example of how to use MySQL's SELECT statement in PHP. Although the MySQL code is simple, printing out the information with PHP is somewhat more involved. Below is a step-by-step walkthrough of the code. '$result = mysql_query("SELECT * FROM example")' When you perform a SELECT query on the database it will return a MySQL Resource that holds everything from your MySQL table, "example". We want to use this Resource in our PHP code, so we need to store it in a variable, $result. 'SELECT * FROM example' Yes, this is a partial repeat of the same line of code, but we wanted to explain this MySQL statement in greater detail again! In English, this line of code reads "Select every entry from the table example". The asterisk is the wild card in MySQL which just tells MySQL to include every single column for that table. '$row = mysql_fetch_array( $result );' $result is now a MySQL Resource containing data from your MySQL table, "example". Data is being stored in $result, but it is not yet visible to visitors of your website. When we pass $result into the mysql_fetch_array function -- mysql_fetch_array($result) -- an associative array (name, age) is returned. In our MySQL table "example," there are only two fields that we care about: name and age. These names are the keys to extracting the data from our associative array. To get the name we use $row['name'] and to get the age we use $row['age']. PHP is case sensitive when you reference MySQL column names, so be sure to use capitalization in your PHP code that matches the MySQL column names!

MySQL Fetch Array MySQL doesn't have a Fetch Array function. mysql_fetch_array is actually a PHP function that allows you to access data stored in the result returned from a successful mysql_query. If you have been jumping around our MySQL Tutorial then you would have already seen this function popping up all over the place. 

 This lesson will teach you how and why to use mysql_fetch_array in your PHP Scripts. mysql_fetch_array: Why Use It? Do you know what is returned when you used the mysql_query function to query a MySQL database? It isn't something you can directly manipulate, that is for sure. Here is a sample SELECT query of a table we created in the MySQL Create Table lesson. PHP and MySQL Code: 

Page 33: PHP OOPS Interview Questions

<?php

$result = mysql_query("SELECT * FROM example");

?> The value that mysql_query returns and stores into $result is a special type of data, it is a MySQL Resource. Additional PHP functions are required to extract the data from this Resource. A Row of Data The mysql_fetch_array function takes a MySQL query resource as an argument ($result) and returns the first row of data returned by the mysql_query. Our table example basically looks like the table below. example MySQL Table: name age

Timmy Mellowman 23

Sandy Smith 21

Bobby Wallace 15

 The first row of data in this table is "Timmy Mellowman" and "23". When we fetch an array from our MySQL Resource $result it should have Timmy's name and age in it. Getting a Row of Data using mysql_fetch_array mysql_fetch_array returns the first row in a MySQL Resource in the form of an associative array. The columns of the MySQL Result can be accessed by using the column names of the table. In our table example these are: name and age. Here is the code to print out the first MySQL Result row.

PHP and MySQL Code:<?php

// Make a MySQL Connection

$query = "SELECT * FROM example";

$result = mysql_query($query) or die(mysql_error());

$row = mysql_fetch_array($result) or die(mysql_error());

echo $row['name']. " - ". $row['age'];

?>

Display: 

Page 34: PHP OOPS Interview Questions

Timmy Mellowman - 23This is just what we expected would happen! Now, the cool thing about mysql_fetch_array is that you can use it again on the same MySQL Resource to return the second, third, fourth and so on rows. You can keep doing this until the MySQL Resource has reached the end (which would be three times in our example). Sounds like an awfully repetitive task. It would be nice if we could get all our results from a MySQL Resource in an easy to do script. Fetch Array While Loop As we have said, the mysql_fetch_array function returns an associative array, but it also returns FALSE if there are no more rows to return! Using a PHP While Loop we can use this information to our advantage. If we place the statement "$row = mysql_fetch_array()" as our while loop's conditional statement we will accomplish two things: We will get a new row of MySQL information that we can print out each time the while loop checks its conditional statement. When there are no more rows the function will return FALSE causing the while loop to stop! Now that we know what we need to do and how to go about doing it, the code pretty much writes itself, so let's move on to the next lesson. Just kidding! Here is the code that will print out all the rows of our MySQL Resource.

PHP and MySQL Code:<?php

// Make a MySQL Connection

$query = "SELECT * FROM example";

$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_array($result)){

echo $row['name']. " - ". $row['age'];

echo "<br />";

}

?> Display: Timmy Mellowman - 23

Sandy Smith - 21

Page 35: PHP OOPS Interview Questions

Bobby Wallace - 15 And there we have all the rows from our example table! You could apply this script to any MySQL table as long as you change both the table name in the query and the column names that we have in the associative array.

MySQL Select You have seen two types of MySQL queries thus far: the query which we used to create a table and the query we used to insert data into our newly created table. The query in this lesson is SELECT, which is used to get information from the database, so that its data can be used in our PHP script. 

 Retrieving Information from MySQL Finally, we get to use the data in our MySQL database to create a dynamic PHP page. In this example we will select everything in our table "example" and put it into a nicely formatted HTML table. Remember, if you don't understand the HTML or PHP code, be sure to check out the HTML and/or PHP Tutorial(s). PHP & MySQL Code: <?php

// Make a MySQL Connection

mysql_connect("localhost", "admin", "1admin") or die(mysql_error());

mysql_select_db("test") or die(mysql_error());

// Get all the data from the "example" table

$result = mysql_query("SELECT * FROM example")

or die(mysql_error());

echo "<table border='1'>";

echo "<tr> <th>Name</th> <th>Age</th> </tr>";

// keeps getting the next row until there are no more to get

while($row = mysql_fetch_array( $result )) { // Print out the contents of each row into a table

echo "<tr><td>";

echo $row['name'];

Page 36: PHP OOPS Interview Questions

echo "</td><td>";

echo $row['age'];

echo "</td></tr>";

}

echo "</table>";

?> Display: Name Age

Timmy Mellowman 23

Sandy Smith 21

Bobby Wallace 15

 Because we only had three entries in our table, three rows appeared above. If you added more entries to your database's table, then you would see each additional row appear in the above table. If you do not understand the above PHP, you can view our PHP Array Tutorial & PHP Loop Tutorial. '$result = mysql_query...' When you select items from a database using mysql_query, the data is returned as a MySQL result. Since we want to use this data in our table we need to store it in a variable. $result now holds the result from our mysql_query. 'SELECT * FROM example' In English, this line of code reads "Select everything from the table example". The asterisk is the wild card in MySQL which just tells MySQL to retrieve every single field from the table. 'while($row = mysql_fetch_array( $result )' The mysql_fetch_array function gets the next-in-line associative array from a MySQL result. By putting it in a while loop it will continue to fetch the next array until there is no next array to fetch. This function can be called as many times as you want, but it will return FALSE when the last associative array has already been returned. By placing this function within the conditional statement of the while loop, we can kill two birds with one stones. We can retrieve the next associative array from our MySQL Resource, $result, so that we can print out the name and age of that person. 

Page 37: PHP OOPS Interview Questions

We can tell the while loop to stop printingn out information when the MySQL Resource has returned the last array, as False is returned when it reaches the end and this will cause the while loop to halt. In our MySQL table "example" there are only two fields that we care about: name and age. These fields are the keys to extracting the data from our associative array. To get the name we use $row['name'] and to get the age we use $row['age'].

Practice What You Have Learned Use the query that we have provided or make a new one and try putting it into a formatted HTML table. It might be useful to try out other methods of HTML formatting as well. See which one you like best! 

 By now you should be starting to understand how powerful PHP and MySQL are when used together. The tasks that you can complete with MySQL and PHP would be nearly impossible to do by hand in HTML. Imagine trying to create an HTML table of 6000 entries without using a MySQL database and a PHP while loop!

MySQL Where In a previous lesson we did a SELECT query to get all the data from our "example" table. If we wanted to select only certain entries of our table, then we would use the keyword WHERE. 

 WHERE lets you specify requirements that entries must meet in order to be returned in the MySQL result. Those entries that do not pass the test will be left out. We will be assuming the data from a previous lesson for the following examples. Being Selective With Your MySQL Selection There are three entries in our "example" table: Tim, Sandy, and Bobby. To select Sandy only we could either specify Sandy's age (21) or we could use her name (Sandy Smith). In the future there may be other people who are 21, so we will use her name as our requirement. WHERE is used in conjuction with a mathematical statement. In our example we will want to select all rows that have the string "Sandy Smith" in the "names" column (mathematically: {name column} = "Sandy Smith"). Here's how to do it.

PHP & MySQL Code:<?php

// Make a MySQL Connection

mysql_connect("localhost", "admin", "1admin") or die(mysql_error());

mysql_select_db("test") or die(mysql_error());

// Get a specific result from the "example" table

Page 38: PHP OOPS Interview Questions

$result = mysql_query("SELECT * FROM example

WHERE name='Sandy Smith'") or die(mysql_error());

// get the first (and hopefully only) entry from the result

$row = mysql_fetch_array( $result );

// Print out the contents of each row into a table

echo $row['name']." - ".$row['age'];

?> Display: Sandy Smith – 21 MySQL Wildcard Usage '%' If you wanted to select every person in the table who was in the ir 20's, how could you go about doing it? With the tools you have now, you could make 10 different queries, one for each age 20, 21, 22...but that seems like more work than we need to do. In MySQL there is a "wildcard" character '%' that can be used to search for partial matches in your database. The '%' tells MySQL to ignore the text that would normally appear in place of the wildcard. For example '2%' would match the following: 20, 25, 2000000, 2avkldj3jklsaf, and 2! On the other hand, '2%' would not match the following: 122, a20, and 32. MySQL Query WHERE With Wildcard To solve our problem from before, selecting everyone who is their 20's from or MySQL table, we can utilize wildcards to pick out all strings starting with a 2.

PHP & MySQL Code:<?php

// Connect to MySQL

// Insert a row of information into the table "example"

$result = mysql_query("SELECT * FROM example WHERE age LIKE '2%' ")

or die(mysql_error());

// keeps getting the next row until there are no more to get

Page 39: PHP OOPS Interview Questions

while($row = mysql_fetch_array( $result )) {

// Print out the contents of each rowecho $row['name']." - ".$row['age']. "<br />";

}

?>

Display: Timmy Mellowman – 23

Sandy Smith - 21 You can use this wildcard at the beginning, middle, and end of the string. Experiment with it so you can see for yourself how powerful this little trick can be. Note: The wildcard was used for example purposes only. If you really wanted to explicilty select people who are in their 20's you would use greater than 19 and less than 30 to define the 20's range. Using a wildcard in this example would select unwanted cases, like a 2 year old and your 200 year old great-great-great-grandparents.

MySQL Order By It would be nice to be able to make MySQL results easier to read and understand. A common way to do this in the real world is to order a big list of items by name or amount. The way to order your result in MySQL is to use the ORDER BY statement. 

 What ORDER BY does is take the a column name that you specify and sort it in alphabetical order (or numeric order if you are using numbers). Then when you use mysql_fetch_array to print out the result, the values are already sorted and easy to read. Ordering is also used quite frequently to add additional functionality to webpages that use any type of column layout. For example, some forums let you sort by date, thread title, post count, view count, and more.

Sorting a MySQL Query - ORDER BY Let's use the same query we had in MySQL Select and modify it to ORDER BY the person's age. The code from MySQL Select looked like... PHP & MySQL Code: <?php

// Make a MySQL Connection

mysql_connect("localhost", "admin", "1admin") or die(mysql_error());

Page 40: PHP OOPS Interview Questions

mysql_select_db("test") or die(mysql_error());

// Get all the data from the "example" table

$result = mysql_query("SELECT * FROM example")

or die(mysql_error());

echo "<table border='1'>"; echo "<tr> <th>Name</th> <th>Age</th> </tr>";

// keeps getting the next row until there are no more to get

while($row = mysql_fetch_array( $result )) {

// Print out the contents of each row into a table

echo "<tr><td>";

echo $row['name'];

echo "</td><td>";

echo $row['age'];

echo "</td></tr>";

}

echo "</table>";

?>

Display:

Name Age

Timmy Mellowman 23

Sandy Smith 21

Bobby Wallace 15

 What we need to do is add on to the existing MySQL statement "SELECT * FROM example" to include our new ordering requirement. When you choose to order a column, be sure that your ORDER BY appears after the SELECT ... FROM part of the MySQL statement. PHP & MySQL Code:<?php

Page 41: PHP OOPS Interview Questions

// Make a MySQL Connection

mysql_connect("localhost", "admin", "1admin") or die(mysql_error());

mysql_select_db("test") or die(mysql_error());// Get all the data from the "example" table

$result = mysql_query("SELECT * FROM example ORDER BY age")

or die(mysql_error());

echo "<table border='1'>";

echo "<tr> <th>Name</th> <th>Age</th> </tr>";

// keeps getting the next row until there are no more to get

while($row = mysql_fetch_array( $result )) {

// Print out the contents of each row into a table

echo "<tr><td>";

echo $row['name'];

echo "</td><td>";

echo $row['age'];

echo "</td></tr>";

echo "</table>";

?>

Display: Name Age

Bobby Wallace 15

Sandy Smith 21

Timmy Mellowman 23

 Presto! We have an ordered MySQL result! Notice that we didn't have to change any of our PHP code. Remember this whenever you're editing a PHP script that uses MySQL. Sometimes it may be easier to just tweak your MySQL query instead of trying to mess around in PHP.

Page 42: PHP OOPS Interview Questions

MySQL Joins Thus far we have only been getting data from one table at a time. This is fine for simple tasks, but in most real world MySQL usage you will often need to get data from multiple tables in a single query. The act of joining in MySQL refers to smashing two or more tables into a single table. This means everything you have learned so far can be applied after you've created this new, joined table. MySQL Join Table Setup We like to show examples and code before we explain anything in detail, so here is how you would combine two tables into one using MySQL. The two tables we will be using relate to a families eating habits.  family Table: Position Age

Dad 41

Mom 45

Daughter 17

Dog

 food Table: Meal Position

Steak Dad

Salad Mom

Spinach Soup

Tacos Dad

 The important thing to note here is that the column Position contains information that can tie these two tables together. In th e "family" table, the Position column contains all the members of the family and their respective ages. In the "food" table the Position column contains the family member who enjoys that dish. It's only through a shared column relationship such as this that tables can be joined together, so remember this when creating tables you wish to have interact with each other. MySQL Join Simple Example Let's imagine that we wanted to SELECT all the dishes that were liked by a family member. If you remember from the previous lesson, this is a situation when we need to use the WHERE clause. We want to SELECT all the dishes WHERE a family member likes it. 

Page 43: PHP OOPS Interview Questions

We will be performing a generic join of these two tables using the Position column from each table as the connector. Note: This example assumes you have created the MySQL tables "food" and "family". If you do not have either of them created, you can either create them using our MySQL Create Table lesson or do it manually yourself. PHP and MySQL Code:<?php

// Make a MySQL Connection

// Construct our join query

$query = "SELECT family.Position, food.Meal ".

"FROM family, food ".

"WHERE family.Position = food.Position";

$result = mysql_query($query) or die(mysql_error());

// Print out the contents of each row into a table

while($row = mysql_fetch_array($result)){

echo $row['Position']. " - ". $row['Meal'];

echo "<br />";

}?>The statement "WHERE family.Position = food.Position" will restrict the results to the rows where the Position exists in both the "family" and "food" tables.

Display: Dad – Steak

Mom – Salad

Dad – TacosThose are the results of our PHP script. Let's analyze the tables to make sure we agree with these results. Compare the Tables: Position Age

Dad 41

Mom 45

Page 44: PHP OOPS Interview Questions

Daughter 17

Dog

Meal Position

Steak Dad

Salad Mom

Spinach Soup

Tacos Dad

 Our results show that there were three meals that were liked by family members. And by manually perusing the tables it looks like there were indeed three meals liked by family members. Note: This is a very simple example of a join. If you do not understand it yet do not despair. Joins are a very hard concept to grasp for beginning MySQL developers.

MySQL LEFT JOIN In the previous lesson, Mysql Joins we learned how to do a basic join of two tables. This lesson will teach you how to do a specialized join: left join. 

 MySQL LEFT JOIN Explanation How is a LEFT JOIN different from a normal join? First of all, the syntax is quite different and somewhat more complex. Besides looking different, the LEFT JOIN gives extra consideration to the table that is on the left. Being "on the left" simply refers to the table that appears before the LEFT JOIN in our SQL statement. Nothing tricky about that. This extra consideration to the left table can be thought of as special kind of preservation. Each item in the left table will show up in a MySQL result, even if there isn't a match with the other table that it is being joined to.

MySQL Join and LEFT JOIN Differences Here are the tables we used in the previous Mysql Joins lesson. MySQL family and food Tables: Position Age

Dad 41

Mom 45

Daughter 17

Dog

Page 45: PHP OOPS Interview Questions

Meal Position

Steak Dad

Salad Mom

Spinach Soup

Tacos Dad

 We executed a simple query that selected all meals that were liked by a family member with this simple join query:

Simplified MySQL Query: SELECT food.Meal, family.Position

FROM family, food

WHERE food.Position = family.Position Result: Dad – Steak

Mom – Salad

Dad - Tacos When we decide to use a LEFT JOIN in the query instead, all the family members be listed, even if they do not have a favorite dish in our food table. This is because a left join will preserve the records of the "left" table. MySQL LEFT JOIN Example The code below is the exact same as the code in the previous lesson, except the LEFT JOIN has now been added to the query. Let's see if the results are what we expected. 

PHP and MySQL Code:<?php

// Make a MySQL Connection

// Construct our join query

$query = "SELECT family.Position, food.Meal ".

"FROM family LEFT JOIN food ".

"ON family.Position = food.Position"; 

$result = mysql_query($query) or die(mysql_error());

Page 46: PHP OOPS Interview Questions

// Print out the contents of each row into a table

while($row = mysql_fetch_array($result)){

echo $row['Position']. " - ". $row['Meal'];

echo "<br />";}

?>

Display: Dad – Steak

Dad – Tacos

Mom – Salad

Daughter –

Dog – Success! The LEFT JOIN preserved every family member, including those who don't yet have a favorite meal in the food table! Please feel free to play around with LEFT JOIN until you feel like you have a solid grasp of it. This stuff isn't easy!

MySQL Update Imagine that you have a MySQL table that holds the information of all the employees in your company. One of the columns in this table is called "Seniority" and it holds an integer value of how many months an employee has worked at your company. Unfortunately for you, your job is to update these numbers every month. 

 You may be thinking that you'll have to open up your MySQL administration tool and edit each entry by hand. That would take hours. On the other hand, you could master MySQL and have an automated script that you run each month to get the job done for you. In this lesson you will learn how to replace the existing data of a MySQL table with freshly supplied up-to-date data using the UPDATE MySQL query. MySQL Update Example Once again we will be working with the data from a previous example. Sandy has just had a birthday and she now 22 years old. Our job now is to update her age using MySQL commands like UPDATE, SET, and WHERE. UPDATE - Performs an update MySQL query SET - The new values to be placed into the table follow SET 

Page 47: PHP OOPS Interview Questions

WHERE - Limits which rows are affected

PHP & MySQL Code: <?php

// Connect to MySQL // Get Sandy's record from the "example" table

$result = mysql_query("UPDATE example SET age='22' WHERE age='21'")

or die(mysql_error()); 

$result = mysql_query("SELECT * FROM example WHERE age='22'")

or die(mysql_error()); 

// get the first (and hopefully only) entry from the result

$row = mysql_fetch_array( $result );

echo $row['name']." - ".$row['age']. "<br />";

?> Display: Sandy Smith - 22 Now it is important to note that this query would have updated ALL records that had an age of 21 to the new age of 22. In a table where Sandy is not the only entry, this may become a problem, and a more sophisticated solution would be necessary.

MySQL Delete Maintenance is a very common task that is necessary for keeping MySQL tables current. From time to time, you may even need to delete items from your database. Some potential reasons for deleting a record from MySQL include when: someone deletes a post from a forum, an employee leaves a company, or you're trying to destroy your records before the federalies come! MySQL DELETE Example The DELETE query is very similar to the UPDATE Query in the previous lesson. We need to choose a table, tell MySQL to perform the deletion, and provide the requirements that a record must have for it to be deleted. Say we want to delete the youngest employee from our previously created table because he has to go back to school. This is how we do it.

PHP & MySQL Code:

Page 48: PHP OOPS Interview Questions

 <?php

// Connect to MySQL

// Delete Bobby from the "example" MySQL table

mysql_query("DELETE FROM example WHERE age='15'")

or die(mysql_error());

?> It is important to note that this query would have deleted ALL records that had an age of 15. Since Bobby was the only 15 year old this was not a problem. MySQL DELETE Tips Before performing a large delete on a database, be sure to back up the table/database in case your script takes off a little more than desired. Test your delete queries before even thinking about using them on your table. As long as you take caution when using this powerful query you should not run into any problems.

MySQL Database Backups If you're storing anything in MySQL databases that you do not want to lose, chances are you should be doing weekly or even daily backups. Depending on what you're using your databases for -- be it to store forum messages, employee information, or your spending information -- you are going to need to choose a backup schedule that meets your needs. 

 You may or may not know that MySQL databases are just files that are stored on your web server. This fact makes the whole backup and restore process extremely simple and painless once you have figured out how to do it. Different Ways to Get That Backup Done There are many paths you can take to create a MySQL backup. However, no matter which application, control panel tool, or SSH script you use, all of the backups will fit into two types of backups: a dump or raw backup.

MySQL Dump A MySQL dump is a bit slower than a raw backup because it creates all the SQL queries required to create the tables of that database, as well as all the insert queries required to place the information back into the database's tables. If you want to perform the mysql dump manually, without the assistance of your hosts control panel, then run SSH to your web server and do the following (taken from MySql.com): mysqldump --tab=/path/to/some/dir --opt db_name

Page 49: PHP OOPS Interview Questions

 If you were to open up a MySQL dump file you would see a slew of SQL queries that you would probably be able to understand (if you've already read through this whole tutorial!). MySQL Raw Backup A MySQL Raw Backup is quicker because it does not translate the contents of the database into human readable SQL queries. However, not many control panels support this type of backup, so do not worry if your hosting provider doesn't have this option set up for you.

MySQL Backup in Control Panel cPanel cPanel is the most widely used web host control panel at this time, so we thought it would make sense to provide a walkthrough specifically for cPanel. From the application selection screen click "Backup". This will bring you to the backup application that allows you to generate and download complete backups for your site. To back up a database individually, look for the title "Download a SQL Database Backup" or something similar. Below that title should be a listing of every database that you have created. Simply click on the name of the database you want to backup and save it to your computer. That's it! Now just be sure that you have a regular backup schedule, just in case the unthinkable happens and your web host loses all your database information!

MySQL GROUP BY - Aggregate Functions After you have mastered the basics of MySQL, it's time to take the next step and take on Aggregate Functions. Before we talk about what they are, let's review the definition of aggregate, as it relates to MySQL: 

 Aggregate - Constituting or amounting to a whole; total. ~American Heritage Dictionary With this type of wording, we can assume that MySQL's aggregate functions are something that will be very top-level, or in other words, the opposite of detailed. The most common types of aggregate functions let you find out things like the minimum, maximum and even the average of a "grouped" set of data. The trick to understanding aggregate functions is often understanding what kind of data is being grouped and analyzed.

MySQL GROUP BY - The Data Before we can start throwing around these fancy functions, let's build an appropriate table that has enough data in it to be meaningful to us. Below is the SQL for our "products" table. You can either run this SQL statement in your MySQL administrator

Page 50: PHP OOPS Interview Questions

software or use MySQL to execute the queries (i.e. create table, then each of the records). You can download the products.sql file from our website. If you are new to MySQL you will need to know how to Create a MySQL Table and Insert a MySQL Row. Below is the MySQL table products. 

Products Table:

id name type price

123451 Park's Great Hits Music 19.99

123452 Silly Puddy Toy 3.99

123453 Playstation Toy 89.95

123454 Men's T-Shirt Clothing 32.50

123455 Blouse Clothing 34.97

123456 Electronica 2002 Music 3.99

123457 Country Tunes Music 21.55

123458 Watermelon Food 8.73

 GROUP BY - Creating Your First "Group"Imagine that our store was running an advertisement in the newspaper and we wanted to have a "bargain basement" section that listed the lowest price of each product type. In this case we would be "grouping" by the product type and finding the minimum price of each group. Our query needs to return two columns: product type and minimum price. Additionally, we want to use the type column as our group. The SELECT statement we are about to use will look different because it includes an aggregate function, MIN, and the GROUP BY PHP and MySQL Code: <?php

// Make a MySQL Connection

$query = "SELECT type, MIN(price) FROM products GROUP BY type";

$result = mysql_query($query) or die(mysql_error());

// Print out result

while($row = mysql_fetch_array($result)){

echo $row['type']. " - $". $row['MIN(price)'];

echo "<br />";

}

Page 51: PHP OOPS Interview Questions

?> Our "products" table has four types of products: Music, Toy, Clothing and Food. When we GROUP BY type then we get one result for each of these types. statement, but otherwise it isn't any different than a normal SELECT statement.Display: Clothing - $32.50

Food - $8.73

Music - $3.99

Toy - $3.99 MySQL GROUP BY – Review Group BY is good for retrieving information about a group of data. If you only had one product of each type, then GROUP BY would not be all that useful. GROUP BY only shines when you have many similar things. For example, if you have a number of products of the same type, and you want to find out some statistical information like the minimum, maximum, or other top-level info, you would use GROUP BY. Some technical rules of GROUP BY: The column that you GROUP BY must also be in your SELECT statement. Remember to group by the column you want information about and not the one you are applying the aggregate function on. In our above example we wanted information on the type column and the aggregate function was applied to the price column. The next few lessons will provide a walkthrou gh for using other popular MySQL aggregate functions in conjunction with the GROUP BY statement.

MySQL Aggregate Functions - COUNT() This lesson will teach you how to use the aggregate function COUNT(). If you missed the Aggregate Introduction Lesson, please check it out now, as it explains many concepts used in this lesson! 

 We will be using the "products" table that we constructed to display the use of MySQL's COUNT function. You can download the products.sql file from our website. If you are new to MySQL you will need to know how to Create a MySQL Table and Insert a MySQL Row first. Below is the MySQL table "products". 

Products Table:

Page 52: PHP OOPS Interview Questions

id name type price

123451 Park's Great Hits Music 19.99

123452 Silly Puddy Toy 3.99

123453 Playstation Toy 89.95

123454 Men's T-Shirt Clothing 32.50

123455 Blouse Clothing 34.97

123456 Electronica 2002 Music 3.99

123457 Country Tunes Music 21.55

123458 Watermelon Food 8.73

 

MySQL COUNT - Counting Records The COUNT function is an aggregate function that simply counts all the items that are in a group. The "products" table that is displayed above has several products of various types. One use of COUNT might be to find out how many items of each type there are in the table. Just as we did in the aggregate introduction lesson, we are going to GROUP BY type to create four groups: Music, Toy, Clothing and Food. For a slight change of pace, let's count the name column to find how many products there are per type. PHP and MySQL Code: <?php

// Make a MySQL Connection

$query = "SELECT type, COUNT(name) FROM products GROUP BY type"; 

$result = mysql_query($query) or die(mysql_error());

// Print out result

while($row = mysql_fetch_array($result)){

echo "There are ". $row['COUNT(name)'] ." ". $row['type'] ." items.";

echo "<br />";

}

?> Display: There are 2 Clothing items.

There are 1 Food items.

Page 53: PHP OOPS Interview Questions

There are 3 Music items.

There are 2 Toy items.

MySQL Aggregate Functions - SUM() This lesson will teach you how to use the aggregate function SUM(). If you haven't already read through Tizag's Aggregate Introduction Lesson, please check it out now. It explains concepts used in this lesson. 

 We will be using the "products" table again -- this time to display the use of MySQL's SUM function. You can download the products.sql file from our website. If you are new to MySQL you will need to know how to Create a MySQL Table and Insert a MySQL Row. Here's a visual of the "products" table. 

Products Table:

id name type price

123451 Park's Great Hits Music 19.99

123452 Silly Puddy Toy 3.99

123453 Playstation Toy 89.95

123454 Men's T-Shirt Clothing 32.50

123455 Blouse Clothing 34.97

123456 Electronica 2002 Music 3.99

123457 Country Tunes Music 21.55

123458 Watermelon Food 8.73

 

 MySQL SUM - Totaling Groups SUM is an aggregate function that totals a specific column for a group. The "products" table that is displayed above has several products of various types. One use of SUM might be to find the total of all the items' price for each product type. Just as we did in the aggregate introduction lesson, we are going to apply the aggregate function to price and GROUP BY type to create four groups: Music, Toy, Clothing and Food. PHP and MySQL Code:<?php

// Make a MySQL Connection

$query = "SELECT type, SUM(price) FROM products GROUP BY type";

Page 54: PHP OOPS Interview Questions

$result = mysql_query($query) or die(mysql_error());

// Print out result

while($row = mysql_fetch_array($result)){

echo "Total ". $row['type']. " = $". $row['SUM(price)'];

echo "<br />";

}

?>Display: Total Clothing = $67.47

Total Food = $8.73

Total Music = $45.53

Total Toy = $93.94

MySQL Aggregate Functions - AVG() This lesson will teach you how to use the aggregate function AVG(). If you missed the Aggregate Introduction Lesson, please check it out now. It explains the meaning of aggregates and describes the GROUP BY statement. 

 The table we will be using is "products" and you can download the products.sql file so you can follow along. The table can be entered through you MySQL interface or through PHP. If you are new to MySQL/PHP programming you will need to know how to Create a MySQL Table and Insert a MySQL Row. Products Table: id name type price

123451 Park's Great Hits Music 19.99

123452 Silly Puddy Toy 3.99

123453 Playstation Toy 89.95

123454 Men's T-Shirt Clothing 32.50

123455 Blouse Clothing 34.97

123456 Electronica 2002 Music 3.99

123457 Country Tunes Music 21.55

Page 55: PHP OOPS Interview Questions

123458 Watermelon Food 8.73

 

MySQL Average - Finding a Middle Ground The AVG function returns the average value for the specified column of a group. Our imaginary customers have been complaining recently that our prices are too high, so we would like to find out the average price of each product type to see if this is in fact the truth. To find out this metric we are going to apply the aggregate function to the price and GROUP BY type to create four price groups: Music, Toy, Clothing and Food. PHP and MySQL Code: <?php 

// Make a MySQL Connection

$query = "SELECT type, AVG(price) FROM products GROUP BY type";

$result = mysql_query($query) or die(mysql_error());

// Print out result

while($row = mysql_fetch_array($result)){ 

echo "The average price of ". $row['type']. " is $".$row['AVG(price)'];

echo "<br />";

}

?>

Display: The average price of Clothing is $33.735000

The average price of Food is $8.730000

The average price of Music is $15.176667

The average price of Toy is $46.970000 Those prices seem very reasonable, in my opinion. I think our imaginary customers should change their view and keep buying products from us.

Page 56: PHP OOPS Interview Questions

MySQL Aggregate Functions - MIN() This lesson will teach you how to use the aggregate function MIN(). If you missed the Aggregate Introduction Lesson, you might want to check it out to learn about the GROUP BY statement and its use with MySQL aggregate functions. You can download the table used in this example, products.sql, from our website. A SQL file can be run through your MySQL administrator interface to create the table. However, if you would like to create the table with PHP/MySQL, check out our Create a MySQL Table and Insert a MySQL Row lessons. 

Products Table:

id name type price

123451 Park's Great Hits Music 19.99

123452 Silly Puddy Toy 3.99

123453 Playstation Toy 89.95

123454 Men's T-Shirt Clothing 32.50

123455 Blouse Clothing 34.97

123456 Electronica 2002 Music 3.99

123457 Country Tunes Music 21.55

123458 Watermelon Food 8.73

 MySQL MIN The MIN function is an aggregate function that finds the smallest value in a group. The products table that is displayed above has several products of various types. One use of MIN might be to find out the cheapest item in each group. Just as we did in the Aggregate Introduction Lesson, we are going to GROUP BY type to create four groups: Music, Toy, Clothing and Food. The column that will have the MIN function applied to it is, of course, price. PHP and MySQL Code: <?php

// Make a MySQL Connection

$query = "SELECT type, MIN(price) FROM products GROUP BY type";

$result = mysql_query($query) or die(mysql_error());

// Print out result Cho "The cheapest ". $row['type']. " is $" .$row['MIN(price)'];

Page 57: PHP OOPS Interview Questions

echo "<br />";

}

?>Display: The cheapest Clothing is $32.50

The cheapest Food is $8.73

The cheapest Music is $3.99

The cheapest Toy is $3.99

MySQL Aggregate Functions - MAX() This lesson will teach you how to use the MAX() aggregate function . If you missed the Aggregate Introduction Lesson, please check it out now, as it explains many concepts used in this lesson! 

 You can download the example the products.sql file from our website, which contains the SQL for the table below. If you would like to use PHP/MySQL to create the table, then you will need to know how to Create a MySQL Table and Insert a MySQL Row. Below is the MySQL table "products". 

Products Table:

id name type price

123451 Park's Great Hits Music 19.99

123452 Silly Puddy Toy 3.99

123453 Playstation Toy 89.95

123454 Men's T-Shirt Clothing 32.50

123455 Blouse Clothing 34.97

123456 Electronica 2002 Music 3.99

123457 Country Tunes Music 21.55

123458 Watermelon Food 8.73

 MySQL MAX - Finding the Big One MySQL's MAX aggregate function will find the largest value in a group. The "products" table that is displayed above has several products of various types. We could use the MAX function to find the most expensive item for each type of product. 

Page 58: PHP OOPS Interview Questions

Just as we did in the aggregate introduction lesson, we are going to GROUP BY type to create four groups: Music, Toy, Clothing and Food. We will also be applying the aggregate function to the price column. PHP and MySQL Code:<?php

// Make a MySQL Connection

$query = "SELECT type, MAX(price) FROM products GROUP BY type";

$result = mysql_query($query) or die(mysql_error());

// Print out result

while($row = mysql_fetch_array($result)){

echo "The most expensive ". $row['type']. " is $" .$row['MAX(price)'];

echo "<br />";

}

?>Display: The most expensive Clothing is $34.97

The most expensive Food is $8.73

The most expensive Music is $21.55

The most expensive Toy is $89.95

MySQL and SQL Injection If you take user input through a webpage and insert it into a MySQL database there's a chance that you have left yourself wide open for a security issue known as SQL Injection. This lesson will teach you how to help prevent this from happening and help you secure your scripts and MySQL statements. Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a MySQL statement that you will unknowingly run on your database. Never trust user provided data, process this data only after validation; as a rule, this is done by pattern matching. In the example below, the username is restricted to alphanumerical chars plus underscore and to a length between 8 and 20 chars - modify these rules as needed. if (preg_match("/^\w{8,20}$/", $_GET['username'], $matches))

Page 59: PHP OOPS Interview Questions

{

$result = mysql_query("SELECT * FROM users

WHERE username=$matches[0]");

}

else

{

echo "username not accepted";

}

To demonstrate the problem, consider this excerpt: // supposed input

$name = "Qadir'; DELETE FROM users;";

mysql_query("SELECT * FROM users WHERE name='{$name}'"); The function call is supposed to retrieve a record from the users table where the name column matches the name specified by the user. Under normal circumstances, $name would only contain alphanumeric characters and perhaps spaces, such as the string ilia. But here, by appending an entirely new query to $name, the call to the database turns into disaster: the injected DELETE query removes all records from users. Fortunately, if you use MySQL, the mysql_query() function does not permit query stacking, or executing multiple queries in a single function call. If you try to stack queries, the call fails. However, other PHP database extensions, such as SQLite and PostgreSQL, happily perform stacked queries, executing all of the queries provided in one string and creating a serious security problem.

Preventing SQL Injection: if (get_magic_quotes_gpc())

{

$name = stripslashes($name);

}

$name = mysql_real_escape_string($name);

mysql_query("SELECT * FROM users WHERE name='{$name}'"); 

Page 60: PHP OOPS Interview Questions

The LIKE Quandary: To address the LIKE quandary, a custom escaping mechanism must convert user-supplied % and _ characters to literals. Use addcslashes(), a function that let's you specify a character range to escape. $sub = addcslashes(mysql_real_escape_string("%something_"), "%_");

// $sub == \%something\_

mysql_query("SELECT * FROM messages WHERE subject LIKE '{$sub}%'");

MySQL Date - Formats MySQL comes with several data types for storing a date in its database system: DATETIME, DATE, TIMESTAMP, and YEAR. This lesson will show you the proper formats of each type, show their related MySQL functions, and give an INSERT example of each. Advertise on Tizag.com These date types are chosen for a column when you create a new table in MySQL. Often the most difficult part of using dates in MySQL is to be sure the format of the date you are trying to store matches the format of your table's date column. If you haven't already, try to create a new MySQL table with the date types we mentioned above. We have assembled a "date playground" MySQL table that can be used to follow along with this lesson. dateplayground.sql. Also, the following acronyms are used in this lesson: Y - year segment M - month segment  D - day segment H - hour segment m - minute segment, note the lower case S - sec segment

MySQL Date – DATE The default way to store a date in MySQL is with the type DATE. Below is the proper format of a DATE.YYYY-MM-DD Date Range: 1000-01-01 to 9999-12-31 If you try to enter a date in a format other than the Year-Month-Day format then it might work, but it won't be storing them as you expect.

Page 61: PHP OOPS Interview Questions

 To insert the current date into your table you can use MySQL's built-in function CURDATE() in your query. Below we have created 2 dates, one manually and one using CURDATE().

PHP & MySQL Code: <?php

//This assumes you have already created the 'dateplayground' table

//Connect to DB

$query_manual = "INSERT INTO dateplayground (dp_name, dp_date)

VALUES ('DATE: Manual Date', '2020-2-14')";

$query_auto = "INSERT INTO dateplayground (dp_name, dp_date)

VALUE ('DATE: Auto CURDATE()', CURDATE() )";

mysql_query($query_manual) or die(mysql_error());

mysql_query($query_auto) or die(mysql_error());

?> MySQL Date - YEAR If you just need to store the year of an event, MySQL also has a date type just for that. YEAR's format is simply: YYYY Date Range: 1901 to 2155 It should be noted that the range of years thatcan be stored are from 1901 to 2155. If you need to store years outside that range then use DATE instead of YEAR. Below we have created another manual and automatic example to show off YEAR's use. We have used CURDATE() again, even though it provides a lot more information than YEAR requires. All the date information, besides the year, is just ignored by YEAR.

PHP & MySQL Code: <?php

$query_manual = "INSERT INTO dateplayground (dp_name, dp_year)

VALUES ('YEAR: Manual Year', '2011')";

$query_auto = "INSERT INTO dateplayground (dp_name, dp_year)

Page 62: PHP OOPS Interview Questions

VALUE ('YEAR: Auto CURDATE()', CURDATE() )";

mysql_query($query_manual) or die(mysql_error());

mysql_query($query_auto) or die(mysql_error());

?>

MySQL Date - DATETIME DATETIME actually stores both the current date and time, meaning it has the ability to store the year, month, day, hour, minute, and second inside it. DATETIME's format is: YYYY-MM-DD HH:mm:SS Date Range: 1000-01-01 00:00:00 to 9999-12-31 23:59:59 The hyphen and the colon are the standard character to separate a date and time respectively, but MySQL allows for you to choose your own delimiters if you wish. With DATETIME you can choose to store the date or the time and date together, but you cannot store just the time. In our example below we have manually stored a complete DATETIME and also used three different MySQL functions: CURDATE(), CURTIME(), and NOW(). 

 PHP & MySQL Code:<?php

$query_manual = "INSERT INTO dateplayground (dp_name, dp_datetime)

VALUES ('DATETIME: Manual DateTime', '1776-7-4 04:13:54')";

$query_autodate = "INSERT INTO dateplayground (dp_name, dp_datetime)

VALUE ('DATETIME: Auto CURDATE()', CURDATE() )";

$query_autotime = "INSERT INTO dateplayground (dp_name, dp_datetime)

VALUE ('DATETIME: Auto CURTIME()', CURTIME() )"; //This will fail

$query_autonow = "INSERT INTO dateplayground (dp_name, dp_datetime)

VALUE ('DATETIME: Auto NOW()', NOW() )";

mysql_query($query_manual) or die(mysql_error());

mysql_query($query_autodate) or die(mysql_error());

Page 63: PHP OOPS Interview Questions

mysql_query($query_autotime) or die(mysql_error());

mysql_query($query_autonow) or die(mysql_error());

?>MySQL Date – TIMESTAMPTIMESTAMP is a format popularized by the *NIX operating systems that stores the amount of time that has passed since January 1, 1970. If you want more versatility than this date type provides, remember to try DATETIME. YYYY-MM-DD HH:mm:SS Date Range: 1970-01-01 00:00:00 to 2037-12-31 23:59:59 The big difference between DATETIME and TIMESTAMP is the date ranges that can be stored. Below we have purposely entered an erroneous date, manually, so you can see what happens when you enter a date that is outside the boundaries of a this type.

PHP & MySQL Code:<?php

//This will fail

$query_manual = "INSERT INTO dateplayground (dp_name, dp_timestamp)

VALUES ('TIMESTAMP: Manual Timestamp', '1776-7-4 04:13:54')";

$query_autodate = "INSERT INTO dateplayground (dp_name, dp_timestamp)

VALUE ('TIMESTAMP: Auto CURDATE()', CURDATE() )";

//This will fail

$query_autotime = "INSERT INTO dateplayground (dp_name, dp_timestamp)

VALUE ('TIMESTAMP: Auto CURTIME()', CURTIME() )";

$query_autonow = "INSERT INTO dateplayground (dp_name, dp_timestamp)

VALUE ('TIMESTAMP: Auto NOW()', NOW() )";

mysql_query($query_manual) or die(mysql_error());

mysql_query($query_autodate) or die(mysql_error());

mysql_query($query_autotime) or die(mysql_error());

mysql_query($query_autonow) or die(mysql_error());   ?>

Page 64: PHP OOPS Interview Questions

Viewing dateplayground in PHPBelow is a quick script that will spit out the MySQL table dateplayground in HTML.PHP & MySQL Code:<?php

$query = "SELECT * FROM dateplayground";

$result = mysql_query($query) or die(mysql_error());

echo "<table border='1'><tr>";

for($i = 0; $i < mysql_num_fields($result); $i++){

echo "<th>".mysql_field_name($result, $i)."</th>";

}

echo "</tr>";

while($row = mysql_fetch_array($result)){

echo "<tr>";

for($i = 0; $i < mysql_num_fields($result); $i++){

echo "<td>". $row[$i] ."</td>";

}

echo "</tr>";

}

echo "</table>"; ?>

Finished dateplayground.sql Display:

dp_name dp_year dp_date dp_datetime dp_timestamp

DATE: Manual Date 0000 2020-02-14

0000-00-00 00:00:00

0000-00-00 00:00:00

DATE: Auto CURDATE() 0000 2006-09-19

0000-00-00 00:00:00

0000-00-00 00:00:00

YEAR: Manual Year 2011 0000-00-00

0000-00-00 00:00:00

0000-00-00 00:00:00

YEAR: Auto CURDATE() 2006 0000-00-00

0000-00-00 00:00:00

0000-00-00 00:00:00

DATETIME: Manual DateTime

0000 0000-00-00

1776-07-04 04:13:54

0000-00-00 00:00:00

Page 65: PHP OOPS Interview Questions

DATETIME: Auto CURDATE()

0000 0000-00-00

2006-09-19 00:00:00

0000-00-00 00:00:00

DATETIME: Auto CURTIME()

0000 0000-00-00

0000-00-00 00:00:00

0000-00-00 00:00:00

DATETIME: Auto NOW() 0000 0000-00-00

2006-09-19 16:56:56

0000-00-00 00:00:00

TIMESTAMP: Manual Timestamp

0000 0000-00-00

0000-00-00 00:00:00

0000-00-00 00:00:00

TIMESTAMP: Auto CURDATE()

0000 0000-00-00

0000-00-00 00:00:00

2006-09-19 00:00:00

TIMESTAMP: Auto CURTIME()

0000 0000-00-00

0000-00-00 00:00:00

0000-00-00 00:00:00

TIMESTAMP: Auto NOW()

0000 0000-00-00

0000-00-00 00:00:00

2006-09-19 16:56:56

 

 Notice that the rows DATETIME: Auto CURTIME(), TIMESTAMP: Manual Timestamp, and TIMESTAMP: Auto CURTIME() have all zeros. This is because they were the INSERTs that were erroneous. When you enter dates that are out of the range or in the wrong format for a given date type, MySQL will often just enter in the default value of all zeros.

MySQL Time - Formats There are three different types of time data types in MySQL: TIME, DATETIME, and TIMESTAMP. If you would like to learn more about DATETIME and TIMESTAMP, then check out our MySQL Date section, as we've covered them there. This lesson will just be covering the basics of using TIME. 

 MySQL Time – TIME First you need to create a MySQL table with a TIME type. We have one already created if you want to use it: timeplayground.sql. The TIME data type can be used to store actual times as well as the amount of time between two points in time (like the time between now and the weekend) that may sometimes be larger than 23 hours. H - Hour; M - Minute; S - Second. Standard format: HH:MM:SS Extended hour format: HHH:MM:SS Time Range: -838:59:50 to 838:59:59 When manually entering a time into MySQL it is highly recommended that you use the exact format show above. MySQL allows for many different ways to enter a time, but they don't always behave as you would expect. Using the standard/extended format we have shown above will help you avoid annoying problems. 

Page 66: PHP OOPS Interview Questions

Below we have entered 3 manual times into MySQL. The first is done in the recommended format, the second is a shorthand version of the first and the final example is outside the allowed time range.

PHP & MySQL Code:<?php

//This assumes you have already created the 'dateplayground' table

//Connect to DB

$query_manual1 = "INSERT INTO timeplayground (dp_name, dp_time)

VALUES ('TIME: Manual Time', '12:10:00')"; //perfectly done

$query_manual2 = "INSERT INTO timeplayground (dp_name, dp_time)

VALUES ('TIME: Manual Time', '1210')"; // will this shorthand work?

$query_manual3 = "INSERT INTO timeplayground (dp_name, dp_time)

VALUES ('TIME: Manual Time', '978:31:12')"; //how about this?

mysql_query($query_manual1) or die(mysql_error());

mysql_query($query_manual2) or die(mysql_error());

mysql_query($query_manual3) or die(mysql_error());

?>MySQL Time - NOW() To get the current time, use MySQL's built in function NOW(). NOW() contains both the date and time information, but MySQL is smart enough to just use the data needed for TIME.

PHP & MySQL Code: <?php

$query_auto = "INSERT INTO timeplayground (dp_name, dp_time)

VALUE ('TIME: Auto NOW()', NOW() )";

mysql_query($query_auto) or die(mysql_error());

?> MySQL timeplayground.sql Displayed Below is a small PHP script to spit out a rough version of our timeplayground.sql table. 

Page 67: PHP OOPS Interview Questions

PHP & MySQL Code:<?php

$query = "SELECT * FROM timeplayground";

$result = mysql_query($query) or die(mysql_error());

echo "<table border='1'><tr>";

for($i = 0; $i < mysql_num_fields($result); $i++){ echo "<th>".mysql_field_name($result, $i)."</th>";

}

echo "</tr>";

while($row = mysql_fetch_array($result)){

echo "<tr>";

for($i = 0; $i < mysql_num_fields($result); $i++){

echo "<td>". $row[$i] ."</td>";

}

echo "</tr>";

}

echo "</table>";

?>

Finished timeplayground.sql Display: dp_name dp_time

TIME: Manual Time 12:10:00

TIME: Manual Time 00:12:10

TIME: Manual Time 838:59:59

TIME: Auto NOW() 14:30:36

 Our first manual time was handled just fine, but our second one did not. MySQL interpreted 1210 as MM:SS instead of HH:MM as we assumed. This is why it's best to use the formats we've described at the beginning. The third manual entry was changed from 978:31:12 to 838:59:59, so that it would be within TIME's range.

Page 68: PHP OOPS Interview Questions

MySQL Index - Overclock Your Tables Hardware enthusiasts have been overclocking their PCs for years now, trying to push the limits of their hardware for maximum performance. Sometimes they are successful and their applications run speedy fast, while other times they push a little too hard and end up damaging the computer! Although it isn't quite as extreme, indexes in MySQL can increase the speed of your MySQL queries to squeeze a bit more performance out of your database. MySQL Index - Speed and Extra Overhead Indexes are created on a per column basis. If you have a table with the columns: name, age, birthday and employeeID and want to create an index to speed up how long it takes to find employeeID values in your queries, then you would need to create an index for employeeID. When you create this index, MySQL will build a lookup index where employeeID specific queries can be run quickly. However, the name, age and birthday queries would not be any faster. Indexes are something extra that you can enable on your MySQL tables to increase performance,cbut they do have some downsides. When you create a new index MySQL builds a separate block of information that needs to be updated every time there are changes made to the table. This means that if you are constantly updating, inserting and removing entries in your table this could have a negative impact on performance.

MySQL Index - Overclock Your Tables Hardware enthusiasts have been overclocking their PCs for years now, trying to push the limits of their hardware for maximum performance. Sometimes they are successful and their applications run speedy fast, while other times they push a little too hard and end up damaging the computer! Although it isn't quite as extreme, indexes in MySQL can increase the speed of your MySQL queries to squeeze a bit more performance out of your database. MySQL Index - Speed and Extra Overhead Indexes are created on a per column basis. If you have a table with the columns: name, age, birthday and employeeID and want to create an index to speed up how long it takes to find employeeID values in your queries, then you would need to create an index for employeeID. When you create this index, MySQL will build a lookup index where employeeID specific queries can be run quickly. However, the name, age and birthday queries would not be any faster. Indexes are something extra that you can enable on your MySQL tables to increase performance,cbut they do have some downsides. When you create a new index MySQL builds a separate block of information that needs to be updated every time there are changes made to the table. This means that if you are constantly updating, inserting and removing entries in your table this could have a negative impact on performance.

Creating a MySQL Index - New Table

Page 69: PHP OOPS Interview Questions

 If you are creating a new MySQL table you can specify a column to index by using the INDEX term as we have below. We have created two fields: name and employeeID (index). MySQL Code: CREATE TABLE employee_records (

          name VARCHAR(50),

          employeeID INT, INDEX (employeeID)

) Creating a MySQL Index - Existing TableYou can also add an index to an older table that you think would benefit from some indexing. The syntax is very similar to creating an index in a new table. First, let's create the table.  MySQL Code:CREATE TABLE employee_records2 (name VARCHAR(50), employeeID INT)With our newly created table we are going to update the "employee_records2" table to include an index.

MySQL Code: CREATE INDEX id_index ON employee_records2(employeeID) We keep our existing employeeID field and create a new index id_index that is made up of employeeID data. If you are creating a new MySQL table you can specify a column to index by using the INDEX term as we have below. We have created two fields: name and employeeID (index). MySQL Code: CREATE TABLE employee_records (

name VARCHAR(50),

employeeID INT, INDEX (employeeID)

 Creating a MySQL Index - Existing Table You can also add an index to an older table that you think would benefit from some indexing. The syntax is very similar to creating an index in a new table. First, let's create the table. 

Page 70: PHP OOPS Interview Questions

MySQL Code: CREATE TABLE employee_records2 (name VARCHAR(50), employeeID INT) With our newly created table we are going to update the "employee_records2" table to include an index. MySQL Code: CREATE INDEX id_index ON employee_records2(employeeID) We keep our existing employeeID field and create a new index id_index that is made up of employeeID data.

MySQL Useful Resources MySQL and PERL - Its a tutorial from Tutorials Point which explains you how to use MySQL along with PERL and DBI module. Here you will learn all the required MySQL operations alongwith examples. MySQL Official Website - Here you can download the latest MySQL release, get the MySQL news update. The mailing list is also a great resources for anyone who want to build dynamic websites using MySQL. PHP Official Website: - A complete resource for PHP stuff. Starting from latest PHP updates to latest function manual is available at this site. MySQL at Wikipedia - A small article on MySQL, worth to go through it. MySQL Reference Manual - A complete official reference for MySQL. MySQL-sr-lib - MySQL General Purpose Stored Routines Library. This is a A repository of ready to use routines for everyday needs. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License. Understanding SQL - If you are new to SQL then go through this tutorial to understand SQL basics. SQL, the Structured Query Language, is a mature, powerful, and versatile relational query language.

MySQL Database Introduction What is Database?A database is a separate application that stores a collection of data. Each database has one or more distinct APIs for creating, accessing, managing, searching, and replicating the data it holds. Other kinds of data stores can be used, such as files on the file system or large hash tables in memory but data fetching and writing would not be so fast and easy with those type of systems. So now a days we use relational database management systems (RDBMS) to store and manager huge volume of data. This is called relational database because all the

Page 71: PHP OOPS Interview Questions

data is stored into different tables and relations are established using primary keys or other keys known as foreign keys. A Relational DataBase Management System (RDBMS) is a software that: Enables you to implement a database with tables, columns, and indexes. Guarantees the Referential Integrity between rows of various tables. Updates the indexes automatically. Interprets an SQL query and combines information from various tables.

RDBMS Terminology: Before we proceed to explain MySQL database system, lets revise few definitions related to database. Database: A database is a collection of tables, with related data. Table: A table is a matrix with data. A table in a database looks like a simple sColumn: One column (data element) contains data of one and the same kind, for example the column postcode. Row: A row (= tuple, entry or record) is a group of related data, for example the data of one subscription. Redundancy: Storing data twice, redundantly to make the system faster. Primary Key: A primary key is unique. A key value can not occur twice in one table. With a key you can find at most one row. Foreign Key: A foreign key is the linking pin between two tables. Compound Key: A compound key (composite key) is a key that consists of multiple columns, because one column is not sufficiently unique. Index: An index in a database resembles an index at the back of a book. Referential Integrity: Referential Integrity makes sure that a foreign key value always points to an existing row.

MySQL Database: MySQL is a fast, easy-to-use RDBMS used being used for many small and big businesses. MySQL is developed, marketed, and supported by MySQL AB, which is a Swedish company. MySQL is becoming so popular because of many good reasons. MySQL is released under an open-source license. So you have nothing to pay to use it. 

Page 72: PHP OOPS Interview Questions

MySQL is a very powerful program in its own right. It handles a large subset of the functionality of the most expensive and powerful database packages. MySQL uses a standard form of the well-known SQL data language. MySQL works on many operating systems and with many languages including PHP, PERL, C, C++, JAVA etc. MySQL works very quickly and works well even with large data sets. MySQL is very friendly to PHP, the most appriciated language for web development. MySQL supports large databases, up to 50 million rows or more in a table. The default file size limit for a table is 4GB, but you can increase this (if your operating system can handle it) to a theoretical limit of 8 million terabytes (TB). MySQL is customizable. The open source GPL license allows programmers to modify the MySQL software to fit their own specific environments.

MySQL Installation - Linux and Windows Downloading MySQL: All downloads for MySQL are located at MySQL Downloads. Pick the version number you want and, as exactly as possible, the platform you want. Installing MySQL on Linux/Unix The recommended way to install MySQL on a Linux system is via RPM. MySQL AB makes the following RPMs available for download on its web site: MySQL - The MySQL database server, which manages databases and tables, controls user access, and processes SQL queries. MySQL-client - MySQL client programs, which makes it possible to connect to, and interact with, the server. MySQL-devel - Libraries and header files that come in handy when compiling other programs that use MySQL. MySQL-shared - Shared libraries for the MySQL client MySQL-bench - Benchmark and performance testing tools for the MySQL database server. The MySQL RPMs listed here are all built on a SuSE Linux system, but they.ll usually work on other Linux variants with no difficulty. Now follow the following steps to proceed for installation: Login to the system using root user. 

Page 73: PHP OOPS Interview Questions

Install the MySQL database server by executing the following command. Remember to replace the filename in italics with the file name of your RPM.Switch to the directory containing the RPMs: [root@host]# rpm -i MySQL-5.0.9-0.i386.rpm ? Above command takes care of installing MySQL server, creating a user of MySQL, creating necessary configuration and starting MySQL server automatically. You can find all the MySQL related binaries in /usr/bin and /usr/sbin. All the tables and databases will be created in /var/lib/mysql directory. ? This is optional but recommended step to install the remaining RPMs in the same manner: [root@host]# rpm -i MySQL-client-5.0.9-0.i386.rpm

[root@host]# rpm -i MySQL-devel-5.0.9-0.i386.rpm

[root@host]# rpm -i MySQL-shared-5.0.9-0.i386.rpm

[root@host]# rpm -i MySQL-bench-5.0.9-0.i386.rpm

Installing MySQL on Windows: Default installation on any version of Windows is now much easier than it used to be, as MySQL now comes neatly packaged with an installer. Simply download the installer package, unzip it anywhere, and run setup.exe. Default installer setup.exe will walk you through the trivial process and by default will install everything under C:\mysql. Test the server by firing it up from the command prompt the first time. Go to the location of the mysqld server, which is probably C:\mysql\bin, and type: mysqld.exe --console NOTE: If you are on NT then you will have to use mysqld-nt.exe instead of mysqld.exe If all went well, you will see some messages about startup and InnoDB. If not, you may have a permissions issue. Make sure that the directory that holds your data is accessible to whatever user (probably mysql) the database processes run under. MySQL will not add itself to the start menu, and there is no particularly nice GUI way to stop the server either. Therefore, if you tend to start the server by double clicking the mysqld executable, you should remember to halt the process by hand by using mysqladmin, Task List, Task Manager, or other Windows-specific means.

Verifying MySQL Installation: After MySQL has been successfully installed, the base tables have been initialized, and the server has been started, you can verify that all is working as it should via some simple tests.

Page 74: PHP OOPS Interview Questions

 Use the mysqladmin Utility to Obtain Server Status: Use mysqladmin binary to check server version. This binary would be available in /usr/bin on linux and in C:\mysql\bin on windows.

MySQL Administration Running and Shutting down MySQL Server: First check if your MySQL server is running or not. You can use following command to check this: ps -ef | grep mysqld If your MySql is running then you will see mysqld process listed out in your result. If server is not running then you can start it by using following command: root@hoat# cd /usr/bin ./safe_mysqld & Now if you want to shutdown an already running MySQL server then you can do it by using following command: root@hoat# cd /usr/bin ./mysqladmin -u root -p shutdown 

Enter password: ******

Setting Up a MySQL User Accounts: For adding a new user to MySQL you just need to add a new entry to user table in database mysql. Below is an example of adding new user guest with SELECT, INSERT and UPDATE privileges with the password guest123 the SQL query is : root@host# mysql -u root –p Enter password:******* mysql> use mysql; Database changed mysql> INSERT INTO user (host, user, password,

select_priv, insert_priv, update_priv)

Page 75: PHP OOPS Interview Questions

VALUES ('localhost', 'guest',

PASSWORD('guest123'), 'Y', 'Y', 'Y'); Query OK, 1 row affected (0.20 sec)

mysql> FLUSH PRIVILEGES;

Query OK, 1 row affected (0.01 sec)

mysql> SELECT host, user, password FROM user WHERE user = 'guest'; 

host      | user    | password         |

| localhost | guest | 6f8c114b58f2ce9e |

1 row in set (0.00 sec)

When adding a new user remember to encrypt the new password using PASSWORD() function provided by MySQL. As you can see in the above example the password mypass is encrypted to 6f8c114b58f2ce9e. Notice the FLUSH PRIVILEGES statement. This tells the server to reload the grant tables. If you don't use it then you won't be able to connect to mysql using the new user account at least until the server is rebooted. You can also specify other privileges to a new user by setting the values of following columns in user table to 'Y' when executing the INSERT query or you can update them later using UPDATE query. Select_priv Insert_priv Update_priv Delete_priv Create_priv Drop_priv Reload_priv Shutdown_priv Process_priv File_priv

Page 76: PHP OOPS Interview Questions

 Grant_priv References_priv Index_priv Alter_priv Another way of adding user account is by using GRANT SQL command; Following example will ada user zara with password zara123 for a particular database called TUTORIALS. root@host# mysql -u root -p password; Enter password:*******

mysql> use mysql;

Database changed mysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP -> ON TUTORIALS.*

-> TO 'zara'@'localhost'

-> IDENTIFIED BY 'zara123'; This will also create an entry in mysql database table called user. NOTE: MySQL does not terminate a command until you give a semi colon (;) at the end of SQL command.

The /etc/my.cnf File Configuration: Most of the cases you should not touch this file. By default it will have following entries: [mysqld]

datadir=/var/lib/mysql

socket=/var/lib/mysql/mysql.sock [mysql.server]

user=mysql

basedir=/var/lib [safe_mysqld]

err-log=/var/log/mysqld.log

Page 77: PHP OOPS Interview Questions

pid-file=/var/run/mysqld/mysqld.pid Here you can specify a different directory for error log, otherwise you should not change any entry in this table.

Administrative MySQL Command: Here is the list of important MySQL command which you will use time to time to work with MySQL database: USE Databasename : This will be used to select a particular database in MySQL workarea. SHOW DATABASES: Lists the databases that are accessible by the MySQL DBMS. SHOW TABLES: Shows the tables in the database once a database has been selected with the use command. SHOW COLUMNS FROM tablename: Shows the attributes, types of attributes, key information, whether NULL is permitted, defaults, and other information for a table. SHOW INDEX FROM tablename: Presents the details of all indexes on the table, including the PRIMARY KEY. SHOW TABLE STATUS LIKE tablename\G: Reports details of the MySQL DBMS performance and statistics.

MySQL PHP Syntax MySQL works very well in combination of various programming languages like PERL, C, C++, JAVA and PHP. Out of these languages, PHP is the most popular one because of its web application development capabilities. This tutorial focuses heavily on using MySQL in a PHP environment. If you are interested in MySQL with PERL then you can look into PERL and MySQL Tutorial. PHP provides various functions to access MySQL database and to manipulate data records inside MySQL database. You would require to call PHP functions in the same way you call any other PHP function. The PHP functions for use with MySQL have the following general format: mysql_function(value,value,...); The second part of the function name is specific to the function, usually a word that describes what the function does. The following are two of the functions which we will use in our tutorial mysqli_connect($connect); mysqli_query($connect,"SQL statement");

Page 78: PHP OOPS Interview Questions

Following example shows a generic sysntax of PHP to call any MySQL function. <html>

<head>

<title>PHP with MySQL</title>

</head>

<body>

<?php

$retval = mysql_function(value, [value,...]);

if( !$retval )

{

die ( "Error: a related error message" );

}

// Otherwise MySQL or PHP Statements

?>

</body>

</html> Starting from next chapter we will see all the important MySQL functionality along with PHP.

MySQL Database Connection MySQL Connection using mysql binary: You can establish MySQL database using mysql binary at command prompt. Example: Here is a simple example to connect to MySQL server from command prompt: [root@host]# mysql -u root –p Enter password:****** This will give you mysql> command prompt where you will be able to execute any SQL command. Following is the result of above command: Welcome to the MySQL monitor. Commands end with ; or \g.

Page 79: PHP OOPS Interview Questions

 Your MySQL connection id is 2854760 to server version: 5.0.9 Type 'help;' or '\h' for help. Type '\c' to clear the buffer. In above example we have used root as a user but you can use any other user. Any user will be able to perform all the SQL operation which are allowed to that user. You can disconnect from MySQL database any time using exit command at mysql> prompt. mysql> exit Bye

MySQL Connection using PHP Script: PHP provides mysql_connect() function to open a database connection. This function takes five parameters and returns a MySQL link identifier on success, or FALSE on failure. Syntax: connection mysql_connect(server,user,passwd,new_link,client_flag); Parameter Description server Optional - The host name running database server. If not specified then default value is localhost:3036. user Optional - The username accessing the database. If not specified then default is the name of the user that owns the server process. passwd Optional - The password of the user accessing the database. If not specified then default is an empty password. new_link Optional - If a second call is made to mysql_connect() with the same arguments, no new connection will be established; instead, the identifier of the already opened connection will be returned. client_flags

Optional - A combination of the following constants: MYSQL_CLIENT_SSL - Use SSL encryption 

 MYSQL_CLIENT_COMPRESS - Use compression protocol

 Optional - A combination of the following constants: Allow space after function names MYSQL_CLIENT_INTERACTIVE - Allow interactive timeout seconds of iYou can disconnect from MySQL database anytime using another PHP function mysql_close(). This function takes a single parameter which is a connection returned by mysql_connect() function. 

 Syntax: Bool mysql(resource $link_identifire); 

Page 80: PHP OOPS Interview Questions

If a resource is not specified then last opened database is closed. This function returns true if it closes connection successfully otherwise it returns false. 

 Example:Try out following example to connect to a MySQL server: <html>

<head>

<title>Connecting MySQL Server</title>

</head>

<body>

<?php

$dbhost = 'localhost:3036';

$dbuser = 'guest';

$dbpass = 'guest123';

$conn = mysql_connect($dbhost, $dbuser, $dbpass);

if(! $conn )

{

die('Could not connect: ' . mysql_error());

}

echo 'Connected successfully';

mysql_close($conn);

?>

</body>

</html>

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.

Page 81: PHP OOPS Interview Questions

Data saved to the session by a script can be retrieved by the same script or another script when

requested from the same visitor.Sessions are commonly used to store temporary data to allow

multiple PHP pages to offer a complete functional transaction for the same visitor.What is meant

by PEAR in php?

Answer1:

PEAR is the next revolution in PHP. This repository is bringing higher level programming to PHP.

PEAR is a framework and distribution system for reusable PHP components. It eases installation by

bringing an automated wizard, and packing the strength and experience of PHP users into a nicely

organised OOP library. PEAR also provides a command-line interface that can be used to

automatically install “packages”

Answer2:

PEAR is short for “PHP Extension and Application Repository” and is pronounced just like the fruit.

The purpose of PEAR is to provide:

A structured library of open-sourced code for PHP users

A system for code distribution and package maintenance

A standard style for code written in PHP

The PHP Foundation Classes (PFC),

The PHP Extension Community Library (PECL),

A web site, mailing lists and download mirrors to support the PHP/PEAR community

PEAR is a community-driven project with the PEAR Group as the governing body. The project has

been founded by Stig S. Bakken in 1999 and quite a lot of people have joined the project since

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

Simple arithmetic:

$date1 = date(‘Y-m-d’);

$date2 = ’2006-07-01′;

$days = (strtotime() – strtotime()) / (60 * 60 * 24);

echo “Number of days since ’2006-07-01′: $days”;How can we repair a MySQL table? The syntex

for repairing a mysql table is:

REPAIR TABLE tablename

Page 82: PHP OOPS Interview Questions

REPAIR TABLE tablename QUICK

REPAIR TABLE tablename EXTENDED

This command will repair the table specified.

If QUICK is given, MySQL will do a repair of only the index tree.

If EXTENDED is given, it will create index row by row.What is the difference between $message

and $$message?

Anwser 1:

$message is a simple variable whereas $$message is a reference variable. Example:

$user = ‘bob’

is equivalent to

$holder = ‘user’;

$$holder = ‘bob’;Anwser 2:

They are both variables. But $message is a variable with a fixed name. $$message is a variable

who’s name is stored in $message. For example, if $message contains “var”, $$message is the

same as $var.What Is a Persistent Cookie?

A persistent cookie is a cookie which is stored in a cookie file permanently on the browser’s

computer. By default, cookies are created as temporary cookies which stored only in the browser’s

memory. When the browser is closed, temporary cookies will be erased. You should decide when to

use temporary cookies and when to use persistent cookies based on their differences:

*Temporary cookies can not be used for tracking long-term information.

*Persistent cookies can be used for tracking long-term information.

*Temporary cookies are safer because no programs other than the browser can access them.

*Persistent cookies are less secure because users can open cookie files see the cookie values.What

does a special set of tags <?= and ?> do in PHP?

The output is displayed directly to the browser.How do you define a constant?

Via define() directive, like define (“MYCONSTANT”, 100);What are the differences between

require and include, include_once?

Page 83: PHP OOPS Interview Questions

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:

Page 84: PHP OOPS Interview Questions

string urlencode(str) – Returns the URL encoded version of the input string. String values to be used

in URL query string need to be URL encoded. In the URL encoded version:

Alphanumeric characters are maintained as is.

Space characters are converted to “+” characters.

Other non-alphanumeric characters are converted “%” followed by two hex digits representing the

converted character.

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

$discount =”10.00%”;

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

echo $url;You will get “http://domain.com/submit.php?disc=10%2E00%25″.How To Get the

Uploaded File Information in the Receiving Script?

Once the Web server received the uploaded file, it will call the PHP script specified in the form action

attribute to process them. This receiving PHP script can get the uploaded file information through

the predefined array called $_FILES. Uploaded file information is organized in $_FILES as a two-

dimensional array as:

$_FILES[$fieldName]['name'] – The Original file name on the browser system.

$_FILES[$fieldName]['type'] – The file type determined by the browser.

$_FILES[$fieldName]['size'] – The Number of bytes of the file content.

$_FILES[$fieldName]['tmp_name'] – The temporary filename of the file in which the uploaded file

was stored on the server.

$_FILES[$fieldName]['error'] – The error code associated with this file upload.

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

difference between mysql_fetch_object and mysql_fetch_array?

MySQL fetch object will collect first single matching record where mysql_fetch_array will collect all

matching records from the table in an arrayHow can I execute a PHP script using command

line?

Page 85: PHP OOPS Interview Questions

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

command line argument. For example, “php myScript.php”, assuming “php” is the command to

invoke the CLI program.

Be aware that if your PHP script was written for the Web CGI interface, it may not execute properly

in command line environment.I am trying to assign a variable the value of 0123, but it keeps coming

up with a different number, what’s the problem?

PHP Interpreter treats numbers beginning with 0 as octal. Look at the similar PHP interview

questions for more numeric problems.Would I use print “$a dollars” or “{$a} dollars” to print out the

amount of dollars in this example?

In this example it wouldn’t matter, since the variable is all by itself, but if you were to print

something like “{$a},000,000 mln dollars”, then you definitely need to use the braces.What are the

different tables present in MySQL? Which type of table is generated when we are creating a table in

the following syntax: create table employee(eno int(2),ename varchar(10))?

Total 5 types of tables we can create

1. MyISAM2. Heap

3. Merge

4. INNO DB

5. ISAM

MyISAM is the default storage engine as of MySQL 3.23. When you fire the above create query

MySQL will create a MyISAM table.How To Create a Table?

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

sample script:

<?php

include “mysql_connection.php”;

$sql = “CREATE TABLE Tech_links (“

. ” id INTEGER NOT NULL”

. “, url VARCHAR(80) NOT NULL”

. “, notes VARCHAR(1024)”

Page 86: PHP OOPS Interview Questions

. “, counts INTEGER”

. “, time TIMESTAMP DEFAULT sysdate()”

. “)”;

if (mysql_query($sql, $con)) {

print(“Table Tech_links created.\n”);

} else {

print(“Table creation failed.\n”);

}

mysql_close($con);

?>

Remember that mysql_query() returns TRUE/FALSE on CREATE statements. If you run this script, you

will get something like this:

Table Tech_links created.How can we encrypt the username and password using PHP?

Answer1

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

Answer2

You can use the MySQL PASSWORD() function to encrypt username and password. For example,

INSERT into user (password, …) VALUES (PASSWORD($password”)), …);How do you pass a

variable by value?

Just like in C++, put an ampersand in front of it, like $a = &$bWhat is the functionality of the

functions STRSTR() and STRISTR()?

string strstr ( string haystack, string needle ) returns part of haystack string from the first

occurrence of needle to the end of haystack. This function is case-sensitive.

stristr() is idential to strstr() except that it is case insensitive.When are you supposed to use endif to

end the conditional statement?

Page 87: PHP OOPS Interview Questions

When the original if was followed by : and then the code block without braces.How can we send mail

using JavaScript?

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

But you can use JavaScript to execute a client side email program send the email using the “mailto”

code. Here is an example:

function myfunction(form)

{

tdata=document.myform.tbox1.value;

location=”mailto:[email protected]?subject=…”;

return true;

}What is the functionality of the function strstr and stristr?

strstr() returns part of a given string from the first occurrence of a given substring to the end of the

string. For example: strstr(“[email protected]”,”@”) will return “@example.com”.

stristr() is idential to strstr() except that it is case insensitive.What is the difference between

ereg_replace() and eregi_replace()?

eregi_replace() function is identical to ereg_replace() except that it ignores case distinction when

matching alphabetic characters.How do I find out the number of parameters passed into

function9. ?

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

following files having extensions: frm, myd, and myi? What these files contain?

In MySQL, the default table type is MyISAM.

Each MyISAM table is stored on disk in three files. The files have names that begin with the table

name and have an extension to indicate the file type.

The ‘.frm’ file stores the table definition.

The data file has a ‘.MYD’ (MYData) extension.

The index file has a ‘.MYI’ (MYIndex) extension,If the variable $a is equal to 5 and variable $b

is equal to character a, what’s the value of $$b?

Page 88: PHP OOPS Interview Questions

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

<?php

print(“<html>”);

print(“<p>Please click the links below”

.” to submit comments about TECHPreparation.com:</p>”);

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

$comment = urlencode($comment);

print(“<p>”

.”<a href=\”processing_forms.php?name=Guest&comment=$comment\”>”

.”It’s an excellent site!</a></p>”);

$comment = ‘This visitor said: “It\’s an average site!   “‘;

$comment = urlencode($comment);

print(“<p>”

.’<a href=”processing_forms.php?’.$comment.’”>’

.”It’s an average site.</a></p>”);

print(“</html>”);

?>Are objects passed by value or by reference?

Everything is passed by value.What are the differences between DROP a table and

TRUNCATE a table?

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

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

definition.How do you call a constructor for a parent class?

Page 89: PHP OOPS Interview Questions

parent::constructor($value)WHAT ARE THE DIFFERENT TYPES OF ERRORS IN PHP?

Here are three basic types of runtime errors in PHP:

1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script – for

example, accessing a variable that has not yet been defined. By default, such errors are not

displayed to the user at all – although you can change this default behavior.

2. Warnings: These are more serious errors – for example, attempting to include() a file which does

not exist. By default, these errors are displayed to the user, but they do not result in script

termination.

3. Fatal errors: These are critical errors – for example, instantiating an object of a non-existent class,

or calling a non-existent function. These errors cause the immediate termination of the script, and

PHP’s default behavior is to display them to the user when they take place.

Internally, these variations are represented by twelve different error typesWhat’s the special

meaning of __sleep and __wakeup?

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

them.How can we submit a form without a submit button?

If you don’t want to use the Submit button to submit a form, you can use normal hyper links to

submit a form. But you need to use some JavaScript code in the URL of the link. For example:

<a href=”javascript: document.myform.submit();”>Submit Me</a> Why doesn’t the following code

print the newline properly? <?php $str = ‘Hello, there.\nHow are you?\nThanks for visiting

techpreparation’; print $str; ?>

Because inside the single quotes the \n character is not interpreted as newline, just as a sequence of

two characters – \ and n.Would you initialize your strings with single quotes or double

quotes?

Since the data inside the single-quoted string is not parsed for variable substitution, it’s always a

better idea speed-wise to initialize a string with single quotes, unless you specifically need variable

substitution.How can we extract string ‘abc.com ‘ from a string http://[email protected] using regular

expression of php?

We can use the preg_match() function with “/.*@(.*)$/” as

the regular expression pattern. For example:

preg_match(“/.*@(.*)$/”,”http://[email protected]”,$data);

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?

Page 90: PHP OOPS Interview Questions

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:

Page 91: PHP OOPS Interview Questions

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_register($session_var);

$_SESSION['var'] = ‘value’;What is the difference between characters 23 and \x23?

The first one is octal 23, the second is hex 23.With a heredoc syntax, do I get variable

substitution inside the heredoc contents?

Yes.How can we submit form without a submit button?

We can use a simple JavaScript code linked to an event trigger of any form field. In the JavaScript

code, we can call the document.form.submit() function to submit the form. For example: <input

Page 92: PHP OOPS Interview Questions

type=button value=”Save” onClick=”document.form.submit()”>How can we create a database

using PHP and mysql?

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

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

As individual objects so single record or as a set or arrays.Can we use include (“abc.php”) two times

in a php page “makeit.php”?

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

echo is the most primitive of them, and just outputs the contents following the construct to the

screen. print is also a construct (so parentheses are optional when calling it), but it returns TRUE on

successful output and FALSE if it was unable to print out the string. However, you can pass multiple

parameters to echo, like:

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

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?

$formatted = ucwords(“TECHPREPARATIONS IS COLLECTION OF INTERVIEW QUESTIONS”);

print $formatted;

What will be printed is TECHPREPARATIONS IS COLLECTION OF INTERVIEW QUESTIONS.

ucwords() makes every first letter of every word capital, but it does not lower-case anything else. To

avoid this, and get a properly formatted string, it’s worth using strtolower() first.What’s the

difference between htmlentities() and htmlspecialchars()?

htmlspecialchars only takes care of <, >, single quote ‘, double quote ” and ampersand. htmlentities

translates all occurrences of character sequences that have different meaning in HTML.How can we

extract string “abc.com” from a string “mailto:[email protected]?subject=Feedback” using

regular expression of PHP?

$text = “mailto:[email protected]?subject=Feedback”;

preg_match(‘|.*@([^?]*)|’, $text, $output);

Page 93: PHP OOPS Interview Questions

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 variablesWhat are the different functions in sorting an

array?

Sorting functions in PHP:

asort()

arsort()

ksort()krsort()

uksort()

sort()

natsort()

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

2 ways:

a) sizeof($array) – This function is an alias of count()

b) count($urarray) – This function returns the number of elements in an array.

Interestingly if you just pass a simple var instead of an array, count() will return 1.How many ways

we can pass the variable through the navigation between the pages?

At least 3 ways:

1. Put the variable into session in the first page, and get it back from session in the next page.

Page 94: PHP OOPS Interview Questions

2. Put the variable into cookie in the first page, and get it back from the cookie in the next page.

3. Put the variable into a hidden form field, and get it back from the form in the next page.What is

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

Database name: 64 characters

Table name: 64 characters

Column name: 64 charactersHow many values can the SET function of MySQL take?

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

are the other commands to know the structure of a table using MySQL commands except

EXPLAIN command?

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

Use this for MySQL

SELECT COUNT(*) FROM table_name;What’s the difference between md5(), crc32() and

sha1() crypto on PHP?

The major difference is the length of the hash generated. CRC32 is, evidently, 32 bits, while sha1()

returns a 128 bit value, and md5() returns a 160 bit value. This is important when avoiding

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

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

$result = mysql_query($any_valid_sql, $database_link);

$num_rows = mysql_num_rows($result);

echo “$num_rows rows found”;How many ways we can we find the current date using

MySQL?

SELECT CURDATE();

SELECT CURRENT_DATE();

SELECT CURTIME();

SELECT CURRENT_TIME();Give the syntax of GRANT commands?

The generic syntax for GRANT is as following

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

Now rights can be:

Page 95: PHP OOPS Interview Questions

a) ALL privilages

b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc.

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

specific table by database.table_name.Give the syntax of REVOKE commands?

The generic syntax for revoke is as following

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

Now rights can be:

a) ALL privileges

b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc.We can grant rights on

all database by using *.* or some specific database by database.* or a specific table by

database.table_name.What is the difference between CHAR and VARCHAR data types?

CHAR is a fixed length data type. CHAR(n) will take n characters of storage even if you enter less

than n characters to that column. For example, “Hello!” will be stored as “Hello! ” in CHAR(10)

column.

VARCHAR is a variable length data type. VARCHAR(n) will take only the required storage for the

actual number of characters entered to that column. For example, “Hello!” will be stored as “Hello!”

in VARCHAR(10) column.How can we encrypt and decrypt a data present in a mysql table

using mysql?

AES_ENCRYPT() and AES_DECRYPT()Will comparison of string “10″ and integer 11 work in

PHP?

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

compared.What is the functionality of MD5 function in PHP?

string md5(string)

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

load data from a text file into a table?

The MySQL provides a LOAD DATA INFILE command. You can load data from a file. Great tool but

you need to make sure that:

a) Data must be delimited

b) Data fields must match table columns correctlyHow can we know the number of days

between two given dates using MySQL?

Use DATEDIFF()

Page 96: PHP OOPS Interview Questions

SELECT DATEDIFF(NOW(),’2006-07-01′);How can we change the name of a column of a table?

This will change the name of column:

ALTER TABLE table_name CHANGE old_colm_name new_colm_nameHow can we change the data

type of a column of a table?

This will change the data type of a column:

ALTER TABLE table_name CHANGE colm_name same_colm_name [new data type]What is the

difference between GROUP BY and ORDER BY in SQL?

To sort a result, use an ORDER BY clause.

The most general way to satisfy a GROUP BY clause is to scan the whole table and create a new

temporary table where all rows from each group are consecutive, and then use this temporary table

to discover groups and apply aggregate functions (if any).

ORDER BY [col1],[col2],…[coln]; Tells DBMS according to what columns it should sort the result. If

two rows will have the same value in col1 it will try to sort them according to col2 and so on.

GROUP BY [col1],[col2],…[coln]; Tells DBMS to group (aggregate) results with same value of column

col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, if you want to count all items in group,

sum all values or view average.What is meant by MIME?

Answer 1:

MIME is Multipurpose Internet Mail Extensions is an Internet standard for the format of e-mail.

However browsers also uses MIME standard to transmit files. MIME has a header which is added to a

beginning of the data. When browser sees such header it shows the data as it would be a file (for

example image)

Some examples of MIME types:

audio/x-ms-wmp

image/png

application/x-shockwave-flash

Answer 2:

Multipurpose Internet Mail Extensions.

Page 97: PHP OOPS Interview Questions

WWW’s ability to recognize and handle files of different types is largely dependent on the use of the

MIME (Multipurpose Internet Mail Extensions) standard. The standard provides for a system of

registration of file types with information about the applications needed to process them. This

information is incorporated into Web server and browser software, and enables the automatic

recognition and display of registered file types. …How can we know that a session is started or not?

A session starts by session_start() function.

This session_start() is always declared in header portion. it always declares first. then we write

session_register().What are the differences between mysql_fetch_array(), mysql_fetch_object(),

mysql_fetch_row()?

Answer 1:

mysql_fetch_array() -> Fetch a result row as a combination of associative array and regular

array.mysql_fetch_object() -> Fetch a result row as an object.

mysql_fetch_row() -> Fetch a result set as a regular array().

Answer 2:

The difference between mysql_fetch_row() and mysql_fetch_array() is that the first returns the

results in a numeric array ($row[0], $row[1], etc.), while the latter returns a the results an array

containing both numeric and associative keys ($row['name'], $row['email'], etc.).

mysql_fetch_object() returns an object ($row->name, $row->email, etc.).If we login more than

one browser windows at the same time with same user and after that we close one

window, then is the session is exist to other windows or not? And if yes then why? If no

then why?

Session depends on browser. If browser is closed then session is lost. The session data will be

deleted after session time out. If connection is lost and you recreate connection, then session will

continue in the browser.What are the MySQL database files stored in system ?

Data is stored in name.myd

Table structure is stored in name.frm

Index is stored in name.myiWhat 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.

Page 98: PHP OOPS Interview Questions

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.phpWhat are the differences between

mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?

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

mysql_fetch_object – Returns an object with properties that correspond to the fetched row and

moves the internal data pointer ahead. Returns an object with properties that correspond to the

fetched row, or FALSE if there are no more rows

mysql_fetch_row() – Fetches one row of data from the result associated with the specified result

identifier. The row is returned as an array. Each result column is stored in an array offset, starting at

offset 0.What is meant by nl2br()?

Anwser1:

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

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

output:

god bless<br>

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

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

AES_ENCRYPT(str, key_str)

AES_DECRYPT(crypt_str, key_str)How can I retrieve values from one database server and

store them in other database server using PHP?

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

other server and simply insert the data into the database.Who is the father of PHP and what is the

current version of PHP and MYSQL?

Rasmus Lerdorf.

PHP 5.1. Beta

Page 99: PHP OOPS Interview Questions

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

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

mysql_fetch_assoc – Fetch a result row as an associative arraymysql_fetch_object – Fetch a result

row as an object

mysql_fetch_row —- Get a result row as an enumerated arrayWhat 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 messageWhat are encryption functions in PHP?

CRYPT()

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

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

htmlentities() – Convert ALL special characters to HTML entitiesWhat 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() functionHow 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

Page 100: PHP OOPS Interview Questions

made, the script will run for a total of 45 seconds before timing out.HOW CAN WE TAKE A BACKUP

OF A MYSQL TABLE AND HOW CAN WE RESTORE IT?

Answer 1:

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

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

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

shell> mysql “.”Executed”;

Answer 2:

To backup: BACKUP TABLE tbl_name TO /path/to/backup/directory

’ To restore: RESTORE TABLE tbl_name FROM /path/to/backup/directory

mysqldump: Dumping Table Structure and Data

Utility to dump a database or a collection of database for backup or for transferring the data to

another SQL server (not necessarily a MySQL server). The dump will contain SQL statements to

create the table and/or populate the table.

-t, no-create-info

Don’t write table creation information (the CREATE TABLE statement).

-d, no-data

Don’t write any row information for the table. This is very useful if you just want to get a dump of the

structure for a table!How to set cookies?

setcookie(‘variable’,'value’,'time’)

;

variable – name of the cookie variable

value – value of the cookie variable

time – expiry time

Page 101: PHP OOPS Interview Questions

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 hourHow to reset/destroy a cookie ?

Reset a cookie by specifying expire time in the past:

Example: setcookie(‘Test’,$i,time()-3600); // already expired time

Reset a cookie by specifying its name only

Example: setcookie(‘Test’);What types of images that PHP supports ?

Using imagetypes() function to find out what types of images are supported in your PHP

engine.imagetypes() – Returns the image types supported.

This function returns a bit-field corresponding to the image formats supported by the version of GD

linked into PHP. The following bits are returned, IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP |

IMG_XPM.Check if a variable is an integer in JAVASCRIPT ?

var myValue =9.8;

if(parseInt(myValue)== myValue)

alert(‘Integer’);

else

alert(‘Not an integer’);Tools used for drawing ER diagrams.

Case Studio

Smart DrawHow 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

Page 102: PHP OOPS Interview Questions

The isNaN() function is used to check if a value is not a number.

Syntax

isNaN(number)

Parameter Description

number Required. The value to be testedHow 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.1What 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

Page 103: PHP OOPS Interview Questions

set to be friends of other classes, by using a friend specifier in the class that is admitting them. Such

functions can use all attributes of the class which names them as a friend, as if they were

themselves members of that class. A friend declaration is essentially a prototype for a member

function, but instead of requiring an implementation with the name of that class attached by the

double colon syntax, a global function or member function of another class provides the match.class

mylinkage

{

private:

mylinkage * prev;

mylinkage * next;

protected:

friend void set_prev(mylinkage* L, mylinkage* N);

void set_next(mylinkage* L);

public:

mylinkage * succ();

mylinkage * pred();

mylinkage();

};

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

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

Friends in other classes

It is possible to specify a member function of another class as a friend as follows:

class C

{

Page 104: PHP OOPS Interview Questions

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 fileHow 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 are the advantages of stored procedures, triggers, indexes?

Page 105: PHP OOPS Interview Questions

A stored procedure is a set of SQL commands that can be compiled and stored in the server. Once

this has been done, clients don’t need to keep re-issuing the entire query but can refer to the stored

procedure. This provides better overall performance because the query has to be parsed only once,

and less information needs to be sent between the server and the client. You can also raise the

conceptual level by having libraries of functions in the server. However, stored procedures of course

do increase the load on the database server system, as more of the work is done on the server side

and less on the client (application) side. Triggers will also be implemented. A trigger is effectively a

type of stored procedure, one that is invoked when a particular event occurs. For example, you can

install a stored procedure that is triggered each time a record is deleted from a transaction table

and that stored procedure automatically deletes the corresponding customer from a customer table

when all his transactions are deleted. Indexes are used to find rows with specific column values

quickly. Without an index, MySQL must begin with the first row and then read through the entire

table to find the relevant rows. The larger the table, the more this costs. If the table has an index for

the columns in question, MySQL can quickly determine the position to seek to in the middle of the

data file without having to look at all the data. If a table has 1,000 rows, this is at least 100 times

faster than reading sequentially. If you need to access most of the rows, it is faster to read

sequentially, because this minimizes disk seeks.What is maximum size of a database in mysql?

If the operating system or filesystem places a limit on the number of files in a directory, MySQL is

bound by that constraint. The efficiency of the operating system in handling large numbers of files in

a directory can place a practical limit on the number of tables in a database. If the time required to

open a file in the directory increases significantly as the number of files increases, database

performance can be adversely affected.

The amount of available disk space limits the number of tables.

MySQL 3.22 had a 4GB (4 gigabyte) limit on table size. With the MyISAM storage engine in MySQL

3.23, the maximum table size was increased to 65536 terabytes (2567 – 1 bytes). With this larger

allowed table size, the maximum effective table size for MySQL databases is usually determined by

operating system constraints on file sizes, not by MySQL internal limits.

The InnoDB storage engine maintains InnoDB tables within a tablespace that can be created from

several files. This allows a table to exceed the maximum individual file size. The tablespace can

include raw disk partitions, which allows extremely large tables. The maximum tablespace size is

64TB.

The following table lists some examples of operating system file-size limits. This is only a rough

guide and is not intended to be definitive. For the most up-to-date information, be sure to check the

documentation specific to your operating system.

Operating System File-size Limit

Page 106: PHP OOPS Interview Questions

Linux 2.2-Intel 32-bit 2GB (LFS: 4GB)

Linux 2.4+ (using ext3 filesystem) 4TB

Solaris 9/10 16TB

NetWare w/NSS filesystem 8TB

Win32 w/ FAT/FAT32 2GB/4GB

Win32 w/ NTFS 2TB (possibly larger)

MacOS X w/ HFS+ 2TBExplain normalization concept?

The normalization process involves getting our data to conform to three progressive normal forms,

and a higher level of normalization cannot be achieved until the previous levels have been achieved

(there are actually five normal forms, but the last two are mainly academic and will not be

discussed).

First Normal Form

The First Normal Form (or 1NF) involves removal of redundant data from horizontal rows. We want to

ensure that there is no duplication of data in a given row, and that every column stores the least

amount of information possible (making the field atomic).

Second Normal Form

Where the First Normal Form deals with redundancy of data across a horizontal row, Second Normal

Form (or 2NF) deals with redundancy of data in vertical columns. As stated earlier, the normal forms

are progressive, so to achieve Second Normal Form, your tables must already be in First Normal

Form.

Third Normal Form

I have a confession to make; I do not often use Third Normal Form. In Third Normal Form we are

looking for data in our tables that is not fully dependant on the primary key, but dependant on

another value in the tableWhat’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?

Page 107: PHP OOPS Interview Questions

External Style Sheets

Advantages

Can control styles for multiple documents at once Classes can be created for use on multiple HTML

element types in many documents Selector and grouping methods can be used to apply styles

under complex contexts

Disadvantages

An extra download is required to import style information for each document The rendering of the

document may be delayed until the external style sheet is loaded Becomes slightly unwieldy for

small quantities of style definitions

Embedded Style Sheets

Advantages

Classes can be created for use on multiple tag types in the document Selector and grouping

methods can be used to apply styles under complex contexts No additional downloads necessary to

receive style information

Disadvantage

This method can not control styles for multiple documents at once

Inline Styles

Advantages

Useful for small quantities of style definitions Can override other style specification methods at the

local level so only exceptions need to be listed in conjunction with other style methods

Disadvantages

Does not distance style information from content (a main goal of SGML/HTML) Can not control styles

for multiple documents at once Author can not create or control classes of elements to control

multiple element types within the document Selector grouping methods can not be used to create

complex element addressing scenariosWhat type of inheritance that php supports?

Page 108: PHP OOPS Interview Questions

In PHP an extended class is always dependent on a single base class, that is, multiple inheritance is

not supported. Classes are extended using the keyword ‘extends’.How can increase the

performance of MySQL select query?

We can use LIMIT to stop MySql for further search in table after we have received our required no. of

records, also we can use LEFT JOIN or RIGHT JOIN instead of full join in cases we have related data in

two or more tables.How can we change the name of a column of a table?

MySQL query to rename table: RENAME TABLE tbl_name TO new_tbl_nameALTER TABLE tableName

CHANGE OldName newName.When you want to show some part of a text displayed on an

HTML page in red font color? What different possibilities are there to do this? What are

the advantages/disadvantages of these methods?

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

1. Using HTML tag <font color=”red”>

2. Using HTML tag <span style=”color: red”>When viewing an HTML page in a Browser, the

Browser often keeps this page in its cache. What can be possible

advantages/disadvantages of page caching? How can you prevent caching of a certain

page (please give several alternate solutions)?

When you use the metatag in the header section at the beginning of an HTML Web page, the Web

page may still be cached in the Temporary Internet Files folder.

A page that Internet Explorer is browsing is not cached until half of the 64 KB buffer is filled. Usually,

metatags are inserted in the header section of an HTML document, which appears at the beginning

of the document. When the HTML code is parsed, it is read from top to bottom. When the metatag is

read, Internet Explorer looks for the existence of the page in cache at that exact moment. If it is

there, it is removed. To properly prevent the Web page from appearing in the cache, place another

header section at the end of the HTML document.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=”([^"]*)”/iHow can I use the COM components in php?

The COM class provides a framework to integrate (D)COM components into your PHP scripts.

Page 109: PHP OOPS Interview Questions

string COM::COM( string module_name [, string server_name [, int codepage]]) – COM class

constructor.

Parameters:

module_name: name or class-id of the requested component.

server_name: name of the DCOM server from which the component should be fetched. If NULL,

localhost is assumed. To allow DCOM com, allow_dcom has to be set to TRUE in php.ini.

codepage – specifies the codepage that is used to convert php-strings to unicode-strings and vice

versa. Possible values are CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7

and CP_UTF8.

Usage:

$word->Visible = 1; //open an empty document

$word->Documents->Add(); //do some weird stuff

$word->Selection->TypeText(“This is a test…”);

$word->Documents[1]->SaveAs(“Useless test.doc”); //closing word

$word->Quit(); //free the object

$word->Release();

$word = null;How many ways we can give the output to a browser?

HTML output

PHP, ASP, JSP, Servlet Function

Script Language output Function

Different Type of embedded Package to output to a browserWhat is the default session time in

php and how can I change it?

The default session time in php is until closing of browser What changes I have to do in php.ini

file for file uploading?

Make the following line uncomment like:

Page 110: PHP OOPS Interview Questions

; Whether to allow HTTP file uploads.

file_uploads = On

; Temporary directory for HTTP uploaded files (will use system default if not

; specified).

upload_tmp_dir = C:\apache2triad\temp

; Maximum allowed size for uploaded files.

upload_max_filesize = 2MHow can I set a cron and how can I execute it in Unix, Linux, and windows?

Cron is very simply a Linux module that allows you to run commands at predetermined times or

intervals. In Windows, it’s called Scheduled Tasks. The name Cron is in fact derived from the same

word from which we get the word chronology, which means order of time.

The easiest way to use crontab is via the crontab command.# crontabThis command ‘edits’ the

crontab. Upon employing this command, you will be able to enter the commands that you wish to

run. My version of

Linux uses the text editor vi. You can find information on using vi here.

The syntax of this file is very important – if you get it wrong, your crontab will not function properly.

The syntax of the file should be as follows:

minutes hours day_of_month month day_of_week command

All the variables, with the exception of the command itself, are numerical constants. In addition to

an asterisk (*), which is a wildcard that allows any value, the ranges permitted for each field are as

follows:

Minutes: 0-59

Hours: 0-23

Day_of_month: 1-31

Month: 1-12

Weekday: 0-6

Page 111: PHP OOPS Interview Questions

We can also include multiple values for each entry, simply by separating each value with a comma.

command can be any shell command and, as we will see momentarily, can also be used to execute

a Web document such as a PHP file.

So, if we want to run a script every Tuesday morning at 8:15 AM, our mycronjob file will contain the

following content on a single line:

15 8 * * 2 /path/to/scriptname

This all seems simple enough, right? Not so fast! If you try to run a PHP script in this manner,

nothing will happen (barring very special configurations that have PHP compiled as an executable,

as opposed to an Apache module). The reason is that, in order for PHP to be parsed, it needs to be

passed through Apache. In other words, the page needs to be called via a browser or other means of

retrieving

Web content. For our purposes, I’ll assume that your server configuration includes wget, as is the

case with most default configurations. To test your configuration, log in to shell. If you’re using an

RPM-based system (e.g. Redhat or Mandrake), type the following:

# wget help

If you are greeted with a wget package identification, it is installed in your system.

You could execute the PHP by invoking wget on the URL to the page, like so:

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

Now, let’s go back to the mailstock.php file we created in the first part of this article. We saved it in

our document root, so it should be accessible via the Internet. Remember that we wanted it to run at

4PM Eastern time, and send you your precious closing bell report? Since I’m located in the Eastern

timezone, we can go ahead and set up our crontab to use 4:00, but if you live elsewhere, you might

have to compensate for the time difference when setting this value.

This is what my crontab will look like:

0 4 * * 1,2,3,4,5 we get http://www.example.com/mailstock.phpSteps 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

Page 112: PHP OOPS Interview Questions

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 batchingHow many ways

I can redirect a PHP page?

Here are the possible ways of php page redirection.

1. Using Java script:

‘; echo ‘window.location.href=”‘.$filename.’”;’; echo ”; echo ”; echo ”; echo ”; } }

redirect(‘http://maosjb.com’); ?>

2. Using php function: header(“Location:http://maosjb.com “);List out different arguments in

PHP header function?

void header ( string string [, bool replace [, int http_response_code]])What type of headers have

to be added in the mail function to attach a file?

$boundary = ‘–’ . md5( uniqid ( rand() ) );

$headers = “From: \”Me\”\n”;

$headers .= “MIME-Version: 1.0\n”;

$headers .= “Content-Type: multipart/mixed; boundary=\”$boundary\”";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.

Page 113: PHP OOPS Interview Questions

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:

Page 114: PHP OOPS Interview Questions

getProperty(‘java.version’) . ”; echo ‘Java vendor=’ . $system->getProperty(‘java.vendor’) . ”; echo

‘OS=’ . $system->getProperty(‘os.name’) . ‘ ‘ . $system->getProperty(‘os.version’) . ‘ on ‘ . $system-

>getProperty(‘os.arch’) . ‘ ‘; // java.util.Date example $formatter = new

Java(‘java.text.SimpleDateFormat’, “EEEE, MMMM dd, yyyy ‘at’ h:mm:ss a zzzz”); echo $formatter-

>format(new Java(‘java.util.Date’)); ?>

The behaviour of these functions is affected by settings in php.ini.

Table 1. Java configuration options

Name

Default

Changeable

java.class.path

NULL

PHP_INI_ALL

Name Default Changeable

java.home

NULL

PHP_INI_ALL

java.library.path

NULL

PHP_INI_ALL

java.library

JAVALIB

PHP_INI_ALLExplain the ternary conditional operator in PHP?

Page 115: PHP OOPS Interview Questions

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.

What is meant by MVC (Model View Controller)?

MODEL VIEW CONTROLLER, is a software architecture, currently considered an architectural

pattern used in software engineering.

This isolates business logic from presentation logic.

1. The Model represents the application data

2. The View renders a presentation of model data

3. The Controller handles and routes requests made by the client