You are on page 1of 68

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 Ior developing web
based soItware applications.
What Is a Session?
A session is a logical object created by the PHP engine to allow you to preserve data across
subsequent HTTP requests.

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

Sessions are commonly used to store temporary data to allow multiple PHP pages to oIIer a
complete Iunctional transaction Ior 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 Iramework and distribution system Ior reusable PHP components. It eases
installation by bringing an automated wizard, and packing the strength and experience oI PHP
users into a nicely organised OOP library. PEAR also provides a command-line interIace that
can be used to automatically install "packages"

Answer2:
PEAR is short Ior "PHP Extension and Application Repository" and is pronounced just like the
Iruit. The purpose oI PEAR is to provide:
A structured library oI open-sourced code Ior PHP users
A system Ior code distribution and package maintenance
A standard style Ior 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 Iounded by Stig S. Bakken in 1999 and quite a lot oI 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 oI days since '2006-07-01': $days";
How can we repair a MySQL table?
The syntex Ior repairing a mysql table is:

REPAIR TABLE tablename
REPAIR TABLE tablename QUICK
REPAIR TABLE tablename EXTENDED

This command will repair the table speciIied.
II QUICK is given, MySQL will do a repair oI only the index tree.
II 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 reIerence variable. Example:
$user 'bob'

is equivalent to

$holder 'user';
$$holder 'bob';


Anwser 2:
They are both variables. But $message is a variable with a Iixed name. $$message is a variable
who's name is stored in $message. For example, iI $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 Iile permanently on the browser's
computer. By deIault, 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
diIIerences:
*Temporary cookies can not be used Ior tracking long-term inIormation.
*Persistent cookies can be used Ior tracking long-term inIormation.
*Temporary cookies are saIer because no programs other than the browser can access them.
*Persistent cookies are less secure because users can open cookie Iiles 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 deIine() directive, like deIine ("MYCONSTANT", 100);
What are the differences between require and include, include_once?
Anwser 1:
requireonce() and includeonce() are both the Iunctions to include and evaluate the speciIied
Iile only once. II the speciIied Iile 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 includeonce() statement includes and evaluates the speciIied Iile during the execution oI
the script. This is a behavior similar to the include() statement, with the only diIIerence being
that iI the code Irom a Iile has already been included, it will not be included again. The major
diIIerence between include() and require() is that in Iailure include() produces a warning
message whereas require() produces a Iatal errors.

Anwser 3:
All three are used to an include Iile into the current page.
II the Iile is not present, require(), calls a Iatal error, while in include() does not.
The includeonce() statement includes and evaluates the speciIied Iile during the execution oI
the script. This is a behavior similar to the include() statement, with the only diIIerence being
that iI the code Irom a Iile has already been included, it will not be included again. It des not call
a Iatal error iI Iile not exists. requireonce() does the same as includeonce(), but it calls a Iatal
error iI Iile not exists.

Anwser 4:
File will not be included more than once. II we want to include a Iile once only and Iurther
calling oI the Iile will be ignored then we have to use the PHP Iunction includeonce(). This will
prevent problems with Iunction redeIinitions, variable value reassignments, etc.
What is meant by urlencode and urldecode?
Anwser 1:
urlencode() returns the URL encoded version oI the given string. URL coding converts special
characters into signs Iollowed by two hex digits. For example: urlencode("10.00") will
return "102E0025". URL encoded strings are saIe to be used as part oI URLs.
urldecode() returns the URL decoded version oI the given string.
Anwser 2:
string urlencode(str) - Returns the URL encoded version oI 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 "" Iollowed by two hex digits representing
the converted character.

string urldecode(str) - Returns the original string oI 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?disc102E0025".
How To Get the Uploaded File Information in the Receiving Script?

Once the Web server received the uploaded Iile, it will call the PHP script speciIied in the Iorm
action attribute to process them. This receiving PHP script can get the uploaded Iile inIormation
through the predeIined array called $FILES. Uploaded Iile inIormation is organized in $FILES
as a two-dimensional array as:
$FILES|$IieldName||'name'| - The Original Iile name on the browser system.
$FILES|$IieldName||'type'| - The Iile type determined by the browser.
$FILES|$IieldName||'size'| - The Number oI bytes oI the Iile content.
$FILES|$IieldName||'tmpname'| - The temporary Iilename oI the Iile in which the uploaded
Iile was stored on the server.
$FILES|$IieldName||'error'| - The error code associated with this Iile upload.

The $IieldName is the name used in the INPUT TYPEFILE, NAMEIieldName~.
What is the difference between mysql_fetch_object and mysql_fetch_array?
MySQL Ietch object will collect Iirst single matching record where mysqlIetcharray will
collect all matching records Irom the table in an array
How can I execute a PHP script using command line?
Just run the PHP CLI (Command Line InterIace) program and provide the PHP script Iile name
as the command line argument. For example, "php myScript.php", assuming "php" is the
command to invoke the CLI program.
Be aware that iI your PHP script was written Ior the Web CGI interIace, 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 Ior 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 itselI, but iI you were to print
something like "$a},000,000 mln dollars", then you deIinitely 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 oI tables we can create
1. MyISAM
2. Heap
3. Merge
4. INNO DB
5. ISAM
MyISAM is the deIault storage engine as oI MySQL 3.23. When you Iire the above create query
MySQL will create a MyISAM table.
How To Create a Table?
II you want to create a table, you can run the CREATE TABLE statement as shown in the
Iollowing sample script:

?php
include "mysqlconnection.php";

$sql "CREATE TABLE Techlinks ("
. " id INTEGER NOT NULL"
. ", url VARCHAR(80) NOT NULL"
. ", notes VARCHAR(1024)"
. ", counts INTEGER"
. ", time TIMESTAMP DEFAULT sysdate()"
. ")";
iI (mysqlquery($sql, $con))
print("Table Techlinks created.\n");
} else
print("Table creation Iailed.\n");
}

mysqlclose($con);
?~

Remember that mysqlquery() returns TRUE/FALSE on CREATE statements. II you run this
script, you will get something like this:
Table Techlinks created.
How can we encrypt the username and password using PHP?
Answer1
You can encrypt a password with the Iollowing Mysql~SET
PASSWORDPASSWORD("Password");

Answer2
You can use the MySQL PASSWORD() Iunction 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 Iront oI it, like $a &$b
What is the functionality of the functions STRSTR() and STRISTR()?
string strstr ( string haystack, string needle ) returns part oI haystack string Irom the Iirst
occurrence oI needle to the end oI haystack. This Iunction is case-sensitive.

stristr() is idential to strstr() except that it is case insensitive.
When are you supposed to use endif to end the conditional statement?
When the original iI was Iollowed by : and then the code block without braces.
How can we send mail using 1avaScript?
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:

Iunction myIunction(Iorm)

tdatadocument.myIorm.tbox1.value;
location"mailto:mailiddomain.com?subject...";
return true;
}
What is the functionality of the function strstr and stristr?
strstr() returns part oI a given string Irom the Iirst occurrence oI a given substring to the end oI
the string. For example: strstr("userexample.com","") will return "example.com".
stristr() is idential to strstr() except that it is case insensitive.
What is the difference between ereg_replace() and eregi_replace()?
eregireplace() Iunction is identical to eregreplace() except that it ignores case distinction when
matching alphabetic characters.
How do I find out the number of parameters passed into function9. ?
Iuncnumargs() Iunction returns the number oI parameters passed in.
What is the purpose of the following files having extensions: frm, myd, and myi? What
these files contain?
In MySQL, the deIault table type is MyISAM.
Each MyISAM table is stored on disk in three Iiles. The Iiles have names that begin with the
table name and have an extension to indicate the Iile type.

The '.Irm' Iile stores the table deIinition.
The data Iile has a '.MYD' (MYData) extension.
The index Iile 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?
100, it`s a reIerence to existing variable.
How To Protect Special Characters in Query String?
II you want to include special characters like spaces in the query string, you need to protect them
by applying the urlencode() translation Iunction. 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 hreI\"processingIorms.php?nameGuest&comment$comment\"~"
."It's an excellent site!/a~/p~");
$comment 'This visitor said: "It\'s an average site! :-("';
$comment urlencode($comment);
print("p~"
.'a hreI"processingIorms.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 tablename - This will delete the table and its data.

TRUNCATE TABLE tablename - This will delete the data oI the table, but not the table
deIinition.
How do you call a constructor for a parent class?
parent::constructor($value)
WHAT ARE THE DIFFERENT TYPES OF ERRORS IN PHP?
Here are three basic types oI runtime errors in PHP:

1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script - Ior
example, accessing a variable that has not yet been deIined. By deIault, such errors are not
displayed to the user at all - although you can change this deIault behavior.

2. Warnings: These are more serious errors - Ior example, attempting to include() a Iile which
does not exist. By deIault, these errors are displayed to the user, but they do not result in script
termination.

3. Fatal errors: These are critical errors - Ior example, instantiating an object oI a non-existent
class, or calling a non-existent Iunction. These errors cause the immediate termination oI the
script, and PHP's deIault behavior is to display them to the user when they take place.

Internally, these variations are represented by twelve diIIerent error types
What`s the special meaning of __sleep and __wakeup?
sleep returns the array oI all the variables than need to be saved, while wakeup retrieves
them.
How can we submit a form without a submit button?
II you don't want to use the Submit button to submit a Iorm, you can use normal hyper links to
submit a Iorm. But you need to use some JavaScript code in the URL oI the link. For example:

a hreI"javascript: document.myIorm.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
oI 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 Ior variable substitution, it`s always a
better idea speed-wise to initialize a string with single quotes, unless you speciIically need
variable substitution.
How can we extract string 'abc.com ' from a string http://infoabc.com using regular
expression of php?
We can use the pregmatch() Iunction with "/.*(.*)$/" as
the regular expression pattern. For example:
pregmatch("/.*(.*)$/","http://inIoabc.com",$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?
Anwser 1:

When we submit a Iorm, which has the GET method it displays pair oI name/value used in the
Iorm at the address bar oI 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 Ior long data sending, say more then 100 character you can use POST
method.

Once most important diIIerence is when you are sending the Iorm with GET method. You can
see the output which you are sending in the address bar. Whereas iI you send the Iorm with
POST method then user can not see that inIormation.

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 DiIIerence

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 Iorm 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 Iorm 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 oI GET method is limited
(they say Internet Explorer can take care oI maximum 2083 character as a query string).

Anwser 4:

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

Anwser 5:

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

Anwser 6:

On the server side, the main diIIerence 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 diIIerence is that data submitted by the GET method will be displayed
in the browser`s address Iield. Data submitted by the POST method will not be displayed
anywhere on the browser.
GET method is mostly used Ior submitting a small amount and less sensitive data. POST method
is mostly used Ior submitting a large amount or sensitive data.
What is the difference between the functions unlink and unset?
unlink() is a Iunction Ior Iile system handling. It will simply delete the Iile in context.

unset() is a Iunction Ior variable management. It will make a variable undeIined.
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?
sessionregister($sessionvar);

$SESSION|'var'| 'value';
What is the difference between characters \023 and \x23?
The Iirst 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 oI any Iorm Iield. In the
JavaScript code, we can call the document.Iorm.submit() Iunction to submit the Iorm. For
example: input typebutton value"Save" onClick"document.Iorm.submit()"~
How can we create a database using PHP and mysql?
We can create MySQL database with the use oI mysqlcreatedb($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 oI them, and just outputs the contents Iollowing the construct to the
screen. print is also a construct (so parentheses are optional when calling it), but it returns TRUE
on successIul output and FALSE iI 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 Iaster, but usually the speed advantage is
negligible, and might not be there Ior Iuture versions oI PHP. printI is a Iunction, not a construct,
and allows such advantages as Iormatted output, but it`s the slowest way to print out data out oI
echo, print and printI.
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 Iormatted according to some length speciIications, use
wordwrap() or chunksplit().
What`s the output of the ucwords function in this example?
$Iormatted ucwords("TECHPREPARATIONS IS COLLECTION OF INTERVIEW
QUESTIONS");
print $Iormatted;
What will be printed is TECHPREPARATIONS IS COLLECTION OF INTERVIEW
QUESTIONS.
ucwords() makes every Iirst letter oI every word capital, but it does not lower-case anything else.
To avoid this, and get a properly Iormatted string, it`s worth using strtolower() Iirst.
What`s the difference between htmlentities() and htmlspecialchars()?
htmlspecialchars only takes care oI , ~, single quote , double quote " and ampersand.
htmlentities translates all occurrences oI character sequences that have diIIerent meaning in
HTML.
How can we extract string "abc.com" from a string
"mailto:infoabc.com?subjectFeedback" using regular expression of PHP?
$text "mailto:inIoabc.com?subjectFeedback";
pregmatch(',.*(|`?|*),', $text, $output);
echo $output|1|;

Note that the second index oI $output, $output|1|, gives the match, not the Iirst 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 Iree. First oII, depending on the data
that you`re encrypting, you might have reasons to store a 32-bit value in the database instead oI
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 signiIicantly slowed
down, iI Irequent md5() generation is required.
How can we destroy the session, how can we unset the variable of a session?
sessionunregister() - Unregister a global variable Irom the current session
sessionunset() - Free all session variables
What are the different functions in sorting an array?
Sorting Iunctions 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) sizeoI($array) - This Iunction is an alias oI count()
b) count($urarray) - This Iunction returns the number oI elements in an array.
Interestingly iI you just pass a simple var instead oI 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 Iirst page, and get it back Irom session in the next page.
2. Put the variable into cookie in the Iirst page, and get it back Irom the cookie in the next page.
3. Put the variable into a hidden Iorm Iield, and get it back Irom the Iorm in the next page.
What is the maximum length of a table name, a database name, or a field name in MySQL?
Database name: 64 characters
Table name: 64 characters
Column name: 64 characters
How many values can the SET function of MySQL take?
MySQL SET Iunction 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 tablename;
How can we find the number of rows in a table using MySQL?
Use this Ior MySQL

SELECT COUNT(*) FROM tablename;
What`s the difference between md5(), crc32() and sha1() crypto on PHP?
The major diIIerence is the length oI 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 Iind the number oI rows in a result set in PHP:

$result mysqlquery($anyvalidsql, $databaselink);
$numrows mysqlnumrows($result);
echo "$numrows rows Iound";
How many ways we can we find the current date using MySQL?
SELECT CURDATE();
SELECT CURRENTDATE();
SELECT CURTIME();
SELECT CURRENTTIME();
Give the syntax of GRANT commands?
The generic syntax Ior GRANT is as Iollowing

GRANT |rights| on |database| TO |usernamehostname| IDENTIFIED BY |password|

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

We can grant rights on all databse by usingh *.* or some speciIic database by database.* or a
speciIic table by database.tablename.
Give the syntax of REVOKE commands?
The generic syntax Ior revoke is as Iollowing

REVOKE |rights| on |database| FROM |usernamehostname|

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

We can grant rights on all database by using *.* or some speciIic database by database.* or a
speciIic table by database.tablename.
What is the difference between CHAR and VARCHAR data types?
CHAR is a Iixed length data type. CHAR(n) will take n characters oI storage even iI 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 Ior
the actual number oI 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?
AESENCRYPT() and AESDECRYPT()
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 oI 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 Irom a Iile. Great
tool but you need to make sure that:

a) Data must be delimited
b) Data Iields must match table columns correctly
How can we know the number of days between two given dates using MySQL?
Use DATEDIFF()

SELECT DATEDIFF(NOW(),'2006-07-01');
How can we change the name of a column of a table?
This will change the name oI column:

ALTER TABLE tablename CHANGE oldcolmname newcolmname
How can we change the data type of a column of a table?
This will change the data type oI a column:

ALTER TABLE tablename CHANGE colmname samecolmname |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 satisIy a GROUP BY clause is to scan the whole table and create a new
temporary table where all rows Irom each group are consecutive, and then use this temporary
table to discover groups and apply aggregate Iunctions (iI any).
ORDER BY |col1|,|col2|,...|coln|; Tells DBMS according to what columns it should sort the
result. II 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 oI
column col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, iI 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 Ior the Iormat oI e-mail.
However browsers also uses MIME standard to transmit Iiles. MIME has a header which is
added to a beginning oI the data. When browser sees such header it shows the data as it would be
a Iile (Ior example image)
Some examples oI MIME types:
audio/x-ms-wmp
image/png
application/x-shockwave-Ilash

Answer 2:
Multipurpose Internet Mail Extensions.
WWW's ability to recognize and handle Iiles oI diIIerent types is largely dependent on the use oI
the MIME (Multipurpose Internet Mail Extensions) standard. The standard provides Ior a system
oI registration oI Iile types with inIormation about the applications needed to process them. This
inIormation is incorporated into Web server and browser soItware, and enables the automatic
recognition and display oI registered Iile types. .
How can we know that a session is started or not?
A session starts by sessionstart() Iunction.
This sessionstart() is always declared in header portion. it always declares Iirst. then we write
sessionregister().
What are the differences between mysql_fetch_array(), mysql_fetch_object(),
mysql_fetch_row()?
Answer 1:
mysqlIetcharray() -~ Fetch a result row as a combination oI associative array and regular
array.
mysqlIetchobject() -~ Fetch a result row as an object.
mysqlIetchrow() -~ Fetch a result set as a regular array().

Answer 2:
The diIIerence between mysqlIetchrow() and mysqlIetcharray() is that the Iirst 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.).
mysqlIetchobject() 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. II browser is closed then session is lost. The session data will be
deleted aIter session time out. II 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.Irm
Index is stored in name.myi
What is the difference between PHP4 and PHP5?
PHP4 cannot support oops concepts and Zend engine 1 is used.

PHP5 supports oops concepts and Zend engine 2 is used.
Error supporting is increased in PHP5.
XML and SQLLite will is increased in PHP5.
Can we use include(abc.PHP) two times in a PHP page makeit.PHP?
Yes we can include that many times we want, but here are some things to make sure oI:
(including abc.PHP, the Iile names are case-sensitive)
there shouldn't be any duplicate Iunction names, means there should not be Iunctions or classes
or variables with the same name in abc.PHP and makeit.php
What are the differences between mysql_fetch_array(), mysql_fetch_object(),
mysql_fetch_row()?
mysqlIetcharray - Fetch a result row as an associative array and a numeric array.

mysqlIetchobject - Returns an object with properties that correspond to the Ietched row and
moves the internal data pointer ahead. Returns an object with properties that correspond to the
Ietched row, or FALSE iI there are no more rows

mysqlIetchrow() - Fetches one row oI data Irom the result associated with the speciIied result
identiIier. The row is returned as an array. Each result column is stored in an array oIIset, starting
at oIIset 0.
What is meant by nl2br()?
Anwser1:
nl2br() inserts a HTML tag br~ beIore all new line characters \n in a string.

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

output:
god blessbr~
you
How can we encrypt and decrypt a data presented in a table using MySQL?
You can use Iunctions: AESENCRYPT() and AESDECRYPT() like:

AESENCRYPT(str, keystr)
AESDECRYPT(cryptstr, keystr)
How can I retrieve values from one database server and store them in other database
server using PHP?
For this purpose, you can Iirst read the data Irom 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 LerdorI.
PHP 5.1. Beta
MySQL 5.0
In how many ways we can retrieve data in the result set of MYSQL using PHP?
mysqlIetcharray - Fetch a result row as an associative array, a numeric array, or both
mysqlIetchassoc - Fetch a result row as an associative array
mysqlIetchobject - Fetch a result row as an object
mysqlIetchrow - Get a result row as an enumerated array
What are the functions for IMAP?
imapbody - Read the message body
imapcheck - Check current mailbox
imapdelete - Mark a message Ior deletion Irom current mailbox
imapmail - Send an email message
What are encryption functions in PHP?
CRYPT()
MD5()
What is the difference between htmlentities() and htmlspecialchars()?
htmlspecialchars() - Convert some special characters to HTML entities (Only the most widely
used)
htmlentities() - Convert ALL special characters to HTML entities
What is the functionality of the function htmlentities?
htmlentities() - Convert all applicable characters to HTML entities
This Iunction 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() Iunction
To know the image width use imagesx() Iunction
To know the image height use imagesy() Iunction
How can we increase the execution time of a php script?
By the use oI void settimelimit(int seconds)
Set the number oI seconds a script is allowed to run. II this is reached, the script returns a Iatal
error. The deIault limit is 30 seconds or, iI it exists, the maxexecutiontime value deIined in the
php.ini. II seconds is set to zero, no time limit is imposed.

When called, settimelimit() restarts the timeout counter Irom zero. In other words, iI the
timeout is the deIault 30 seconds, and 25 seconds into script execution a call such as
settimelimit(20) is made, the script will run Ior a total oI 45 seconds beIore timing out.
HOW CAN WE TAKE A BACKUP OF A MYSQL TABLE AND HOW CAN WE
RESTORE IT?
Answer 1:
Create a Iull backup oI your database: shell~ mysqldump tab/path/to/some/dir opt dbname
Or: shell~ mysqlhotcopy dbname /path/to/some/dir
The Iull backup Iile is just a set oI SQL statements, so restoring it is very easy:

shell~ mysql "."Executed";

Answer 2:
To backup: BACKUP TABLE tblname TO /path/to/backup/directory
` To restore: RESTORE TABLE tblname FROM /path/to/backup/directory

mysqldump: Dumping Table Structure and Data

Utility to dump a database or a collection oI database Ior backup or Ior transIerring 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-inIo
Don't write table creation inIormation (the CREATE TABLE statement).
-d, no-data
Don't write any row inIormation Ior the table. This is very useIul iI you just want to get a dump
oI the structure Ior a table!
How to set cookies?
setcookie('variable','value','time')
;
variable - name oI the cookie variable
value - value oI the cookie variable
time - expiry time
Example: setcookie('Test',$i,time()3600);

Test - cookie variable name
$i - value oI the variable 'Test'
time()3600 - denotes that the cookie will expire aIter an one hour
How to reset/destroy a cookie ?
Reset a cookie by speciIying expire time in the past:
Example: setcookie('Test',$i,time()-3600); // already expired time

Reset a cookie by speciIying its name only
Example: setcookie('Test');
What types of images that PHP supports ?
Using imagetypes() Iunction to Iind out what types oI images are supported in your PHP engine.
imagetypes() - Returns the image types supported.
This Iunction returns a bit-Iield corresponding to the image Iormats supported by the version oI
GD linked into PHP. The Iollowing bits are returned, IMGGIF , IMGJPG , IMGPNG ,
IMGWBMP , IMGXPM.
Check if a variable is an integer in 1AVASCRIPT ?
var myValue 9.8;
iI(parseInt(myValue) myValue)
alert('Integer');
else
alert('Not an integer');
Tools used for drawing ER diagrams.
Case Studio
Smart Draw
How can I know that a variable is a number or not using a 1avaScript?
Answer 1:
bool isnumeric( mixed var)
Returns TRUE iI var is a number or a numeric string, FALSE otherwise.

Answer 2:
DeIinition and Usage
The isNaN() Iunction is used to check iI a value is not a number.

Syntax
isNaN(number)

Parameter Description
number Required. The value to be tested
How can we submit from without a submit button?
Trigger the JavaScript code on any event ( like onSelect oI drop down list box, onIocus, etc )
document.myIorm.submit(); This will submit the Iorm.
How many ways can we get the value of current session id?
sessionid() returns the session id Ior the current session.
How can we destroy the cookie?
Set the cookie with a past expiration time.
What are the current versions of Apache, PHP, and MySQL?
PHP: PHP 5.1.2
MySQL: MySQL 5.1
Apache: Apache 2.1
What are the reasons for selecting LAMP (Linux, Apache, MySQL, Php) instead of
combination of other software programs, servers and operating systems?
All oI those are open source resource. Security oI Linux is very more than windows. Apache is a
better server that IIS both in Iunctionality and security. Mysql is world most popular open source
database. Php is more Iaster that asp or any other scripting language.
What are the features and advantages of OB1ECT ORIENTED PROGRAMMING?
One oI the main advantages oI OO programming is its ease oI modiIication; objects can easily be
modiIied 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 Ior
more complicated and Ilexible interactions. OO systems are also easier Ior non-technical
personnel to understand and easier Ior them to participate in the maintenance and enhancement
oI 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 modiIied Ior a speciIic system.
How can we get second of the current time using date function?
$second date("s");
What is the use of friend function?
Friend Iunctions
Sometimes a Iunction is best shared among a number oI diIIerent classes. Such Iunctions can be
declared either as member Iunctions oI one class or as global Iunctions. In either case they can be
set to be Iriends oI other classes, by using a Iriend speciIier in the class that is admitting them.
Such Iunctions can use all attributes oI the class which names them as a Iriend, as iI they were
themselves members oI that class.
A Iriend declaration is essentially a prototype Ior a member Iunction, but instead oI requiring an
implementation with the name oI that class attached by the double colon syntax, a global
Iunction or member Iunction oI another class provides the match.
class mylinkage

private:
mylinkage * prev;
mylinkage * next;

protected:
Iriend void setprev(mylinkage* L, mylinkage* N);
void setnext(mylinkage* L);

public:
mylinkage * succ();
mylinkage * pred();
mylinkage();
};

void mylinkage::setnext(mylinkage* L) next L; }

void setprev(mylinkage * L, mylinkage * N ) N-~prev L; }

Friends in other classes
It is possible to speciIy a member Iunction oI another class as a Iriend as Iollows:
class C

Iriend int B::I1();
};
class B

int I1();
};

It is also possible to speciIy all the Iunctions in another class as Iriends, by speciIying the entire
class as a Iriend.
class A

Iriend class B;
};

Friend Iunctions allow binary operators to be deIined which combine private data in a pair oI
objects. This is particularly powerIul when using the operator overloading Ieatures oI 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 oI a Iile set uploadmaxIilesize variable in php.ini Iile
How can I make a script that can be bilingual (supports English, German)?
You can change char set variable in above line in the script to support bi language.
What are the difference between abstract class and interface?
Abstract class: abstract classes are the class where one or more methods are abstract but not
necessarily all method has to be abstract. Abstract methods are the methods, which are declare in
its class but not deIine. The deIinition oI those methods must be in its extending class.

InterIace: InterIaces are one type oI class where all the methods are abstract. That means all the
methods only declared but not deIined. All the methods must be deIine by its implemented class.
What are the advantages of stored procedures, triggers, indexes?
A stored procedure is a set oI 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 reIer to the
stored procedure. This provides better overall perIormance because the query has to be parsed
only once, and less inIormation needs to be sent between the server and the client. You can also
raise the conceptual level by having libraries oI Iunctions in the server. However, stored
procedures oI course do increase the load on the database server system, as more oI the work is
done on the server side and less on the client (application) side. Triggers will also be
implemented. A trigger is eIIectively a type oI 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 Irom a transaction table and that stored procedure automatically deletes
the corresponding customer Irom a customer table when all his transactions are deleted. Indexes
are used to Iind rows with speciIic column values quickly. Without an index, MySQL must begin
with the Iirst row and then read through the entire table to Iind the relevant rows. The larger the
table, the more this costs. II the table has an index Ior the columns in question, MySQL can
quickly determine the position to seek to in the middle oI the data Iile without having to look at
all the data. II a table has 1,000 rows, this is at least 100 times Iaster than reading sequentially. II
you need to access most oI the rows, it is Iaster to read sequentially, because this minimizes disk
seeks.
What is maximum size of a database in mysql?
II the operating system or Iilesystem places a limit on the number oI Iiles in a directory, MySQL
is bound by that constraint. The eIIiciency oI the operating system in handling large numbers oI
Iiles in a directory can place a practical limit on the number oI tables in a database. II the time
required to open a Iile in the directory increases signiIicantly as the number oI Iiles increases,
database perIormance can be adversely aIIected.
The amount oI available disk space limits the number oI 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 eIIective table size Ior MySQL databases is usually
determined by operating system constraints on Iile sizes, not by MySQL internal limits.
The InnoDB storage engine maintains InnoDB tables within a tablespace that can be created
Irom several Iiles. This allows a table to exceed the maximum individual Iile size. The
tablespace can include raw disk partitions, which allows extremely large tables. The maximum
tablespace size is 64TB.
The Iollowing table lists some examples oI operating system Iile-size limits. This is only a rough
guide and is not intended to be deIinitive. For the most up-to-date inIormation, be sure to check
the documentation speciIic to your operating system.
Operating System File-size Limit
Linux 2.2-Intel 32-bit 2GB (LFS: 4GB)
Linux 2.4 (using ext3 Iilesystem) 4TB
Solaris 9/10 16TB
NetWare w/NSS Iilesystem 8TB
Win32 w/ FAT/FAT32 2GB/4GB
Win32 w/ NTFS 2TB (possibly larger)
MacOS X w/ HFS 2TB
Explain normalization concept?
The normalization process involves getting our data to conIorm to three progressive normal
Iorms, and a higher level oI normalization cannot be achieved until the previous levels have been
achieved (there are actually Iive normal Iorms, but the last two are mainly academic and will not
be discussed).

First Normal Form
The First Normal Form (or 1NF) involves removal oI redundant data Irom horizontal rows. We
want to ensure that there is no duplication oI data in a given row, and that every column stores
the least amount oI inIormation possible (making the Iield atomic).

Second Normal Form
Where the First Normal Form deals with redundancy oI data across a horizontal row, Second
Normal Form (or 2NF) deals with redundancy oI data in vertical columns. As stated earlier, the
normal Iorms are progressive, so to achieve Second Normal Form, your tables must already be in
First Normal Form.

Third Normal Form
I have a conIession to make; I do not oIten use Third Normal Form. In Third Normal Form we
are looking Ior data in our tables that is not Iully dependant on the primary key, but dependant on
another value in the table
What`s the difference between accessing a class method via -> and via ::?
:: is allowed to access methods that can perIorm static operations, i.e. those, which do not require
object initialization.
What are the advantages and disadvantages of CASCADE STYLE SHEETS?
External Style Sheets
Advantages
Can control styles Ior multiple documents at once Classes can be created Ior 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 inIormation Ior each document The rendering oI
the document may be delayed until the external style sheet is loaded Becomes slightly unwieldy
Ior small quantities oI style deIinitions

Embedded Style Sheets
Advantages
Classes can be created Ior 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 inIormation

Disadvantage
This method can not control styles Ior multiple documents at once

Inline Styles
Advantages
UseIul Ior small quantities oI style deIinitions Can override other style speciIication methods at
the local level so only exceptions need to be listed in conjunction with other style methods

Disadvantages
Does not distance style inIormation Irom content (a main goal oI SGML/HTML) Can not control
styles Ior multiple documents at once Author can not create or control classes oI elements to
control multiple element types within the document Selector grouping methods can not be used
to create complex element addressing scenarios
What type of inheritance that php supports?
In PHP an extended class is always dependent on a single base class, that is, multiple inheritance
is not supported. Classes are extended using the keyword 'extends'.
How can increase the performance of MySQL select query?
We can use LIMIT to stop MySql Ior Iurther search in table aIter we have received our required
no. oI records, also we can use LEFT JOIN or RIGHT JOIN instead oI Iull 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 tblname TO newtblname
or,
ALTER TABLE tableName CHANGE OldName newName.
When you want to show some part of a text displayed on an HTML page in red font color?
What different possibilities are there to do this? What are the advantages/disadvantages of
these methods?
There are 2 ways to show some part oI a text in red:

1. Using HTML tag Iont 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 oI an HTML Web page, the
Web page may still be cached in the Temporary Internet Files Iolder.

A page that Internet Explorer is browsing is not cached until halI oI the 64 KB buIIer is Iilled.
Usually, metatags are inserted in the header section oI an HTML document, which appears at the
beginning oI the document. When the HTML code is parsed, it is read Irom top to bottom. When
the metatag is read, Internet Explorer looks Ior the existence oI the page in cache at that exact
moment. II it is there, it is removed. To properly prevent the Web page Irom appearing in the
cache, place another header section at the end oI 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 iI 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: /hreI"(|`"|*)"/i
How can I use the COM components in php?
The COM class provides a Iramework to integrate (D)COM components into your PHP scripts.
string COM::COM( string modulename |, string servername |, int codepage||) - COM class
constructor.

Parameters:

modulename: name or class-id oI the requested component.
servername: name oI the DCOM server Irom which the component should be Ietched. II NULL,
localhost is assumed. To allow DCOM com, allowdcom has to be set to TRUE in php.ini.
codepage - speciIies the codepage that is used to convert php-strings to unicode-strings and vice
versa. Possible values are CPACP, CPMACCP, CPOEMCP, CPSYMBOL,
CPTHREADACP, CPUTF7 and CPUTF8.
Usage:
$word-~Visible 1; //open an empty document
$word-~Documents-~Add(); //do some weird stuII
$word-~Selection-~TypeText("This is a test.");
$word-~Documents|1|-~SaveAs("Useless test.doc"); //closing word
$word-~Quit(); //Iree 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
DiIIerent Type oI embedded Package to output to a browser
What is the default session time in php and how can I change it?
The deIault session time in php is until closing oI browser
What changes I have to do in php.ini file for file uploading?
Make the Iollowing line uncomment like:
; Whether to allow HTTP Iile uploads.
Iileuploads On
; Temporary directory Ior HTTP uploaded Iiles (will use system deIault iI not
; speciIied).
uploadtmpdir C:\apache2triad\temp
; Maximum allowed size Ior uploaded Iiles.
uploadmaxIilesize 2M
How can I set a cron and how can I execute it in Unix, Linux, and windows?
Cron is very simply a Linux module that allows you to run commands at predetermined times or
intervals. In Windows, it's called Scheduled Tasks. The name Cron is in Iact derived Irom the
same word Irom which we get the word chronology, which means order oI time.
The easiest way to use crontab is via the crontab command.

# crontab

This command 'edits' the crontab. Upon employing this command, you will be able to enter the
commands that you wish to run. My version oI
Linux uses the text editor vi. You can Iind inIormation on using vi here.

The syntax oI this Iile is very important iI you get it wrong, your crontab will not Iunction
properly. The syntax oI the Iile should be as Iollows:
minutes hours dayoImonth month dayoIweek command

All the variables, with the exception oI the command itselI, are numerical constants. In addition
to an asterisk (*), which is a wildcard that allows any value, the ranges permitted Ior each Iield
are as Iollows:

Minutes: 0-59
Hours: 0-23
DayoImonth: 1-31
Month: 1-12
Weekday: 0-6

We can also include multiple values Ior 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 Iile.
So, iI we want to run a script every Tuesday morning at 8:15 AM, our mycronjob Iile will
contain the Iollowing content on a single line:

15 8 * * 2 /path/to/scriptname

This all seems simple enough, right? Not so Iast! II you try to run a PHP script in this manner,
nothing will happen (barring very special conIigurations that have PHP compiled as an
executable, as opposed to an Apache module). The reason is that, in order Ior 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 oI retrieving

Web content. For our purposes, I'll assume that your server conIiguration includes wget, as is the
case with most deIault conIigurations. To test your conIiguration, log in to shell. II you're using
an RPM-based system (e.g. Redhat or Mandrake), type the Iollowing:

# wget help

II you are greeted with a wget package identiIication, 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/Iile.php

Now, let's go back to the mailstock.php Iile we created in the Iirst part oI 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 iI you live elsewhere,
you might have to compensate Ior the time diIIerence 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.php
Steps for the payment gateway processing?
An online payment gateway is the interIace between your merchant account and your Web site.
The online payment gateway allows you to immediately veriIy credit card transactions and
authorize Iunds on a customer's credit card directly Irom your Web site. It then passes the
transaction oII to your merchant bank Ior processing, commonly reIerred to as transaction
batching
How many ways I can redirect a PHP page?
Here are the possible ways oI php page redirection.

1. Using Java script:
'; echo 'window.location.hreI"'.$Iilename.'";'; echo ''; echo ''; echo ''; echo ''; } }
redirect('http://maosjb.com'); ?~

2. Using php Iunction: header("Location:http://maosjb.com ");
List out different arguments in PHP header function?
void header ( string string |, bool replace |, int httpresponsecode||)
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 oI the mail.

Return-path: Return path is when there is a mail delivery Iailure occurs then where to delivery
the Iailure notiIication.
How to store the uploaded file to the final location?
moveuploadedIile ( string Iilename, string destination)

This Iunction checks to ensure that the Iile designated by Iilename is a valid upload Iile (meaning
that it was uploaded via PHP's HTTP POST upload mechanism). II the Iile is valid, it will be
moved to the Iilename given by destination.

II Iilename is not a valid upload Iile, then no action will occur, and moveuploadedIile() will
return FALSE.

II Iilename is a valid upload Iile, but cannot be moved Ior some reason, no action will occur, and
moveuploadedIile() will return FALSE. Additionally, a warning will be issued.
Explain about Type 1uggling in php?
PHP does not require (or support) explicit type deIinition in variable declaration; a variable's
type is determined by the context in which that variable is used. That is to say, iI you assign a
string value to variable $var, $var becomes a string. II you then assign an integer value to $var, it
becomes an integer.

An example oI PHP's automatic type conversion is the addition operator ''. II any oI the
operands is a Iloat, then all operands are evaluated as Iloats, and the result will be a Iloat.
Otherwise, the operands will be interpreted as integers, and the result will also be an integer.
Note that this does NOT change the types oI the operands themselves; the only change is in how
the operands are evaluated.

$Ioo 2; // $Ioo is now an integer (2)
$Ioo $Ioo 1.3; // $Ioo is now a Iloat (3.3)
$Ioo 5 "10 Little Piggies"; // $Ioo is integer (15)
$Ioo 5 "10 Small Pigs"; // $Ioo is integer (15)

II the last two examples above seem odd, see String conversion to numbers.
II you wish to change the type oI a variable, see settype().
II you would like to test any oI the examples in this section, you can use the vardump()
Iunction.
Note: The behavior oI an automatic conversion to array is currently undeIined.

Since PHP (Ior historical reasons) supports indexing into strings via oIIsets using the same
syntax as array indexing, the example above leads to a problem: should $a become an array with
its Iirst element being "I", or should "I" become the Iirst character oI the string $a? The current
versions oI PHP interpret the second assignment as a string oIIset identiIication, so $a becomes
"I", the result oI this automatic conversion however should be considered undeIined. PHP 4
introduced the new curly bracket syntax to access characters in string, use this syntax instead oI
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 eIIicient solution, or integrate Java support
into PHP. The Iormer is provided by a SAPI module that interIaces with the Servlet server, the
latter by this Java extension.
The Java extension provides a simple and eIIective means Ior creating and invoking methods on
Java objects Irom PHP. The JVM is created using JNI, and everything runs in-process.

Example Code:

getProperty('java.version') . ''; echo 'Java vendor' . $system-~getProperty('java.vendor') . ''; echo
'OS' . $system-~getProperty('os.name') . ' ' . $system-~getProperty('os.version') . ' on ' .
$system-~getProperty('os.arch') . ' '; // java.util.Date example $Iormatter new
Java('java.text.SimpleDateFormat', "EEEE, MMMM dd, yyyy 'at' h:mm:ss a zzzz"); echo
$Iormatter-~Iormat(new Java('java.util.Date')); ?~

The behaviour oI these Iunctions is aIIected by settings in php.ini.
Table 1. Java conIiguration options
Name
DeIault
Changeable
java.class.path
NULL
PHPINIALL
Name DeIault Changeable
java.home
NULL
PHPINIALL
java.library.path
NULL
PHPINIALL
java.library
JAVALIB
PHPINIALL
Explain the ternary conditional operator in PHP?
Expression preceding the ? is evaluated, iI it`s true, then the expression preceding the : is
executed, otherwise, the expression Iollowing : is executed.
What`s the difference between include and require?
It`s how they handle Iailures. II the Iile is not Iound by require(), it will cause a Iatal error and
halt the execution oI the script. II the Iile is not Iound by include(), a warning will be issued, but
execution will continue.
How many ways can we get the value of current session id?
sessionid() returns the session id Ior the current session.
Questions : 1 Who is the father of PHP ? nswers : 1 Rasmus LerdorI is known as the Iather oI
PHP. Questions : 2 What is the difference between $name and $$name?
Answers : 2 $name is variable where as $$name is reIerence variable
like $namesonia and $$namesingh so $sonia value is singh. Questions : 3 How can we
submit a form without a submit button? Answer : 3 Java script submit() Iunction is used Ior
submit Iorm without submit button
on click call document.Iormname.submit() Questions : 4 In how many ways we can retrieve
the data in the result set of
MySQL using PHP? Answer : 4 We can do it by 4 Ways
1. mysqlIetchrow. , 2. mysqlIetcharray , 3. mysqlIetchobject
4. mysqlIetchassoc Questions : 5 What is the difference between mysql_fetch_object
and
mysql_fetch_array? Answers : 5 mysql_fetch_object() is similar tomysql_fetch_array(), with
one diIIerence -
an object is returned, instead oI an array. Indirectly, that means that
you can only access the data by the Iield names, and not by their
oIIsets (numbers are illegal property names). Questions : 6 What are the differences
between Get and post methods. Answers : 6
There are some deIIerence between GET and POST method
1. GET Method have some limit like only 2Kb data able to send Ior request
But in POST method unlimited data can we send
2. when we use GET method requested data show in url but
Not in POST method so POST method is good Ior send sensetive request
Questions : 7 How can we extract string "pcds.co.in " from a string
"http://infopcds.co.in
using regular expression of PHP? Answers : 7
pregmatch("/`http:\/\/.(.)$/","http://inIopcds.co.in",$matches);
echo $matches|1|; Questions : 8 How can we create a database using PHP and MySQL?
Answers : 8 We can create MySQL database with the use oI
mysqlcreatedb("Database Name") Questions : 9 What are the differences between
require and include? Answers : 9 Both include and require used to include a Iile but when
included Iile not Iound
Include send Warning where as Require send Fatal Error .
Questions : 10 Can we use include ("xyz.PHP") two times in a PHP page "index.PHP"?
Answers : 10 Yes we can use include("xyz.php") more than one time in any page. but it create
a prob when xyz.php Iile contain some Iuntions declaration then error will come Ior already
declared Iunction in this Iile else not a prob like iI you want to show same content two time in
page then must incude it two time not a prob Questions : 11 What are the different
tables(Engine) present in MySQL, which one is default? Answers : 11 Following tables
(Storage Engine) we can create
1. MyISAM(The deIault storage engine IN MYSQL Each MyISAM table is stored on disk in
three Iiles. The Iiles have names that begin with the table name and have an extension to indicate
the Iile type. An .Irm Iile stores the table Iormat. The data Iile has an .MYD (MYData)
extension. The index Iile has an .MYI (MYIndex) extension. )
2. InnoDB(InnoDB is a transaction-saIe (ACID compliant) storage engine Ior MySQL that has
commit, rollback, and crash-recovery capabilities to protect user data.)
3. Merge
4. Heap (MEMORY)(The MEMORY storage engine creates tables with contents that are stored
in memory. Formerly, these were known as HEAP tables. MEMORY is the preIerred term,
although HEAP remains supported Ior backward compatibility. )
5. BDB (BerkeleyDB)(Sleepycat SoItware has provided MySQL with the Berkeley DB
transactional storage engine. This storage engine typically is called BDB Ior short. BDB tables
may have a greater chance oI surviving crashes and are also capable oI COMMIT and
ROLLBACK operations on transactions)
6. EXAMPLE
7. FEDERATED (It is a storage engine that accesses data in tables oI remote databases rather
than in local tables. )
8. ARCHIVE (The ARCHIVE storage engine is used Ior storing large amounts oI data without
indexes in a very small Iootprint. )
9. CSV (The CSV storage engine stores data in text Iiles using comma-separated values Iormat.)
10. BLACKHOLE (The BLACKHOLE storage engine acts as a "black hole" that accepts data
but throws it away and does not store it. Retrievals always return an empty result) Questions :
12 What is use of header() function in php ? Answers : 12 The header() Iunction sends a raw
HTTP header to a client.We can use herder()
Iunction Ior redirection oI pages. It is important to notice that header() must
be called beIore any actual output is seen.. Questions : 13 How can I execute a PHP script
using command line? Answers : 13 Just run the PHP CLI (Command Line InterIace) program
and
provide the PHP script Iile name as the command line argument. Questions : 14 Suppose
your Zend engine supports the mode <? ?> Then how can u
configure your PHP Zend engine to support <?PHP ?> mode ? Answers : 14 In php.ini Iile:
set
short_open_tagon
to make PHP support Questions : 15 Shopping cart online validation i.e. how can we
configure Paypal,
etc.? Answers : 15 Nothing more we have to do only redirect to the payPal url aIter
submit all inIormation needed by paypal like amount,adresss etc. Questions : 16 What is
meant by nl2br()? Answers : 16 Inserts HTML line breaks (BR /~) beIore all newlines in a
string. Questions : 17 What is htaccess? Why do we use this and Where? Answers : 17
.htaccess Iiles are conIiguration Iiles oI Apache Server which provide
a way to make conIiguration changes on a per-directory basis. A Iile,
containing one or more conIiguration directives, is placed in a particular
document directory, and the directives apply to that directory, and all
subdirectories thereoI. Questions : 18 How we get IP address of client, previous reference
page etc ? Answers : 18 By using
$SERVER|'REMOTEADDR'|,$SERVER|'HTTPREFERER'| etc. Questions : 19 What
are the reasons for selecting lamp (Linux, apache, MySQL,
PHP) instead of combination of other software programs, servers and
operating systems? Answers : 19 All oI those are open source resource. Security oI Linux is
very
very more than windows. Apache is a better server that IIS both in
Iunctionality and security. MySQL is world most popular open source
database. PHP is more Iaster that asp or any other scripting language. Questions : 20 How
can we encrypt and decrypt a data present in a MySQL table
using MySQL? Answers : 20 AESENCRYPT () and AESDECRYPT () Questions : 21
How can we encrypt the username and password using PHP? Answers : 21 The Iunctions in
this section perIorm encryption and decryption, and
compression and uncompression:
encryption decryption
AESENCRYT() AESDECRYPT()
ENCODE() DECODE()
DESENCRYPT() DESDECRYPT()
ENCRYPT() Not available
MD5() Not available
OLDPASSWORD() Not available
PASSWORD() Not available
SHA() or SHA1() Not available
Not available UNCOMPRESSEDLENGTH()
Questions : 22 What are the features and advantages of object-oriented
programming? Answers : 22 One oI the main advantages oI OO programming is its ease oI
modiIication; objects can easily be modiIied 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 Ior more complicated and Ilexible interactions. OO systems are
also easier Ior non-technical personnel to understand and easier Ior
them to participate in the maintenance and enhancement oI 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
modiIied Ior a speciIic system Questions : 23 What are the differences between procedure-
oriented languages and
object-oriented languages? Answers : 23 There are lot oI diIIerence between procedure
language and object oriented like below
1~Procedure language easy Ior new developer but complex to understand whole soItware as
compare to object oriented model
2~In Procedure language it is diIIicult to use design pattern mvc , Singleton pattern etc but in
OOP you we able to develop design pattern
3~IN OOP language we able to ree use code like Inheritance ,polymorphism etc but this type oI
thing not available in procedure language on that our Fonda use COPY and PASTE .
Questions : 24 What is the use of friend function? Answers : 24 Sometimes a Iunction is best
shared among a number oI diIIerent
classes. Such Iunctions can be declared either as member Iunctions oI
one class or as global Iunctions. In either case they can be set to be
Iriends oI other classes, by using a Iriend speciIier in the class that
is admitting them. Such Iunctions can use all attributes oI the class
which names them as a Iriend, as iI they were themselves members oI that
class.
A Iriend declaration is essentially a prototype Ior a member Iunction,
but instead oI requiring an implementation with the name oI that class
attached by the double colon syntax, a global Iunction or member
Iunction oI another class provides the match. Questions : 25 What are the differences
between public, private, protected,
static, transient, final and volatile? Answer : 25 Public: Public declared items can be accessed
everywhere.
Protected: Protected limits access to inherited and parent
classes (and to the class that deIines the item).
Private: Private limits visibility only to the class that deIines
the item.
Static: A static variable exists only in a local Iunction scope,
but it does not lose its value when program execution leaves this scope.
Final: Final keyword prevents child classes Irom overriding a
method by preIixing the deIinition with Iinal. II the class itselI is
being deIined Iinal then it cannot be extended.
transient: A transient variable is a variable that may not
be serialized.
volatile: a variable that might be concurrently modiIied by multiple
threads should be declared volatile. Variables declared to be volatile
will not be optimized by the compiler because their value can change at
any time. Questions : 26 What are the different types of errors in PHP? Answer : 26
Three are three types oI errors:1. Notices: These are trivial,
non-critical errors that PHP encounters while executing a script t' Ior
example, accessing a variable that has not yet been deIined. By deIault,
such errors are not displayed to the user at all t' although, as you will
see, you can change this deIault behavior.2. Warnings: These are more serious errors t' Ior
example, attempting
to include() a Iile which does not exist. By deIault, these errors are
displayed to the user, but they do not result in script termination.3. Fatal errors: These are critical
errors t' Ior example,
instantiating an object oI a non-existent class, or calling a
non-existent Iunction. These errors cause the immediate termination oI
the script, and PHP's deIault behavior is to display them to the user
when they take place. Questions : 27 What is the functionality of the function strstr and
stristr? Answers : 27 strstr Returns part oI string Irom the Iirst occurrence oI needle(sub string
that we Iinding out ) to the end oI string.
$email 'sonialoudergmail.com';
$domain strstr($email, '');
echo $domain; // prints gmail.com
here is the needle
stristr is case-insensitive means able not able to diIIrenciate between a and A Questions : 28
What are the differences between PHP 3 and PHP 4 and PHP 5? Answer : 28 There are lot
oI diIIerence among these three version oI php
1~Php3 is oldest version aIter that php4 came and current version is php5 (php5.3) where php6
have to come
2~DiIIerence mean oldest version have less Iunctionality as compare to new one like php5 have
all OOPs concept now where as php3 was pure procedural language constructive like C
In PHP5 1. Implementation oI exceptions and exception handling
2. Type hinting which allows you to Iorce the type oI a speciIic argument
3. Overloading oI methods through the call Iunction
4. Full constructors and destructors etc through a constuctor and destructor Iunction
5. autoload Iunction Ior dynamically including certain include Iiles depending on the class you
are trying to create.
6 Finality : can now use the Iinal keyword to indicate that a method cannot be overridden by a
child. You can also declare an entire class as Iinal which prevents it Irom having any children at
all.
7 InterIaces & Abstract Classes
8 Passed by ReIerence :
9 An clone method iI you really want to duplicate an object Questions : 29 How can we
convert asp pages to PHP pages? Answer : 29 there are lots oI tools available Ior asp to PHP
conversion. you can
search Google Ior that. the best one is available athttp://asp2php.naken.cc./ Questions : 30
What is the functionality of the function htmlentities? Answer : 30 Convert all applicable
characters to HTML entities
This Iunction is identical to htmlspecialchars() in all ways, except
with htmlentities(), all characters which have HTML character entity
equivalents are translated into these entities. Questions : 31 How can we get second of the
current time using date function?
Answer : 31 $second date("s"); Questions : 32 How can we convert the time zones using
PHP? Answer : 32 By using date_default_timezone_get and
date_default_timezone_set function on PHP 5.1.0
<.php
// Discover what 8am in Tokyo relates to on the East Coast of the US

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

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

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

// Jutput the date in a standard format (RFC1123), this will print:
// Fri, 31 Dec 1999 18:00:00 EST
echo '<p', date(DATE_RFC1123, $stamp) ,'</p';.
Questions : 33 What is meant by urlencode and urldocode? Answer : 33 URLencode
returns a string in which all non-alphanumeric characters
except _. have been replaced with a percent (%)
sign Iollowed by two hex digits and spaces encoded as plus (+)
signs. It is encoded the same way that the posted data Irom a WWW Iorm
is encoded, that is the same way as in
application/xwwwformurlencoded media type.
urldecode decodes any %
encoding in the given string.
Questions : 34 What is the difference between the functions unlink and unset?
Answer : 34 unlink() deletes the given Iile Irom the Iile system.
unset() makes a variable undeIined. Questions : 35 How can we register the variables into a
session? Answer : 35 $SESSION|'name'| "sonia"; Questions : 36 How can we get the
properties (size, type, width, height) of an
image using PHP image functions? Answer : 36 To know the Image type use exiIimagetype
() Iunction
To know the Image size use getimagesize () Iunction
To know the image width use imagesx () Iunction
To know the image height use imagesy() Iunction t Questions : 37 How can we get the
browser properties using PHP? Answer : 37 By using
$_SERVER'HTTP_USER_AGENT',
variable.
Questions : 38 What is the maximum size of a file that can be uploaded using PHP
and how can we change this? Answer : 38 By deIault the maximum size is 2MB. and we can
change the Iollowing
setup at php.iniuploadmaxIilesize 2M Questions : 39 How can we increase the
execution time of a PHP script? Answer : 39 by changing the Iollowing setup at
php.inimaxexecutiontime 30
; Maximum execution time oI each script, in seconds Questions : 40 How can we take a
backup of a MySQL table and how can we restore
it. ? Answer : 40 To backup: BACKUP TABLE tblname|,tblnamet,| TO
'/path/to/backup/directory'
RESTORE TABLE tblname|,tblnamet,| FROM '/path/to/backup/directory'mysqldump:
Dumping Table Structure and DataUtility to dump a database or a collection oI database Ior
backup or
Ior transIerring 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, t'no-create-inIo
Don't write table creation inIormation (the CREATE TABLE statement).
-d, t'no-data
Don't write any row inIormation Ior the table. This is very useIul iI
you just want to get a dump oI the structure Ior a table! Questions : 41 How can we optimize
or increase the speed of a MySQL select
query? Answer : 41
O Iirst oI all instead oI using select * Irom table1, use select
column1, column2, column3.. Irom table1
O Look Ior the opportunity to introduce index in the table you are
querying.
O use limit keyword iI you are looking Ior any speciIic number oI
rows Irom the result set.
Questions : 42 How many ways can we get the value of current session id? Answer : 42
sessionid() returns the session id Ior the current session. Questions : 43 How can we destroy
the session, how can we unset the variable of
a session? Answer : 43 sessionunregister t Unregister a global variable Irom the current
session
sessionunset t Free all session variables Questions : 44 How can we set and destroy the
cookie n php? Answer : 44 By using setcookie(name, value, expire, path, domain); Iunction we
can set the cookie in php ;
Set the cookies in past Ior destroy. like
setcookie("user", "sonia", time()3600); Ior set the cookie
setcookie("user", "", time()-3600); Ior destroy or delete the cookies; Questions : 45 How
many ways we can pass the variable through the navigation
between the pages? Answer : 45
O GET/QueryString
O POST
Questions : 46 What is the difference between ereg_replace() and eregi_replace()?
Answer : 46 eregireplace() Iunction is identical to eregreplace() except that
this ignores case distinction when matching alphabetic
characters.eregireplace() Iunction is identical to eregreplace()
except that this ignores case distinction when matching alphabetic
characters. Questions : 47 What are the different functions in sorting an array? Answer :
47 Sort(), arsort(),
asort(), ksort(),
natsort(), natcasesort(),
rsort(), usort(),
arraymultisort(), and
uksort(). Questions : 48 How can we know the count/number of elements of an array?
Answer : 48 2 ways
a) sizeoI($urarray) This Iunction is an alias oI count()
b) count($urarray) Questions : 49 what is session_set_save_handler in PHP? Answer : 49
session_set_save_handler() sets the user-level session storage Iunctions which are used Ior
storing and retrieving data associated with a session. This is most useIul when a storage method
other than those supplied by PHP sessions is preIerred. i.e. Storing the session data in a local
database. Questions : 50 How can I know that a variable is a number or not using a
1avaScript? Answer : 50 bool isnumeric ( mixed var)
Returns TRUE iI var is a number or a numeric string, FALSE otherwise.or use isNaN(mixed
var)The isNaN() Iunction is used to check iI a value is not a number. Questions : 51 List out
some tools through which we can draw E-R diagrams for
mysql. Answer : 51 Case Studio
Smart Draw Questions : 52 How can I retrieve values from one database server and store
them
in other database server using PHP? Answer : 52 we can always Ietch Irom one database and
rewrite to another. here
is a nice solution oI it.$db1 mysqlconnect("host","user","pwd")
mysqlselectdb("db1", $db1);
$res1 mysqlquery("query",$db1);$db2 mysqlconnect("host","user","pwd")
mysqlselectdb("db2", $db2);
$res2 mysqlquery("query",$db2);At this point you can only Ietch records Irom you previous
ResultSet,
i.e $res1 t' But you cannot execute new query in $db1, even iI you
supply the link as because the link was overwritten by the new db.so at this point the Iollowing
script will Iail
$res3 mysqlquery("query",$db1); //this will IailSo how to solve that?
take a look below.
$db1 mysqlconnect("host","user","pwd")
mysqlselectdb("db1", $db1);
$res1 mysqlquery("query",$db1);
$db2 mysqlconnect("host","user","pwd", true)
mysqlselectdb("db2", $db2);
$res2 mysqlquery("query",$db2);
So mysqlconnect has another optional boolean parameter which
indicates whether a link will be created or not. as we connect to the
$db2 with this optional parameter set to 'true', so both link will
remain live.
now the Iollowing query will execute successIully.
$res3 mysqlquery("query",$db1);
Questions : 53 List out the predefined classes in PHP? Answer : 53 Directory
stdClass
PHPIncompleteClass
exception
phpuserIilter Questions : 54 How can I make a script that can be bi-language (supports
English, German)? Answer : 54 You can maintain two separate language Iile Ior each oI the
language. all the labels are putted in both language Iiles as variables
and assign those variables in the PHP source. on runtime choose the
required language option. Questions : 55 What are the difference between abstract class
and interface? Answer : 55 Abstract class: abstract classes are the class where one or more
methods are abstract but not necessarily all method has to be abstract.
Abstract methods are the methods, which are declare in its class but not
deIine. The deIinition oI those methods must be in its extending class.InterIace: InterIaces are
one type oI class where all the methods are
abstract. That means all the methods only declared but not deIined. All
the methods must be deIine by its implemented class. Questions : 56 How can we send mail
using 1avaScript? Answer : 56 JavaScript does not have any networking capabilities as it is
designed to work on client site. As a result we can not send mails using
JavaScript. But we can call the client side mail protocol mailto
via JavaScript to prompt Ior an email to send. this requires the client
to approve it. Questions : 57 How can we repair a MySQL table? Answer : 57 The syntex
Ior repairing a MySQL table is
REPAIR TABLENAME, |TABLENAME, |, |Quick|,|Extended|
This command will repair the table speciIied iI the quick is given the
MySQL will do a repair oI only the index tree iI the extended is given
it will create index row by row Questions : 58 What are the advantages of stored
procedures, triggers, indexes?
Answer : 58 A stored procedure is a set oI 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 reIer to the stored procedure.
This provides better overall perIormance because the query has to be
parsed only once, and less inIormation needs to be sent between the
server and the client. You can also raise the conceptual level by having
libraries oI Iunctions in the server. However, stored procedures oI
course do increase the load on the database server system, as more oI
the work is done on the server side and less on the client (application)
side.Triggers will also be implemented. A trigger is eIIectively a type oI
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 Irom a transaction table and that stored
procedure automatically deletes the corresponding customer Irom a
customer table when all his transactions are deleted.Indexes are used to Iind rows with speciIic
column values quickly.
Without an index, MySQL must begin with the Iirst row and then read
through the entire table to Iind the relevant rows. The larger the
table, the more this costs. II the table has an index Ior the columns in
question, MySQL can quickly determine the position to seek to in the
middle oI the data Iile without having to look at all the data. II a
table has 1,000 rows, this is at least 100 times Iaster than reading
sequentially. II you need to access most oI the rows, it is Iaster to
read sequentially, because this minimizes disk seeks. Questions : 59 What is the maximum
length of a table name, database name, and
fieldname in MySQL? Answer : 59 The Iollowing table describes the maximum length Ior each
type oI
identiIier.
Identifier
Maximum Length
(bytes)
Database 64
Table 64
Column 64
Index 64
Alias 255
There are some restrictions on the characters that may appear in
identiIiers:
Questions : 60 How many values can the SET function of MySQL take? Answer : 60
MySQL set can take zero or more values but at the maximum it can
take 64 values Questions : 61 What are the other commands to know the structure of
table using
MySQL commands except explain command? Answer : 61 describe Table-Name;
Questions : 62 How many tables will create when we create table, what are they?
Answer : 62 The '.Irm' Iile stores the table deIinition.
The data Iile has a '.MYD' (MYData) extension.
The index Iile has a '.MYI' (MYIndex) extension, Questions : 63 What is the purpose of the
following files having extensions 1) .frm
2) .myd 3) .myi? What do these files contain? Answer : 63 In MySql, the deIault table type is
MyISAM.
Each MyISAM table is stored on disk in three Iiles. The Iiles have names
that begin with the table name and have an extension to indicate the
Iile type.
The '.Irm' Iile stores the table deIinition.
The data Iile has a '.MYD' (MYData) extension.
The index Iile has a '.MYI' (MYIndex) extension, Questions : 64 What is maximum size of a
database in MySQL? Answer : 64 II the operating system or Iilesystem places a limit on the
number
oI Iiles in a directory, MySQL is bound by that constraint.The eIIiciency oI the operating system
in handling large numbers oI
Iiles in a directory can place a practical limit on the number oI tables
in a database. II the time required to open a Iile in the directory
increases signiIicantly as the number oI Iiles increases, database
perIormance can be adversely aIIected.
The amount oI available disk space limits the number oI 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 t' 1 bytes). With this larger allowed table size,
the maximum eIIective table size Ior MySQL databases is usually
determined by operating system constraints on Iile sizes, not by MySQL
internal limits.The InnoDB storage engine maintains InnoDB tables within a tablespace
that can be created Irom several Iiles. This allows a table to exceed
the maximum individual Iile size. The tablespace can include raw disk
partitions, which allows extremely large tables. The maximum tablespace
size is 64TB.
The Iollowing table lists some examples oI operating system Iile-size
limits. This is only a rough guide and is not intended to be deIinitive.
For the most up-to-date inIormation, be sure to check the documentation
speciIic to your operating system.
Operating System File-size LimitLinux 2.2-Intel 32-bit 2GB (LFS: 4GB)
Linux 2.4 (using ext3 Iilesystem) 4TB
Solaris 9/10 16TB
NetWare w/NSS Iilesystem 8TB
Win32 w/ FAT/FAT32 2GB/4GB
Win32 w/ NTFS 2TB (possibly larger)
MacOS X w/ HFS 2TB Questions : 65 Give the syntax of Grant and Revoke commands?
Answer : 65 The generic syntax Ior grant is as Iollowing
~ GRANT |rights| on |database/s| TO |usernamehostname| IDENTIFIED BY
|password|
now rights can be
a) All privileges
b) combination oI create, drop, select, insert, update and delete etc.We can grant rights on all
databse by using *.* or some speciIic
database by database.* or a speciIic table by database.tablename
usernamehotsname can be either usernamelocalhost, usernamehostname
and username
where hostname is any valid hostname and represents any name, the *.*
any condition
password is simply the password oI userThe generic syntax Ior revoke is as Iollowing
~ REVOKE |rights| on |database/s| FROM |usernamehostname|
now rights can be as explained above
a) All privileges
b) combination oI create, drop, select, insert, update and delete etc.
usernamehotsname can be either usernamelocalhost, usernamehostname
and username
where hostname is any valid hostname and represents any name, the *.*
any condition Questions : 66 Explain Normalization concept? Answer : 66 The
normalization process involves getting our data to conIorm to
three progressive normal Iorms, and a higher level oI normalization
cannot be achieved until the previous levels have been achieved (there
are actually Iive normal Iorms, but the last two are mainly academic and
will not be discussed).First Normal FormThe First Normal Form (or 1NF) involves removal oI
redundant data
Irom horizontal rows. We want to ensure that there is no duplication oI
data in a given row, and that every column stores the least amount oI
inIormation possible (making the Iield atomic).Second Normal FormWhere the First Normal
Form deals with redundancy oI data across a
horizontal row, Second Normal Form (or 2NF) deals with redundancy oI
data in vertical columns. As stated earlier, the normal Iorms are
progressive, so to achieve Second Normal Form, your tables must already
be in First Normal Form.Third Normal Form
I have a conIession to make; I do not oIten use Third Normal Form. In
Third Normal Form we are looking Ior data in our tables that is not
Iully dependant on the primary key, but dependant on another value in
the table
Questions : 67 How can we find the number of rows in a table using MySQL? Answer :
67 Use this Ior mysql
~SELECT COUNT(*) FROM tablename; Questions : 68 How can we find the number of
rows in a result set using PHP? Answer : 68 $result = mysql_query($sql, $db_link);
$num_rows = mysql_num_rows($result);
echo "$num_rows rows found"; Questions : 69 How many ways we can we find the
current date using MySQL? Answer : 69 SELECT CURDATE();
CURRENTDATE() CURDATE()
Ior time use
SELECT CURTIME();
CURRENTTIME() CURTIME() Questions : 70 What are the advantages and
disadvantages of Cascading Style
Sheets? Answer : 70 External Style SheetsAdvantagesCan control styles Ior multiple documents
at once. Classes can be
created Ior use on multiple HTML element types in many documents.
Selector and grouping methods can be used to apply styles under complex
contextsDisadvantagesAn extra download is required to import style inIormation Ior each
document The rendering oI the document may be delayed until the external
style sheet is loaded Becomes slightly unwieldy Ior small quantities oI
style deIinitionsEmbedded Style Sheets
Advantages
Classes can be created Ior 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 inIormation
Disadvantages
This method can not control styles Ior multiple documents at once
Inline Styles
Advantages
UseIul Ior small quantities oI style deIinitions. Can override other
style speciIication methods at the local level so only exceptions need
to be listed in conjunction with other style methods
Disadvantages
Does not distance style inIormation Irom content (a main goal oI
SGML/HTML). Can not control styles Ior multiple documents at once.
Author can not create or control classes oI elements to control multiple
element types within the document. Selector grouping methods can not be
used to create complex element addressing scenarios
Questions : 71 What type of inheritance that PHP supports? Answer : 71 In PHP an
extended class is always dependent on a single base class,
that is, multiple inheritance is not supported. Classes are extended
using the keyword 'extends'. Questions : 72 What is the difference between Primary Key
and
Unique key? Answer : 72 Primary Key: A column in a table whose values uniquely identiIy the
rows in the table. A primary key value cannot be NULL.
Unique Key: Unique Keys are used to uniquely identiIy each row in the
table. There can be one and only one row Ior each unique key value. So
NULL can be a unique key.There can be only one primary key Ior a table but there can be more
than one unique Ior a table.

Question : 73 what is garbage collection? default time ? refresh time? Answer : 73 Garbage
Collection is an automated part oI PHP , II the Garbage Collection process runs, it then analyzes
any Iiles in the /tmp Ior any session Iiles that have not been accessed in a certain amount oI time
and physically deletes them. Garbage Collection process only runs in the deIault session save
directory, which is /tmp. II you opt to save your sessions in a diIIerent directory, the Garbage
Collection process will ignore it. the Garbage Collection process does not diIIerentiate between
which sessions belong to whom when run. This is especially important note on shared web
servers. II the process is run, it deletes ALL Iiles that have not been accessed in the directory.
There are 3 PHP.ini variables, which deal with the garbage collector: PHP ini value name deIault
session.gcmaxliIetime 1440 seconds or 24 minutes session.gcprobability 1 session.gcdivisor
100 Questions : 74 What are the advantages/disadvantages of MySQL and PHP? Answer
: 74 Both oI them are open source soItware (so Iree oI cost), support
cross platIorm. php is Iaster then ASP and JSP. Questions : 75 What is the difference
between GROUP BY and ORDER BY in Sql? Answer : 75 ORDER BY
|col1|,|col2|,t,,|coln|; Tels DBMS according to what columns
it should sort the result. II two rows will hawe the same value in col1
it will try to sort them according to col2 and so on.GROUP BY
|col1|,|col2|,t,,|coln|; Tels DBMS to group results with same value oI
column col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, iI
you want to count all items in group, sum all values or view average Questions : 76 What is
the difference between char and varchar data types? Answer : 76 Set char to occupy n bytes
and it will take n bytes even iI u r
storing a value oI n-m bytes
Set varchar to occupy n bytes and it will take only the required space
and will not use the n bytes
eg. name char(15) will waste 10 bytes iI we store 'romharshan', iI each char
takes a byte
eg. name varchar(15) will just use 5 bytes iI we store 'romharshan', iI each
char takes a byte. rest 10 bytes will be Iree. Questions : 77 What is the functionality of md5
function in PHP? Answer : 77 Calculate the md5 hash oI a string. The hash is a 32-character
hexadecimal number. I use it to generate keys which I use to identiIy
users etc. II I add random no techniques to it the md5 generated now
will be totally diIIerent Ior the same string I am using. Questions : 78 How can I load data
from a text file into a table? Answer : 78 you can use LOAD DATA INFILE Iilename;
syntax to load data
Irom a text Iile. but you have to make sure thata) data is delimited
b) columns and data matched correctly Questions : 79 How can we know the number of
days between two given dates using
MySQL? Answer : 79 SELECT DATEDIFF("2007-03-07","2005-01-01"); Questions : 80
How can we know the number of days between two given dates using PHP? Answer : 80
$date1 date("Y-m-d");
$date2 "2006-08-15";
$days (strtotime($date1) - strtotime($date2)) / (60 * 60 * 24); Questions : 81 How we load
all classes that placed in different directory in one PHP File , means how to do auto load
classes Answer : 81

by using splautoloadregister('autoloader::Iuntion');

Like below

class autoloader



public static Iunction moduleautoloader($class)



$path $SERVER|'DOCUMENTROOT'| . "/modules/$class}.php";

iI (isreadable($path)) require $path;

}

public static Iunction daoautoloader($class)



$path $SERVER|'DOCUMENTROOT'| . "/dataobjects/$class}.php";

iI (isreadable($path)) require $path;

}

public static Iunction includesautoloader($class)



$path $SERVER|'DOCUMENTROOT'| . "/includes/$class}.php";

iI (isreadable($path)) require $path;

}

}

splautoloadregister('autoloader::includesautoloader');

splautoloadregister('autoloader::daoautoloader');

splautoloadregister('autoloader::moduleautoloader');

Questions : 82 How many types of Inheritances used in PHP and how we achieve it
Answer : 82 As Iar PHP concern it only support single Inheritance in scripting.
we can also use interIace to achieve multiple inheritance. Questions : 83 PHP how to know
user has read the email? Answers : 83 Using Disposition-NotiIication-To: in mailheader we
can get read receipt.
Add the possibility to deIine a read receipt when sending an email.
Itts quite straightIorward, just edit email.php, and add this at vars deIinitions:
var $readReceipt null;
And then, at t`createHeadert Iunction add:
iI (!empty($this-~readReceipt))
$this-~header . t`Disposition-NotiIication-To: t` . $this-~IormatAddress($this-
~readReceipt) . $this-~newLine;
} Questions : 84 What are default session time and path? Answers : 84 deIault session
time in PHP is 1440 seconds or 24 minutes
DeIault session save path id temporary Iolder /tmp Questions : 85 how to track user logged
out or not? when user is idle ? Answers : 85 By checking the session variable exist or not
while loading th page. As the session will exist longer as till browser closes. The deIault
behaviour Ior sessions is to keep a session open indeIinitely and only to expire a session when
the browser is closed. This behaviour can be changed in the php.ini Iile by altering the line
session.cookieliIetime 0 to a value in seconds. II you wanted the session to Iinish in 5 minutes
you would set this to session.cookieliIetime 300 and restart your httpd server. Questions :
86 how to track no of user logged in ? Answers : 86 whenever a user logs in track the IP,
userID etc..and store it in a DB with a active Ilag while log out or sesion expire make it inactive.
At any time by counting the no: oI active records we can get the no: oI visitors. Questions : 87
in PHP for pdf which library used? Answers : 87 The PDF Iunctions in PHP can create PDF
Iiles using the PDFlib library With version 6, PDFlib oIIers an object-oriented API Ior PHP 5 in
addition to the Iunction-oriented API Ior PHP 4. There is also the Panda module. FPDF is a
PHP class which allows to generate PDF Iiles with pure PHP, that is to say without using the
PDFlib library. F Irom FPDF stands Ior Free: you may use it Ior any kind oI usage and modiIy it
to suit your needs. FPDF requires no extension (except zlib to activate compression and GD Ior
GIF support) and works with PHP4 and PHP5. Questions : 88 for image work which
library? Answers : 88 we will need to compile PHP with the GD library oI image Iunctions Ior
this to work. GD and PHP may also require other libraries, depending on which image Iormats
you want to work with. Questions : 89 what is design pattern? singleton pattern? Answers
: 89 A design pattern is a general reusable solution to a commonly occurring problem in soItware
design.
The Singleton design pattern allows many parts oI a program to share a single resource without
having to work out the details oI the sharing themselves. Questions : 90 what are magic
methods? Answers : 90 Magic methods are the members Iunctions that is available to all the
instance oI class Magic methods always starts with "". Eg. construct All magic methods
needs to be declared as public To use magic method they should be deIined within the class or
program scope Various Magic Methods used in PHP 5 are: construct() destruct() set()
get() call() toString() sleep() wakeup() isset() unset() autoload() clone()
Questions : 91 what is magic quotes? Answers : 91 Magic Quotes is a process that
automagically escapes ncoming data to the PHP script. Itts preIerred to code with magic
quotes oII and to instead escape the data at runtime, as needed. This Ieature has been
DEPRECATED as oI PHP 5.3.0 and REMOVED as oI PHP 6.0.0. Relying on this Ieature is
highly discouraged. Questions : 92 what is cross site scripting? SQL injection? Answers :
92 Cross-site scripting (XSS) is a type oI computer security vulnerability typically Iound in web
applications which allow code injection by malicious web users into the web pages viewed by
other users. Examples oI such code include HTML code and client-side scripts. SQL injection is
a code injection technique that exploits a security vulnerability occurring in the database layer oI
an application. The vulnerability is present when user input is either incorrectly Iiltered Ior string
literal escape characters embedded in SQL statements or user input is not strongly typed and
thereby unexpectedly executed Questions : 93 what is URL rewriting? Answers : 93 Using
URL rewriting we can convert dynamic URl to static URL Static URLs are known to be better
than Dynamic URLs because oI a number oI reasons 1. Static URLs typically Rank better in
Search Engines. 2. Search Engines are known to index the content oI dynamic pages a lot slower
compared to static pages. 3. Static URLs are always more Iriendlier looking to the End Users.
along with this we can use URL rewriting in adding variables |cookies| to the URL to handle the
sessions. Questions : 94 what is the major php security hole? how to avoid? Answers : 94
1. Never include, require, or otherwise open a Iile with a Iilename based on user input, without
thoroughly checking it Iirst.
2. Be careIul with eval() Placing user-inputted values into the eval() Iunction can be extremely
dangerous. You essentially give the malicious user the ability to execute any command he or she
wishes!
3. Be careIul when using registerglobals ON It was originally designed to make programming
in PHP easier (and that it did), but misuse oI it oIten led to security holes
4. Never run unescaped queries
5. For protected areas, use sessions or validate the login every time.
6. II you dontt want the Iile contents to be seen, give the Iile a .php extension. Questions :
95 whether PHP supports Microsoft SQL server ? Answers : 95 The SQL Server Driver Ior
PHP v1.0 is designed to enable reliable, scalable integration with SQL Server Ior PHP
applications deployed on the Windows platIorm. The Driver Ior PHP is a PHP 5 extension that
allows the reading and writing oI SQL Server data Irom within PHP scripts. using MSSQL or
ODBC modules we can access MicrosoIt SQL server. Questions : 96 what is MVC? why its
been used? Answers : 96 Model-view-controller (MVC) is an architectural pattern used in
soItware engineering. SuccessIul use oI the pattern isolates business logic Irom user interIace
considerations, resulting in an application where it is easier to modiIy either the visual
appearance oI the application or the underlying business rules without aIIecting the other. In
MVC, the model represents the inIormation (the data) oI the application; the view corresponds to
elements oI the user interIace such as text, checkbox items, and so Iorth; and the controller
manages the communication oI data and the business rules used to manipulate the data to and
Irom the model. WHY ITS NEEDED IS 1 Modular separation oI Iunction 2 Easier to maintain 3
View-Controller separation means:
A t Tweaking design (HTML) without altering code B t Web design staII can modiIy UI
without understanding code Questions : 97 what is framework? how it works? what is
advantage? Answers : 97 In general, a Iramework is a real or conceptual structure intended to
serve as a support or guide Ior the building oI something that expands the structure into
something useIul. Advantages : Consistent Programming Model Direct Support Ior Security
SimpliIied Development EIIorts Easy Application Deployment and Maintenance Questions :
98 what is CURL? Answers : 98 CURL means Client URL Library
curl is a command line tool Ior transIerring Iiles with URL syntax, supporting FTP, FTPS,
HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS and FILE. curl supports
SSL certiIicates, HTTP POST, HTTP PUT, FTP uploading, HTTP Iorm based upload, proxies,
cookies, userpassword authentication (Basic, Digest, NTLM, Negotiate, kerberost,), Iile
transIer resume, proxy tunneling and a busload oI other useIul tricks.
CURL allows you to connect and communicate to many diIIerent types oI servers with many
diIIerent types oI protocols. libcurl currently supports the http, https, Itp, gopher, telnet, dict, Iile,
and ldap protocols. libcurl also supports HTTPS certiIicates, HTTP POST, HTTP PUT, FTP
uploading (this can also be done with PHPts Itp extension), HTTP Iorm based upload,
proxies, cookies, and userpassword authentication. Questions : 99 what is PDO ? Answers
: 99
The PDO ( PHP Data Objects ) extension deIines a lightweight, consistent interIace Ior accessing
databases in PHP. iI you are using the PDO API, you could switch the database server you used,
Irom say PgSQL to MySQL, and only need to make minor changes to your PHP code.
While PDO has its advantages, such as a clean, simple, portable API but its main disadvantage
is that it doesn't allow you to use all oI the advanced Ieatures that are available in the latest
versions oI MySQL server. For example, PDO does not allow you to use MySQL's support Ior
Multiple Statements.
Just need to use below code Ior connect mysql using PDO
try
$dbh new PDO("mysql:host$hostname;dbnamedatabasename", $username, $password);
$sql "SELECT * FROM employee";
Ioreach ($dbh-~query($sql) as $row)

print $row|'employeename'| .' - '. $row|'employeeage'| ;
}
}
catch(PDOException $e)

echo $e-~getMessage();
} Questions : 100 What is PHP's mysqli Extension? Answers : 100
The mysqli extension, or as it is sometimes known, the MySQL improved extension, was
developed to take advantage oI new Ieatures Iound in MySQL systems versions 4.1.3 and newer.
The mysqli extension is included with PHP versions 5 and later.
The mysqli extension has a number oI beneIits, the key enhancements over the mysql extension
being:
~Object-oriented interIace
~Support Ior Prepared Statements
~Support Ior Multiple Statements
~Support Ior Transactions
~Enhanced debugging capabilities
~Embedded server support
oops interview questions and answers are below
Questions
: 1
What is Object Oriented Programming ?
nswers :
1
It is a problem solving technique to develop software systems. It is a technique to think real world in
terms of objects. Object maps the software model to real world concept. These objects have
responsibilities and provide services to application or other objects.

Questions
: 2
What is a Class ?
nswers :
2
A class describes all the attributes of objects, as well as the methods that implement the behavior of
member objects. It is a comprehensive data type which represents a blue print of objects. Its a
template of object.

Questions
: 3
What is an Object ?
nswers :
3
It is a basic unit of a system. An object is an entity that has attributes, behavior, and identity. Objects
are members of a class. Attributes and behavior of an object are defined by the class definition.

Questions
: 4
What is the relation between Classes and Objects?
nswers :
4
They look very much same but are not same. Class is a definition, while object is instance of the class
created. Class is a blue print while objects are actual objects existing in real world. Example we have
class CAR which has attributes and methods like Speed, Brakes, Type of Car etc.Class CAR is just a
prototype, now we can create real time objects which can be used to provide functionality. Example
we can create a Maruti car object with 100 km speed and urgent brakes.

Questions
: 5
What are different properties provided by Object-oriented systems ?
nswers :
5
Following are characteristics of Object Oriented System's:-
bstraction
It allows complex real world to be represented in simplified manner. Example color is abstracted to
RGB.By just making the combination of these three colors we can achieve any color in world. Its a
model of real world or concept.
Encapsulation
The process of hiding all the internal details of an object from the outside world.
Communication
Using messages when application wants to achieve certain task it can only be done using combination
of objects. A single object can not do the entire task. Example if we want to make order processing
form. We will use Customer object, Order object, Product object and Payment object to achieve this
functionality. In short these objects should communicate with each other. This is achieved when
objects send messages to each other.
Object lifetime
All objects have life time. Objects are created, initialized, necessary functionalities are done and later
the object is destroyed. Every object have there own state and identity, which differ from instance to
instance.

Questions
: 6
What is an bstract class ?
nswers :
6
Abstract class defines an abstract concept which can not be instantiated and comparing o interface it
can have some implementation while interfaces can not. Below are some
points for abstract class:-
=>We can not create object of abstract class it can only be inherited in a below class.
=> Normally abstract classes have base implementation and then child classes derive from the
abstract class to make the class concrete.

Questions
: 7
What are bstract methods?
nswers :
7
Abstract class can contain abstract methods. Abstract methods do not have implementation. Abstract
methods should be implemented in the subclasses which inherit them. So if an abstract class has an
abstract method class inheriting the abstract class should implement the method or else java compiler
will through an error. In this way, an abstract class can define a complete programming interface
thereby providing its subclasses with the method declarations for all of the methods necessary to
implement that programming interface. Abstract methods are defined using "abstract" keyword.
Below is a sample code snippet.
abstract class pcdsGraphics
{
abstract void draw();
}
Any class inheriting from "pcdsGraphics" class should implement the "draw" method or else the java
compiler will throw an error. so if we do not implement a abstract method the program will not
compile.

Questions
: 8
What is the difference between bstract classes and Interfaces ?
nswers :
8
Difference between Abstract class and Interface is as follows:-
Abstract class can only be inherited while interfaces can not be it has to be implemented.
Interface cannot implement any methods, whereas an abstract class can have implementation.
Class can implement many interfaces but can have only one super class.
Interface is not part of the class hierarchy while Abstract class comes in through inheritance.
Unrelated classes can implement the same interface.

Questions
: 9
What is difference between Static and Non-Static fields of a class ?
nswers :
9
Non-Static values are also called as instance variables. Each object of the class has its own copy of
Non-Static instance variables. So when a new object is created of the same class it will have
completely its own copy of instance variables. While Static values have only one copy of instance
variables and will be shared among all the objects of the class.

Questions
: 10
What are inner classes and what is the practical implementation of inner classes?
nswers :
10
Inner classes are nested inside other class. They have access to outer class fields and methods even if
the fields of outer class are defined as private.
public class Pcds
{
class pcdsEmp
{
// inner class defines the required structure
String first;
String last;
}
// array of name objects
clsName personArray[] = {new clsName(), new clsName(), new clsName()};
}
Normally inner classes are used for data structures like one shown above or some kind of helper
classes.

Questions
: 11
What is a constructor in class?
nswers :
11
Constructor has the same name as the class in which it resides and looks from syntax point of view it
looks similiar to a method. Constructor is automatically called immediately after the object is created,
before the new operator completes. Constructors have no return type, not even void. This is because
the implicit return type of a class' constructor is the class type itself. It is the constructor's job to
initialize the internal state of an object so that the code creating an instance will have a fully
initialized, usable object immediately.

Questions
: 12
Can constructors be parameterized?
nswers :
12
Yes we can have parameterized constructor which can also be termed as constructor overloading.
Below is a code snippet which shows two constructors for pcdsMaths class one with parameter and
one with out.
class pcdsMaths
{
double PI;
// This is the constructor for the maths constant class.
pcdsMaths()
{PI = 3.14;}
pcdsMaths(int pi)
{
PI = pi;
} }

Questions
: 13
What is the use if instanceof keyword? and How do refer to a current instance of object?
nswers :
13
"instanceof" keyword is used to check what is the type of object.
we can refer the current instance of object using "this" keyword. For instance if we have class which
has color property we can refer the current object instance inside any of the method using
"this.color".

Questions
: 14
what is Bootstrap, Extension and System Class loader? or Can you explain primordial class
loader?
nswers :
14
There three types of class loaders:-
BootStrap Class loader also called as primordial class loader.
Extension Class loader.
System Class loader. Lets now try to get the fundamentals of these class loaders.

Bootstrap Class loader
Bootstrap class loader loads those classes those which are essential for JVM to function properly.
Bootstrap class loader is responsible for loading all core java classes for instance java.lang.*, java.io.*
etc. Bootstrap class loader finds these necessary classes from "jdk/ jre/lib/rt.jar. Bootstrap class
loader can not be instantiated from JAVA code and is implemented natively inside JVM.
Extension Class loader
The extension class loader also termed as the standard extensions class loader is a child of the
bootstrap class loader. Its primary responsibility is to load classes from the extension directories,
normally located the "jre/lib/ext directory. This provides the ability to simply drop in new extensions,
such as various security extensions, without requiring modification to the user's class path.
System Class loader
The system class loader also termed application class loader is the class loader responsible for loading
code from the path specified by the CLASSPATH environment variable. It is also used to load an
applications entry point class that is the "static void main ()" method in a class.

Questions
: 15
what's the main difference between rrayList / HashMap and Vector / Hashtable?
nswers :
15
Vector / HashTable are synchronized which means they are thread safe. Cost of thread safe is
performance degradation. So if you are sure that you are not dealing with huge number of threads
then you should use ArrayList / HashMap.But yes you can still
synchronize List and Maps using Collections provided methods :-
List OurList = Collections.synchronizedList (OurList);
Map OurMap = Collections.synchronizedMap (OurMap);

Questions
: 16
What are access modifiers?
nswers :
16
Access modifiers decide whether a method or a data variable can be accessed by another method in
another class or subclass.
four types of access modifiers:
Public: - Can be accessed by any other class anywhere.
Protected: - Can be accessed by classes inside the package or by subclasses ( that means classes
who inherit from this class).
Private - Can be accessed only within the class. Even methods in subclasses in the same package do
not have access.
Default - (Its private access by default) accessible to classes in the same package but not by classes
in other packages, even if these are subclasses.

Questions
: 17
Define exceptions ?
nswers :
17
An exception is an abnormal condition that arises in a code sequence at run time. Basically there are
four important keywords which form the main pillars of exception handling: try, catch, throw and
finally. Code which you want to monitor for exception is contained in the try block. If any exception
occurs in the try block its sent to the catch block which can handle this error in a more rational
manner. To throw an exception manually you need to call use the throw keyword. If you want to put
any clean up code use the finally block. The finally block is executed irrespective if there is an error or
not.

Questions
: 18
What is serialization?How do we implement serialization actually?
nswers :
18
Serialization is a process by which an object instance is converted in to stream of bytes. There are
many useful stuff you can do when the object instance is converted in to stream of bytes for instance
you can save the object in hard disk or send it across the network.
In order to implement serialization we need to use two classes from java.io package
ObjectOutputStream and ObjectInputStream. ObjectOutputStream has a method called writeObject,
while ObjectInputStream has a method called readObject. Using writeobject we can write and
readObject can be used to read the object from the stream. Below are two code snippet which used
the FileInputStream and FileOutputstream to read and write from harddisk.
Database (DBMS) interview questions and answers are below
Questions
: 1
What is database or database management systems (DBMS)? and - What's the difference
between file and database? Can files qualify as a database?
nswers :
1
Database provides a systematic and organized way of storing, managing and retrieving from collection
of logically related information.
Secondly the information has to be persistent, that means even after the application is closed the
information should be persisted.
Finally it should provide an independent way of accessing data and should not be dependent on the
application to access the information.
Main difference between a simple file and database that database has independent way (SQL) of
accessing information while simple files do not File meets the storing, managing and retrieving part of
a database but not the independent way of accessing data. Many experienced programmers think that
the main difference is that file can not provide multi-user capabilities which a DBMS provides. But if
we look at some old COBOL and C programs where file where the only means of storing data, we can
see functionalities like locking, multi-user etc provided very efficiently. So its a matter of debate if
some interviewers think this as a main difference between files and database accept it. going in to
debate is probably loosing a job.

Questions
: 2
What is SQL ?
nswers :
2
SQL stands for Structured Query Language.SQL is an ANSI (American National Standards Institute)
standard computer language for accessing and manipulating database systems. SQL statements are
used to retrieve and update data in a database.


Questions
: 3
What's difference between DBMS and RDBMS ?
nswers :
3
DBMS provides a systematic and organized way of storing, managing and retrieving from collection of
logically related information. RDBMS also provides what DBMS provides but above that it provides
relationship integrity. So in short we can say
RDBMS = DBMS + REFERENTIL INTEGRITY
These relations are defined by using "Foreign Keys in any RDBMS.Many DBMS companies claimed
there DBMS product was a RDBMS compliant, but according to industry rules and regulations if the
DBMS fulfills the twelve CODD rules its truly a RDBMS. Almost all DBMS (SQL SERVER, ORACLE etc)
fulfills all the twelve CODD rules and are considered as truly RDBMS.

Questions
: 4
What are CODD rules?
nswers :
4
In 1969 Dr. E. F. Codd laid down some 12 rules which a DBMS should adhere in order to get the logo
of a true RDBMS.
Rule 1: Information Rule.
"All information in a relational data base is represented explicitly at the logical level and in exactly one
way - by values in tables."
Rule 2: Guaranteed access Rule.
"Each and every datum (atomic value) in a relational data base is guaranteed to be logically
accessible by resorting to a combination of table name, primary key value and column name."
In flat files we have to parse and know exact location of field values. But if a DBMS is truly RDBMS
you can access the value by specifying the table name, field name, for instance Customers.Fields
[`Customer Name].
Rule 3: Systematic treatment of null values.
"Null values (distinct from the empty character string or a string of blank characters and distinct from
zero or any other number) are supported in fully relational DBMS for representing missing information
and inapplicable information in a systematic way, independent of data type.".
Rule 4: Dynamic on-line catalog based on the relational model.
"The data base description is represented at the logical level in the same way as ordinary data, so
that authorized users can apply the same relational language to its interrogation as they apply to the
regular data."The Data Dictionary is held within the RDBMS, thus there is no-need for off-line volumes
to tell you the structure of the database.
Rule 5: Comprehensive data sub-language Rule.
"A relational system may support several languages and various modes of terminal use (for example,
the fill-in-the-blanks mode). However, there must be at least one language whose statements are
expressible, per some well-defined syntax, as character strings and that is comprehensive in
supporting all the following items

Data Definition
View Definition
Data Manipulation (Interactive and by program).
Integrity Constraints
Authorization.
Transaction boundaries ( Begin , commit and rollback)
Rule 6: .View updating Rule
"All views that are theoretically updatable are also updatable by the system."
Rule 7: High-level insert, update and delete.
"The capability of handling a base relation or a derived relation as a single operand applies not only to
the retrieval of data but also to the insertion, update and deletion of data."
Rule 8: Physical data independence.
"Application programs and terminal activities remain logically unimpaired whenever any changes are
made in either storage representations or access methods."
Rule 9: Logical data independence.
"Application programs and terminal activities remain logically unimpaired when information-preserving
changes of any kind that theoretically permit un-impairment are made to the base tables."
Rule 10: Integrity independence.
"Integrity constraints specific to a particular relational data base must be definable in the relational
data sub-language and storable in the catalog, not in the application programs." Rule 11:
Distribution independence.
"A relational DBMS has distribution independence."
Rule 12: Non-subversion Rule.
"If a relational system has a low-level (single-record-at-a-time) language, that low level cannot be
used to subvert or bypass the integrity Rules and constraints expressed in the higher level relational
language (multiple-records-at-a-time)."

Questions
: 5
What are E-R diagrams?
nswers :
5
E-R diagram also termed as Entity-Relationship diagram shows relationship between various tables in
the database. .

Questions
: 6
How many types of relationship exist in database designing?
nswers :
6
There are three major relationship models:-
One-to-one
One-to-many
Many-to-many

Questions
: 7
7.What is normalization? What are different type of normalization?
nswers :
7
There is set of rules that has been established to aid in the design of tables that are meant to be
connected through relationships. This set of rules is known as Normalization.
Benefits of Normalizing your database include:
=>Avoiding repetitive entries
=>Reducing required storage space
=>Preventing the need to restructure existing tables to accommodate new data.
=>Increased speed and flexibility of queries, sorts, and summaries.

Following are the three normal forms :-
First Normal Form
For a table to be in first normal form, data must be broken up into the smallest un possible.In addition
to breaking data up into the smallest meaningful values, tables first normal form should not contain
repetitions groups of fields.
Second Normal form
The second normal form states that each field in a multiple field primary keytable must be directly
related to the entire primary key. Or in other words,each non-key field should be a fact about all the
fields in the primary key.
Third normal form
A non-key field should not depend on other Non-key field.

Questions
: 8
What is denormalization ?
nswers :
8
Denormalization is the process of putting one fact in numerous places (its vice-versa of
normalization).Only one valid reason exists for denormalizing a relational design - to enhance
performance.The sacrifice to performance is that you increase redundancy in database.

Questions
: 9
Can you explain Fourth Normal Form and Fifth Normal Form ?
nswers :
9
In fourth normal form it should not contain two or more independent multi-v about an entity and it
should satisfy "Third Normal form.
Fifth normal form deals with reconstructing information from smaller pieces of information. These
smaller pieces of information can be maintained with less redundancy.

Questions
: 10
Have you heard about sixth normal form?
nswers :
10
If we want relational system in conjunction with time we use sixth normal form. At this moment SQL
Server does not supports it directly.

Questions
: 11
What are DML and DDL statements?
nswers :
11
DML stands for Data Manipulation Statements. They update data values in table. Below are the most
important DDL statements:-
=>SELECT - gets data from a database table
=> UPDATE - updates data in a table
=> DELETE - deletes data from a database table
=> INSERT INTO - inserts new data into a database table

DDL stands for Data definition Language. They change structure of the database objects like table,
index etc. Most important DDL statements are as shown below:-
=>CREATE TABLE - creates a new table in the database.
=>ALTER TABLE - changes table structure in database.
=>DROP TABLE - deletes a table from database
=> CREATE INDEX - creates an index
=> DROP INDEX - deletes an index

Questions
: 12
How do we select distinct values from a table?
nswers :
12
DISTINCT keyword is used to return only distinct values. Below is syntax:- Column age and Table
pcdsEmp
SELECT DISTINCT age FROM pcdsEmp

Questions
: 13
What is Like operator for and what are wild cards?
nswers :
13
LIKE operator is used to match patterns. A "%" sign is used to define the pattern.
Below SQL statement will return all words with letter "S"
SELECT * FROM pcdsEmployee WHERE EmpName LIKE 'S%'
Below SQL statement will return all words which end with letter "S"
SELECT * FROM pcdsEmployee WHERE EmpName LIKE '%S'
Below SQL statement will return all words having letter "S" in between
SELECT * FROM pcdsEmployee WHERE EmpName LIKE '%S%'
"_" operator (we can read as "Underscore Operator). "_ operator is the character defined at that
point. In the below sample fired a query Select name from pcdsEmployee where name like '_s%' So
all name where second letter is "s is returned.

Questions
: 14
Can you explain Insert, Update and Delete query?
nswers :
14
Insert statement is used to insert new rows in to table. Update to update existing data in the table.
Delete statement to delete a record from the table. Below code snippet for Insert, Update and Delete
:-
INSERT INTO pcdsEmployee SET name='rohit',age='24';
UPDATE pcdsEmployee SET age='25' where name='rohit';
DELETE FROM pcdsEmployee WHERE name = 'sonia';

Questions
: 15
What is order by clause?
nswers :
15
ORDER BY clause helps to sort the data in either ascending order to descending order.
Ascending order sort query
SELECT name,age FROM pcdsEmployee ORDER BY age ASC
Descending order sort query
SELECT name FROM pcdsEmployee ORDER BY age DESC

Questions
: 16
What is the SQL " IN " clause?
nswers :
16
SQL IN operator is used to see if the value exists in a group of values. For instance the below SQL
checks if the Name is either 'rohit' or 'Anuradha' SELECT * FROM pcdsEmployee WHERE name IN
('Rohit','Anuradha') Also you can specify a not clause with the same. SELECT * FROM pcdsEmployee
WHERE age NOT IN (17,16)

Questions
: 17
Can you explain the between clause?
nswers :
17
Below SQL selects employees born between '01/01/1975' AND '01/01/1978' as per mysql
SELECT * FROM pcdsEmployee WHERE DOB BETWEEN '1975-01-01' AND '2011-09-28'

Questions
: 18
we have an employee salary table how do we find the second highest from it?
nswers :
18
below Sql Query find the second highest salary
SELECT * FROM pcdsEmployeeSalary a WHERE (2=(SELECT COUNT(DISTINCT(b.salary)) FROM
pcdsEmployeeSalary b WHERE b.salary>=a.salary))

Questions
: 19
What are different types of joins in SQL?
nswers :
19
INNER JOIN
Inner join shows matches only when they exist in both tables. Example in the below SQL there are
two tables Customers and Orders and the inner join in made on Customers.Customerid and
Orders.Customerid. So this SQL will only give you result with customers who have orders. If the
customer does not have order it will not display that record.
SELECT Customers.*, Orders.* FROM Customers INNER JOIN Orders ON Customers.CustomerID
=Orders.CustomerID

LEFT OUTER JOIN
Left join will display all records in left table of the SQL statement. In SQL below customers with or
without orders will be displayed. Order data for customers without orders appears as NULL values. For
example, you want to determine the amount ordered by each customer and you need to see who has
not ordered anything as well. You can also see the LEFT OUTER JOIN as a mirror image of the RIGHT
OUTER JOIN (Is covered in the next section) if you switch the side of each table.
SELECT Customers.*, Orders.* FROM Customers LEFT OUTER JOIN Orders ON Customers.CustomerID
=Orders.CustomerID

RIGHT OUTER JOIN
Right join will display all records in right table of the SQL statement. In SQL below all orders with or
without matching customer records will be displayed. Customer data for orders without customers
appears as NULL values. For example, you want to determine if there are any orders in the data with
undefined CustomerID values (say, after a conversion or something like it). You can also see the
RIGHT OUTER JOIN as a mirror image of the LEFT OUTER JOIN if you switch the side of each table.
SELECT Customers.*, Orders.* FROM Customers RIGHT OUTER JOIN Orders ON
Customers.CustomerID =Orders.CustomerID

Questions
: 20
What is "CROSS JOIN"? or What is Cartesian product?
nswers :
20
"CROSS JOIN or "CARTESIAN PRODUCT combines all rows from both tables. Number of rows will be
product of the number of rows in each table. In real life scenario I can not imagine where we will want
to use a Cartesian product. But there are scenarios where we would like permutation and combination
probably Cartesian would be the easiest way to achieve it.

Questions
: 21
How to select the first record in a given set of rows?
nswers :
21
Select top 1 * from sales.salesperson

Questions
: 22
What is the default "-SORT " order for a SQL?
nswers :
22
ASCENDING

Questions
: 23
What is a self-join?
nswers :
23
If we want to join two instances of the same table we can use self-join.

Questions What's the difference between DELETE and TRUNCTE ?
: 24
nswers :
24
Following are difference between them:
=>>DELETE TABLE syntax logs the deletes thus making the delete operations low. TRUNCATE table
does not log any information but it logs information about deallocation of data page of the table. So
TRUNCATE table is faster as compared to delete table.
=>>DELETE table can have criteria while TRUNCATE can not.
=>> TRUNCATE table can not have triggers.

Questions
: 25
What's the difference between "UNION" and "UNION LL" ?
nswers :
25
UNION SQL syntax is used to select information from two tables. But it selects only distinct records
from both the table. , while UNION ALL selects all records from both the tables.

Questions
: 26
What are cursors and what are the situations you will use them?
nswers :
26
SQL statements are good for set at a time operation. So it is good at handling set of data. But there
are scenarios where we want to update row depending on certain criteria. we will loop through all
rows and update data accordingly. Theres where cursors come in to picture.

Questions
: 27
What is " Group by " clause?
nswers :
27
"Group by clause group similar data so that aggregate values can be derived.

Questions
: 28
What is the difference between "HVING" and "WHERE" clause?
nswers :
28
"HAVING clause is used to specify filtering criteria for "GROUP BY, while "WHERE clause applies on
normal SQL.

Questions
: 29
What is a Sub-Query?
nswers :
29
A query nested inside a SELECT statement is known as a subquery and is an alternative to complex
join statements. A subquery combines data from multiple tables and returns results that are inserted
into the WHERE condition of the main query. A subquery is always enclosed within parentheses and
returns a column. A subquery can also be referred to as an inner query and the main query as an
outer query. JOIN gives better performance than a subquery when you have to check for the
existence of records.
For example, to retrieve all EmployeeID and CustomerID records from the ORDERS table that have
the EmployeeID greater than the average of the EmployeeID field, you can create a nested query, as
shown:
SELECT DISTINCT EmployeeID, CustomerID FROM ORDERS WHERE EmployeeID > (SELECT
AVG(EmployeeID) FROM ORDERS)

Questions
: 30
What are ggregate and Scalar Functions?
nswers :
30
Aggregate and Scalar functions are in built function for counting and calculations.
Aggregate functions operate against a group of values but returns only one value.
AVG(column) :- Returns the average value of a column
COUNT(column) :- Returns the number of rows (without a NULL value) of a column
COUNT(*) :- Returns the number of selected rows
MAX(column) :- Returns the highest value of a column
MIN(column) :- Returns the lowest value of a column
Scalar functions operate against a single value and return value on basis of the single value.
UCASE(c) :- Converts a field to upper case
LCASE(c) :- Converts a field to lower case
MID(c,start[,end]) :- Extract characters from a text field
LEN(c) :- Returns the length of a text

Questions
: 31
Can you explain the SELECT INTO Statement?
nswers :
31
SELECT INTO statement is used mostly to create backups. The below SQL backsup the Employee table
in to the EmployeeBackUp table. One point to be noted is that the structure of pcdsEmployeeBackup
and pcdsEmployee table should be same. SELECT * INTO pcdsEmployeeBackup FROM pcdsEmployee

Questions
: 32
What is a View?
nswers :
32
View is a virtual table which is created on the basis of the result set returned by the select statement.
CREATE VIEW [MyView] AS SELECT * from pcdsEmployee where LastName = 'singh'
In order to query the view
SELECT * FROM [MyView]

Questions
: 33
What is SQl injection ?
nswers :
33
It is a Form of attack on a database-driven Web site in which the attacker executes unauthorized SQL
commands by taking advantage of insecure code on a system connected to the Internet, bypassing
the firewall. SQL injection attacks are used to steal information from a database from which the data
would normally not be available and/or to gain access to an organizations host computers through
the computer that is hosting the database.
SQL injection attacks typically are easy to avoid by ensuring that a system has strong input validation.
As name suggest we inject SQL which can be relatively dangerous for the database. Example this is a
simple SQL
SELECT email, passwd, login_id, full_name
FROM members WHERE email = 'x'
Now somebody does not put "x as the input but puts "x ; DROP TABLE members;.
So the actual SQL which will execute is :-
SELECT email, passwd, login_id, full_name FROM members WHERE email = 'x' ; DROP TABLE
members;
Think what will happen to your database.

Questions
: 34
What is Data Warehousing ?
nswers :
34
Data Warehousing is a process in which the data is stored and accessed from central location and is
meant to support some strategic decisions. Data Warehousing is not a requirement for Data mining.
But just makes your Data mining process more efficient.
Data warehouse is a collection of integrated, subject-oriented databases designed to support the
decision-support functions (DSF), where each unit of data is relevant to some moment in time.

Questions
: 35
What are Data Marts?
nswers :
35
Data Marts are smaller section of Data Warehouses. They help data warehouses collect data. For
example your company has lot of branches which are spanned across the globe. Head-office of the
company decides to collect data from all these branches for anticipating market. So to achieve this IT
department can setup data mart in all branch offices and a central data warehouse where all data will
finally reside.

Questions
: 36
What are Fact tables and Dimension Tables ? What is Dimensional Modeling and Star
Schema Design
nswers :
36
When we design transactional database we always think in terms of normalizing design to its least
form. But when it comes to designing for Data warehouse we think more in terms of denormalizing
the database. Data warehousing databases are designed using Dimensional Modeling. Dimensional
Modeling uses the existing relational database structure and builds on that.
There are two basic tables in dimensional modeling:-
Fact Tables.
Dimension Tables.
Fact tables are central tables in data warehousing. Fact tables have the actual aggregate values which
will be needed in a business process. While dimension tables revolve around fact tables. They describe
the attributes of the fact tables.

Questions
: 37
What is Snow Flake Schema design in database? What's the difference between Star and
Snow flake schema?
nswers :
37
Star schema is good when you do not have big tables in data warehousing. But when tables start
becoming really huge it is better to denormalize. When you denormalize star schema it is nothing but
snow flake design. For instance below customeraddress table is been normalized and is a child table of
Customer table. Same holds true for Salesperson table.

Questions
: 38
What is ETL process in Data warehousing? What are the different stages in "Data
warehousing"?
nswers :
38
ETL (Extraction, Transformation and Loading) are different stages in Data warehousing. Like when we
do software development we follow different stages like requirement gathering, designing, coding and
testing. In the similar fashion we have for data warehousing.
Extraction:-
In this process we extract data from the source. In actual scenarios data source can be in many forms
EXCEL, ACCESS, Delimited text, CSV (Comma Separated Files) etc. So extraction process handles the
complexity of understanding the data source and loading it in a structure of data warehouse.
Transformation:-
This process can also be called as cleaning up process. Its not necessary that after the extraction
process data is clean and valid. For instance all the financial figures have NULL values but you want it
to be ZERO for better analysis. So you can have some kind of stored procedure which runs through all
extracted records and sets the value to zero.
Loading:-
After transformation you are ready to load the information in to your final data warehouse database.

Questions
: 39
What is Data mining ?
nswers :
39
Data mining is a concept by which we can analyze the current data from different perspectives and
summarize the information in more useful manner. Its mostly used either to derive some valuable
information from the existing data or to predict sales to increase customer market.
There are two basic aims of Data mining:-

Prediction: -
From the given data we can focus on how the customer or market will perform. For instance we are
having a sale of 40000 $ per month in India, if the same product is to be sold with a discount how
much sales can the company expect.
Summarization: -
To derive important information to analyze the current business scenario. For example a weekly sales
report will give a picture to the top management how we are performing on a weekly basis?

Questions
: 40
Compare Data mining and Data Warehousing ?
nswers :
40
"Data Warehousing is technical process where we are making our data centralized while "Data
mining is more of business activity which will analyze how good your business is doing or predict how
it will do in the future coming times using the current data. As said before "Data Warehousing is not
a need for "Data mining. Its good if you are doing "Data mining on a "Data Warehouse rather than
on an actual production database. "Data Warehousing is essential when we want to consolidate data
from different sources, so its like a cleaner and matured data which sits in between the various data
sources and brings then in to one format. "Data Warehouses are normally physical entities which are
meant to improve accuracy of "Data mining process. For example you have 10 companies sending
data in different format, so you create one physical database for consolidating all the data from
different company sources, while "Data mining can be a physical model or logical model. You can
create a database in "Data mining which gives you reports of net sales for this year for all
companies. This need not be a physical database as such but a simple query.

Questions
: 41
What are indexes? What are B-Trees?
nswers :
41
Index makes your search faster. So defining indexes to your database will make your search
faster.Most of the indexing fundamentals use "B-Tree or "Balanced-Tree principle. Its not a principle
that is something is created by SQL Server or ORACLE but is a mathematical derived fundamental.In
order that "B-tree fundamental work properly both of the sides should be balanced.

Questions
: 42
I have a table which has lot of inserts, is it a good database design to create indexes on
that table?
Insert's are slower on tables which have indexes, justify it?or Why do page splitting
happen?
nswers :
42
All indexing fundamentals in database use "B-tree fundamental. Now whenever there is new data
inserted or deleted the tree tries to become unbalance.
Creates a new page to balance the tree.
Shuffle and move the data to pages.
So if your table is having heavy inserts that means its transactional, then you can visualize the
amount of splits it will be doing. This will not only increase insert time but will also upset the end-user
who is sitting on the screen. So when you forecast that a table has lot of inserts its not a good idea to
create indexes.

Questions
: 43
What are the two types of indexes and explain them in detail? or What's the difference
between clustered and non-clustered indexes?
nswers :
43
There are basically two types of indexes:-
Clustered Indexes.
Non-Clustered Indexes.
In clustered index the non-leaf level actually points to the actual data.In Non-Clustered index the leaf
nodes point to pointers (they are rowids) which then point to actual data.
Mysql interview questions and answers are below
'
Questions
: 1
how to do login in mysql with unix shell
nswers
:1
By below method if password is pass and user name is root
# [mysql dir]/bin/mysql -h hostname -u root -p pass

Questions
: 2
how you will Create a database on the mysql server with unix shell
nswers :
2
mysql> create database databasename;

Questions
: 3
how to list or view all databases from the mysql server.
nswers :
3
mysql> show databases;

Questions
: 4
How Switch (select or use) to a database.
nswers :
4
mysql> use databasename;

Questions
: 5
How To see all the tables from a database of mysql server.
nswers :
5
mysql> show tables;

Questions
: 6
How to see table's field formats or description of table .
nswers :
6
mysql> describe tablename;

Questions
: 7
How to delete a database from mysql server.
nswers :
7
mysql> drop database databasename;

Questions
: 8
How we get Sum of column
nswers :
8
mysql> SELECT SUM(*) FROM [table name];

Questions
: 9
How to delete a table
nswers :
9
mysql> drop table tablename;

Questions
: 10
How you will Show all data from a table.
nswers :
10
mysql> SELECT * FROM tablename;

Questions
: 11
How to returns the columns and column information pertaining to the
designated table
nswers :
11
mysql> show columns from tablename;

Questions
: 12
How to Show certain selected rows with the value "pcds"
nswers :
12
mysql> SELECT * FROM tablename WHERE fieldname = "pcds";

Questions
: 13
How will Show all records containing the name "sonia" ND the phone
number '9876543210'
nswers :
13
mysql> SELECT * FROM tablename WHERE name = "sonia" AND phone_number =
'9876543210';

Questions
: 14
How you will Show all records not containing the name "sonia" ND the
phone number '9876543210' order by the phone_number field.
nswer :
14
mysql> SELECT * FROM tablename WHERE name != "sonia" AND phone_number =
'9876543210' order by phone_number;

Questions
: 15
How to Show all records starting with the letters 'sonia' ND the phone
number '9876543210'
nswers :
15
mysql> SELECT * FROM tablename WHERE name like "sonia%" AND phone_number
= '9876543210';

Questions
: 16
How to show all records starting with the letters 'sonia' ND the phone
number '9876543210' limit to records 1 through 5.
nswers :
16
mysql> SELECT * FROM tablename WHERE name like "sonia%" AND phone_number
= '9876543210' limit 1,5;

Questions
: 16
Use a regular expression to find records. Use "REGEXP BINRY" to force
case-sensitivity. This finds any record beginning with r.
nswer :
16
mysql> SELECT * FROM tablename WHERE rec RLIKE "^r";

Questions
: 17
How you will Show unique records.
nswer :
17
mysql> SELECT DISTINCT columnname FROM tablename;

Questions
: 18
how we will Show selected records sorted in an ascending (asc) or
descending (desc)
nswer :
18
mysql> SELECT col1,col2 FROM tablename ORDER BY col2 DESC;

mysql> SELECT col1,col2 FROM tablename ORDER BY col2 ASC;

Questions
: 19
how to Return total number of rows.
nswers :
19
mysql> SELECT COUNT(*) FROM tablename;

Questions
: 20
How to Join tables on common columns.
nswer :
20
mysql> select lookup.illustrationid, lookup.personid,person.birthday from lookup left
join person on lookup.personid=person.personid=statement to join birthday in person
table with primary illustration id

Questions
: 21
How to Creating a new user. Login as root. Switch to the MySQL db. Make the
user. Update privs.
nswer :
21
# mysql -u root -p

mysql> use mysql;

mysql> INSERT INTO user (Host,User,Password)
VALUES('%','username',PASSWORD('password'));

mysql> flush privileges;

Questions
: 22
How to Change a users password from unix shell.
nswers :
22
# [mysql dir]/bin/mysqladmin -u username -h hostname.blah.org -p password 'new-
password'

Questions
: 23
How to Change a users password from MySQL prompt. Login as root. Set the
password. Update privs.
nswer :
# mysql -u root -p
23
mysql> SET PASSWORD FOR 'user'@'hostname' = PASSWORD('passwordhere');

mysql> flush privileges;

Questions
: 24
How to Recover a MySQL root password. Stop the MySQL server process.
Start again with no grant tables. Login to MySQL as root. Set new password.
Exit MySQL and restart MySQL server.
nswer :
24
# /etc/init.d/mysql stop
# mysqld_safe --skip-grant-tables &
# mysql -u root
mysql> use mysql;
mysql> update user set password=PASSWORD("newrootpassword") where
User='root';
mysql> flush privileges;
mysql> quit
# /etc/init.d/mysql stop
# /etc/init.d/mysql start

Questions
: 25
How to Set a root password if there is on root password.
nswer :
25
# mysqladmin -u root password newpassword

Questions
: 26
How to Update a root password.
nswer :
26
# mysqladmin -u root -p oldpassword newpassword

Questions
: 27
How to allow the user "sonia" to connect to the server from localhost using
the password "passwd". Login as root. Switch to the MySQL db. Give privs.
Update privs.
nswers :
27
# mysql -u root -p
mysql> use mysql;
mysql> grant usage on *.* to sonia@localhost identified by 'passwd';
mysql> flush privileges;

Questions
: 28
How to give user privilages for a db. Login as root. Switch to the MySQL db.
Grant privs. Update privs.
nswers :
28
# mysql -u root -p
mysql> use mysql;
mysql> INSERT INTO user
(Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv)
VALUES ('%','databasename','username','Y','Y','Y','Y','Y','N');
mysql> flush privileges;
or
mysql> grant all privileges on databasename.* to username@localhost;
mysql> flush privileges;

Questions
: 29
How To update info already in a table and Delete a row(s) from a table.
nswer :
29
mysql> UPDATE [table name] SET Select_priv = 'Y',Insert_priv = 'Y',Update_priv =
'Y' where [field name] = 'user';
mysql> DELETE from [table name] where [field name] = 'whatever';

Questions How to Update database permissions/privilages.
: 30
nswer :
30
mysql> flush privileges;

Questions
: 31
How to Delete a column and dd a new column to database
nswer :
31
mysql> alter table [table name] drop column [column name];
mysql> alter table [table name] add column [new column name] varchar (20);

Questions
: 32
Change column name and Make a unique column so we get no dupes.
nswer :
32
mysql> alter table [table name] change [old column name] [new column name]
varchar (50);
mysql> alter table [table name] add unique ([column name]);

Questions
: 33
How to make a column bigger and Delete unique from table.
nswer :
33
mysql> alter table [table name] modify [column name] VARCHAR(3);
mysql> alter table [table name] drop index [colmn name];

Questions
: 34
How to Load a CSV file into a table
nswer :
34
mysql> LOAD DATA INFILE '/tmp/filename.csv' replace INTO TABLE [table name]
FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (field1,field2,field3);

Questions
: 35
How to dump all databases for backup. Backup file is sql commands to
recreate all db's.
nswer :
35
# [mysql dir]/bin/mysqldump -u root -ppassword --opt >/tmp/alldatabases.sql

Questions
: 36
How to dump one database for backup.
nswer :
36
# [mysql dir]/bin/mysqldump -u username -ppassword --databases databasename
>/tmp/databasename.sql

Questions
: 37
How to dump a table from a database.
nswer :
37
# [mysql dir]/bin/mysqldump -c -u username -ppassword databasename tablename
> /tmp/databasename.tablename.sql

Questions
: 38
Restore database (or database table) from backup.
nswer :
38
# [mysql dir]/bin/mysql -u username -ppassword databasename <
/tmp/databasename.sql

Questions
: 39
How to Create Table show Example
nswer :
39
mysql> CREATE TABLE [table name] (firstname VARCHAR(20), middleinitial
VARCHAR(3), lastname VARCHAR(35),suffix VARCHAR(3),officeid
VARCHAR(10),userid VARCHAR(15),username VARCHAR(8),email
VARCHAR(35),phone VARCHAR(25), groups VARCHAR(15),datestamp
DATE,timestamp time,pgpemail VARCHAR(255));
Questions
: 40
How to search second maximum(second highest) salary value(integer)from
table employee (field salary)in the manner so that mysql gets less load?
nswers :
40
By below query we will get second maximum(second highest) salary
value(integer)from table employee (field salary)in the manner so that mysql gets less
load?
SELECT DISTINCT(salary) FROM employee order by salary desc limit 1 , 1 ;
(This way we will able to find out 3rd highest , 4th highest salary so on just need to
change limit condtion like LIMIT 2,1 for 3rd highest and LIMIT 3,1 for 4th
some one may finding this way useing below query that taken more time as compare
to above query SELECT salary FROM employee where salary < (select max(salary)
from employe) order by salary DESC limit 1 ;
Mysql interview questions and answers are below
'
Questions
: 1
how to do login in mysql with unix shell
nswers
:1
By below method if password is pass and user name is root
# [mysql dir]/bin/mysql -h hostname -u root -p pass

Questions
: 2
how you will Create a database on the mysql server with unix shell
nswers :
2
mysql> create database databasename;

Questions
: 3
how to list or view all databases from the mysql server.
nswers :
3
mysql> show databases;

Questions
: 4
How Switch (select or use) to a database.
nswers :
4
mysql> use databasename;

Questions
: 5
How To see all the tables from a database of mysql server.
nswers :
5
mysql> show tables;

Questions
: 6
How to see table's field formats or description of table .
nswers :
6
mysql> describe tablename;

Questions
: 7
How to delete a database from mysql server.
nswers :
7
mysql> drop database databasename;

Questions
: 8
How we get Sum of column
nswers :
8
mysql> SELECT SUM(*) FROM [table name];

Questions
: 9
How to delete a table
nswers :
9
mysql> drop table tablename;

Questions
: 10
How you will Show all data from a table.
nswers :
10
mysql> SELECT * FROM tablename;

Questions
: 11
How to returns the columns and column information pertaining to the
designated table
nswers :
11
mysql> show columns from tablename;

Questions
: 12
How to Show certain selected rows with the value "pcds"
nswers :
12
mysql> SELECT * FROM tablename WHERE fieldname = "pcds";

Questions
: 13
How will Show all records containing the name "sonia" ND the phone
number '9876543210'
nswers :
13
mysql> SELECT * FROM tablename WHERE name = "sonia" AND phone_number =
'9876543210';

Questions
: 14
How you will Show all records not containing the name "sonia" ND the
phone number '9876543210' order by the phone_number field.
nswer :
14
mysql> SELECT * FROM tablename WHERE name != "sonia" AND phone_number =
'9876543210' order by phone_number;

Questions
: 15
How to Show all records starting with the letters 'sonia' ND the phone
number '9876543210'
nswers :
15
mysql> SELECT * FROM tablename WHERE name like "sonia%" AND phone_number
= '9876543210';

Questions
: 16
How to show all records starting with the letters 'sonia' ND the phone
number '9876543210' limit to records 1 through 5.
nswers :
16
mysql> SELECT * FROM tablename WHERE name like "sonia%" AND phone_number
= '9876543210' limit 1,5;

Questions
: 16
Use a regular expression to find records. Use "REGEXP BINRY" to force
case-sensitivity. This finds any record beginning with r.
nswer :
16
mysql> SELECT * FROM tablename WHERE rec RLIKE "^r";

Questions
: 17
How you will Show unique records.
nswer :
17
mysql> SELECT DISTINCT columnname FROM tablename;

Questions
: 18
how we will Show selected records sorted in an ascending (asc) or
descending (desc)
nswer :
18
mysql> SELECT col1,col2 FROM tablename ORDER BY col2 DESC;

mysql> SELECT col1,col2 FROM tablename ORDER BY col2 ASC;

Questions
: 19
how to Return total number of rows.
nswers :
19
mysql> SELECT COUNT(*) FROM tablename;

Questions
: 20
How to Join tables on common columns.
nswer :
20
mysql> select lookup.illustrationid, lookup.personid,person.birthday from lookup left
join person on lookup.personid=person.personid=statement to join birthday in person
table with primary illustration id

Questions
: 21
How to Creating a new user. Login as root. Switch to the MySQL db. Make the
user. Update privs.
nswer :
21
# mysql -u root -p

mysql> use mysql;

mysql> INSERT INTO user (Host,User,Password)
VALUES('%','username',PASSWORD('password'));

mysql> flush privileges;

Questions
: 22
How to Change a users password from unix shell.
nswers :
22
# [mysql dir]/bin/mysqladmin -u username -h hostname.blah.org -p password 'new-
password'

Questions
: 23
How to Change a users password from MySQL prompt. Login as root. Set the
password. Update privs.
nswer :
23
# mysql -u root -p

mysql> SET PASSWORD FOR 'user'@'hostname' = PASSWORD('passwordhere');

mysql> flush privileges;

Questions
: 24
How to Recover a MySQL root password. Stop the MySQL server process.
Start again with no grant tables. Login to MySQL as root. Set new password.
Exit MySQL and restart MySQL server.
nswer :
24
# /etc/init.d/mysql stop
# mysqld_safe --skip-grant-tables &
# mysql -u root
mysql> use mysql;
mysql> update user set password=PASSWORD("newrootpassword") where
User='root';
mysql> flush privileges;
mysql> quit
# /etc/init.d/mysql stop
# /etc/init.d/mysql start

Questions
: 25
How to Set a root password if there is on root password.
nswer :
25
# mysqladmin -u root password newpassword

Questions
: 26
How to Update a root password.
nswer :
26
# mysqladmin -u root -p oldpassword newpassword

Questions
: 27
How to allow the user "sonia" to connect to the server from localhost using
the password "passwd". Login as root. Switch to the MySQL db. Give privs.
Update privs.
nswers :
27
# mysql -u root -p
mysql> use mysql;
mysql> grant usage on *.* to sonia@localhost identified by 'passwd';
mysql> flush privileges;

Questions
: 28
How to give user privilages for a db. Login as root. Switch to the MySQL db.
Grant privs. Update privs.
nswers :
28
# mysql -u root -p
mysql> use mysql;
mysql> INSERT INTO user
(Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv)
VALUES ('%','databasename','username','Y','Y','Y','Y','Y','N');
mysql> flush privileges;
or
mysql> grant all privileges on databasename.* to username@localhost;
mysql> flush privileges;

Questions
: 29
How To update info already in a table and Delete a row(s) from a table.
nswer :
29
mysql> UPDATE [table name] SET Select_priv = 'Y',Insert_priv = 'Y',Update_priv =
'Y' where [field name] = 'user';
mysql> DELETE from [table name] where [field name] = 'whatever';

Questions
: 30
How to Update database permissions/privilages.
nswer :
30
mysql> flush privileges;

Questions
: 31
How to Delete a column and dd a new column to database
nswer :
31
mysql> alter table [table name] drop column [column name];
mysql> alter table [table name] add column [new column name] varchar (20);

Questions
: 32
Change column name and Make a unique column so we get no dupes.
nswer :
32
mysql> alter table [table name] change [old column name] [new column name]
varchar (50);
mysql> alter table [table name] add unique ([column name]);

Questions How to make a column bigger and Delete unique from table.
: 33
nswer :
33
mysql> alter table [table name] modify [column name] VARCHAR(3);
mysql> alter table [table name] drop index [colmn name];

Questions
: 34
How to Load a CSV file into a table
nswer :
34
mysql> LOAD DATA INFILE '/tmp/filename.csv' replace INTO TABLE [table name]
FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (field1,field2,field3);

Questions
: 35
How to dump all databases for backup. Backup file is sql commands to
recreate all db's.
nswer :
35
# [mysql dir]/bin/mysqldump -u root -ppassword --opt >/tmp/alldatabases.sql

Questions
: 36
How to dump one database for backup.
nswer :
36
# [mysql dir]/bin/mysqldump -u username -ppassword --databases databasename
>/tmp/databasename.sql

Questions
: 37
How to dump a table from a database.
nswer :
37
# [mysql dir]/bin/mysqldump -c -u username -ppassword databasename tablename
> /tmp/databasename.tablename.sql

Questions
: 38
Restore database (or database table) from backup.
nswer :
38
# [mysql dir]/bin/mysql -u username -ppassword databasename <
/tmp/databasename.sql

Questions
: 39
How to Create Table show Example
nswer :
39
mysql> CREATE TABLE [table name] (firstname VARCHAR(20), middleinitial
VARCHAR(3), lastname VARCHAR(35),suffix VARCHAR(3),officeid
VARCHAR(10),userid VARCHAR(15),username VARCHAR(8),email
VARCHAR(35),phone VARCHAR(25), groups VARCHAR(15),datestamp
DATE,timestamp time,pgpemail VARCHAR(255));
Questions
: 40
How to search second maximum(second highest) salary value(integer)from
table employee (field salary)in the manner so that mysql gets less load?
nswers :
40
By below query we will get second maximum(second highest) salary
value(integer)from table employee (field salary)in the manner so that mysql gets less
load?
SELECT DISTINCT(salary) FROM employee order by salary desc limit 1 , 1 ;
(This way we will able to find out 3rd highest , 4th highest salary so on just need to
change limit condtion like LIMIT 2,1 for 3rd highest and LIMIT 3,1 for 4th
some one may finding this way useing below query that taken more time as compare
to above query SELECT salary FROM employee where salary < (select max(salary)
from employe) order by salary DESC limit 1 ;

You might also like