Anda di halaman 1dari 271

1

HTML
HTML is a not a scripting language or programming language
But it is a simply markup language .this markup language with the pair of markup tags. The first
Tag is known as opening tag (or) starting tag. The second tag is known as closing (or) end tag.
HTML are used to describe the web pages
HTML can be written in notepad, notepad++, dream viewer, adov and cs5
HTML file can be saved with .html as its extension
The look end of an web page should be same on the all browsers. If it is not same the cross
browser compatibility

Tags in html: Heading tags are h1, h2...h6


Ex: - <h1>welcome to html</h1>
.
.
<h6> welcome to html</h6>
<hr>: - this tag is used for horizontal line
<br>: - this tag is used for break
<p>: - this tag is used for paragraph content
<b>: - this tag is used for bold content
<i>: - this tag is used for italic content
<link>: - this tag is used for connect the style sheets
<script>: - this tag is used for JavaScript
<big>: - this tag is used for big content
<strong>: - this tag is used for strong content
<blink>: - this tag is used for blink content

<del>: - this tag is used for delete the content


<strike>: - this tag is used for strike
<u>: - this tag is used for underline content
<ins>: - this tag is used for insert content
<q>: - this tag is used for quotation content
<sup>: - this tag is used for super content
Ex: - (a+b) <sup> 2</sup>
<sub>: - this tag is used for subscript content
Ex: - h<sub>2</sub>o
Entities: Entities are used to describe the symbols (or) special characters on to the web page. We have
certain symbols are not available on the keyboard. So such symbols can be inserting through
entities. We have mainly two types of entities they are
1. Named Entity
2. Number Entity
1. Named Entity: Syntax: - Ampersand + entity name + semicolon
Ex: -&dollar;
2. Number Entity: Syntax: - Ampersand + hash + ascci value+ semicolon
Ex: - &#65; =>A
&#153; =>Trademark: tm
List Tags: List tags are two types
1. Order list: - Grouping of elements in the form of order wise through number, upper alpha
(A) lower alpha (a), upper roman, lower roman is known as order list
Ex: - Order list.html

<html>
<head>
<title>List Tags</title>
</head>
<body>
<h3>Ordered List</h3>
<ol type='a' start='25'>
<li>Nokia</li>
<li>Mototola</li>
<li>LG-Mobile</li>
<li>Sony</li>
</ol>
</body>
</html>
2. Unorder list: - Grouping of elements in the form of disk, square circle are known as unorder
list
Ex: - unorder list.html
<html>
<head>
<title>List Tags</title>
</head>
<body>
<h3>Unordered List</h3>
<ul type='square'>
<li>PHP</li>
<li>HTML</li>
<li>JOOMLA</li>

<li>MySQL</li>
</ul>
<hr>
<h3>Defination List</h3>
<dl>
<dt>Terms & Conditions</dt>
<dd><small><small>some large text matter write here </small></small></dd>
</dl>
</body>
</html>
Definition list: - this is used to maintain the heading the description on to the <dl> tag this is dl
Definition term: - definition term creates the heading
Definition description: -which holds to the description of the content this is dd
Dt and dd tags are both child tags of DL
Meta tag: - Meta tag is used generate the traffic on to your web page. Meta tags can be embed
into the head tag using Meta tag
Meta tag helps in search engine ranking on Google page and PTC(pay to click)
Ex: - Meta.html
<html>
<head>
<title>Meta Tags</title>
<meta name='keyword'
content='PHP,HTML,JQUERY,CSS,HYDERABAD,Institute,Ameerpet'/>
<meta name='description' content='We been in lamp for more than 8years and trained many
student ... many have got jobs in PHP ...'/>
<meta http-equiv='refresh' content='5;url=http://www.axis-bank.com'/>
</head>

<body>
<h2>We have changed our Website Name from UTI Bank to AXIS Bank ... Sorry for
incontinent Please wait for 5 sec it would be Automatically be Redirected</h2>
</body>
</html>
Link tags: - links are used to navigate from one page to another page using inter (or) external
links
The attributes we can pass are
Target = -blank // new web page
Target = -new

// new web page

Target = -self

// open on same page

Links can also we target to mails and also we search the link on same page
Ex: - linktag.html
<html>
<head>
<title>Link Tags</title>
</head>
<body>
<h3>Links Navigation</h3>
<a href='http://www.google.com' target="_blank">Google page</a> ||
<a href='http://www.facebook.com' target='_self'>Facebook Page</a> ||
<a href='Tags.html' target="_new"> Tags Content</a>
<hr>
<h3>Mail Concept</h3>
<a href='mailto:admin@gmail.com'>Contact Us</a><br>
<a href='mailto:admin@gmail.com,admin4@gmail.com?
cc=admin2@gmail.com&bcc=admin3@gmail.com&subject=Please Rectify my
Issue&body=Not resolved Raise the Ticket'>Contact Support & Admin</a>

<hr>
<h3>Navigating to Search the Link</h3>
<h1><a name='top'>FAQ</a></h1>
<a href='#q1'>what is html ?</a><br>
<a href='#q2'>what is php ?</a><br>
<a href='#q3'>what is joomla ?</a><br>
<a href='#q4'>what is ajax ?</a><br>
<a href='#q5'>what is mysql ?</a><br>
<a href='#q6'>what is jquery ?</a><br>
<a href='#q7'>what is java script ?</a><br>
<hr>
<p><b><a name='q1'>Answer 01: </a></b> write here some large text matter
<a href='#top'>Back to Top</a>
</p>
<p><b><a name='q2'>Answer 02: </a></b> write here some large text matter
<a href='#top'>Back to Top</a>
</p>
<p><b><a name='q3'>Answer 03: </a></b>write here some large text matter</p>
<p><b><a name='q4'>Answer 04: </a></b>write here some large text matter </p>
<p><b><a name='q5'>Answer 05: </a></b> write here some large text matter</p>
</body>
</html>
Image tags: - images can be embed into the body tag using image tag. Images have extension
of jpg, png, gif etc
Placing on image on to the web page can be done by two types they are
1. Absolute path: - working from the working directory you can call the image from any ware
with respect its parent directory (or) out of the parent directory (or) external files

Ex:<html>
<head>
<title>image tags</title>
</head>
<body>
<h3><center>image tags</center></h3>
<h2>absolute path</h2>
<img src = http://www.google.com/images/mountain.jpg alt = beautiful border = 10 width
= 200px height = 180px;>
</body>
2. Relative path: - using relative path you can work with images on to the same current
working directory (or) sub folders did not out of your parent directory
Ex: <html>
<head>
<title>image tags</title>
</head>
<body>
<h3><center>image tags</center></h3>
<h2>relation tags</h2>
<img src="suresh.jpg" width='140px' height='150px' border='0' title='suresh'>
<img src="DSC_0100.jpg" width='200px' height='180px' border='3' title='suresh'><br>
<img src="../water lilies.jpg" width='200px' height='180px' border='3' title='suresh'>
<img src="../../sunset.jpg" width='200px' height='180px' border='3' title='suresh'><br>
<img src="new folder/dsc_0083.jpg" width='200px' height='180px' border='3' title='suresh'>
</body>

</html>
Tables create: - tables are used to put down content in tabular structure. Table tag can be embed
into your body tag using
<table>
<tr> table row</tr>
<td> table data (or) content</td>
</table>
The general attributes that we can pass in tables are
Border = <num>
Width = <num>
Height = <num>
Cell padding = <num>
Cell spacing = <num>
Align = left/center/right
Background = image path
Fames = box/group/lhs/rhs/above/below/vsides/hsides
Rules = all/middle/bottom
Colspan =<num>
Rowspan = <num>
Bgcolor = color name
Ex: <html>
<head>
<title>table creat</title>
</head>
<body>
<table border = 1 align = center width = 70%>
<tr>
<td>employee detailsl</td>
</tr>
<table>
<tr>

10

<td>s.no</td><td>Name</td><td>designation</td>
</tr>
<tr>
<td>1</td><td>suresh</td><td>php programmer</td>
</tr>
</body>
</html>
Cell padding: - cell padding is used to maintain the distance between its content and from its
wall (or) border
Cell spacing: - cell spacing is used to increase the wall (or) the border
Frame set: - frame set we can divide the body into no of divisions that are passed as an
argument based on rows (or) cols working with frame set you should ensure that body tag in not
given
Note: - frame set is a depreciated tag and would be working with feature versions
Ex: <html>
<head>
<title>Frameset Tags</title>
</head>
<frameset cols='30%,25%,*'>
<frame src = 'links.html' scrolling='no' >
<frame src = 'entities.html' >
<frame src = 'list.html' >
</frameset>
</html>
Iframes: Ex: -

11

<html>
<head>
<title>Iframes Tags</title>
</head>
<body>
<p align='center'><a href='list.html' target='x'>List Page</a> | <a href='links.html'
target='x'>Links Page</a><br><br>
<iframe src='list.html' name='x' width='600px' height='200px' ></iframe></p>
</body>
</html>
Created registration form: - registration.html
<html>
<head>
<title>Register Form</title>
</head>
<body>
<form name='testForm' enctype='multipart/form-data'/>
<table align='center' border='1' cellpadding='5px' width='60%' cellspacing='0' frame='box'
rules='rows'>
<tr><th colspan='3'>New Registration Form</th></tr>
<tr>
<td>First name</td><td>:</td><td><input type='text' name='fname' id='Fldfname'
value='Rajesh' readonly></td>
</tr>
<tr>
<td>E-Mail</td><td>:</td><td><input type='text' value='type email' name='email'
id='Fldemail'></td></tr>
<tr>

12

<td>Password</td><td>:</td><td><input type='password' name='pwd' id='Fldpwd'></td></tr>


<tr>
<td><label for='Fldcpwd'>Confirm Password</label></td><td>:</td><td><input
type='password' name='cpwd' id='Fldcpwd'></td></tr>
<tr>
<td>Gender *</td><td>:</td><td><input type='radio' name='gender' checked value='m'
id='Fldgendm'/> <label for='Fldgendm'>Male</label> <input type='radio' name='gender'
value='f' id='Fldgendf'/> <label for='Fldgendf'>Female</label> </td>
</tr>
<tr>
<td>Hobbies</td><td>:</td><td><input type='checkbox' name='hobb[]' value='p'
id='Fldhobbp'/> Playing <input type='checkbox' name='hobb[]' value='r' i8d='Fldhobbr'/>
Reading <input type='checkbox' name='hobb[]' value='s' id='Fldhobbs' disabled /> Singing</td>
<tr>
<td>Country</td><td>:</td><td><select name='country'>
<option value=''>Please select</option>
<option value='91'>INDIA</option>
<option value='001'>USA</option>
<option value='215'>United Kingdom</option>
</select></td>
</tr>
<tr>
<td>Address</td><td>:</td><td><textarea name='addr' rows='5'
cols='30'></textarea></td></tr>
<tr>
<td>Image Upload</td><td>:</td><td><input type='file' name='img' size='16'
id='Fldimg'/></td></tr>
<tr>
<td colspan='3' align='right'>

13

<input type='submit' name='submit' value='Register'> <input type='reset' name='refresh'


value='Cancel'/>
</td>
</tr>
</table>
</form>
</body>
</html>

14

15

Css
Css stands for cascading style sheet. Css is used to put some styles (or) colors on to the web
page. Css can be embed into the html head tag using style tag. There are mainly 3 different
flavors to attach this style on to the web page. Which are mainly
1. Internal style sheet
2. External style sheet
3. in-line style sheet
1. Internal style sheet: An internal style sheet should be used when a single document has a unique style. You define
internal styles in the head section of an HTML page, by using the <style> tag, like this:
<head>
<style type="text/css">
hr {color:sienna;}
p {margin-left:20px;}
body {background-image:url("images/back40.gif");}
</style>
</head>
2. External style sheet: An external style sheet is ideal when the style is applied to many pages. With an external style
sheet, you can change the look of an entire Web site by changing one file. Each page must link
to the style sheet using the <link> tag. The <link> tag goes inside the head section:
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css" />
</head>
An external style sheet can be written in any text editor. The file should not contain any html
tags. Your style sheet should be saved with a .css extension. An example of a style sheet file is
shown below:

16

hr {color:sienna;}
p {margin-left:20px;}
body {background-image:url("images/back40.gif");}
3. in-line style sheet: An inline style loses many of the advantages of style sheets by mixing content with
presentation. Use this method sparingly!
To use inline styles you use the style attribute in the relevant tag. The style attribute can contain
any CSS property. The example shows how to change the color and the left margin of a
paragraph:
<p style="color:sienna;margin-left:20px">This is a paragraph.</p>
We have one more style which is given by default by browsers which is not editable
External style sheet can be saved with .css as its extension
Syntax: (Attributes) element (or) class (or) id {property: value ;}

CSS Syntax
A CSS rule has two main parts: a selector, and one or more declarations:

The selector is normally the HTML element you want to style.


Each declaration consists of a property and a value.
The property is the style attribute you want to change. Each property has a value.
Selector: - selector are identifiers which give styles based on elements, class (denoted by period
.), id (denoted by #) based on selectors we have
Element selector
Class selector

17

Class with element selector


Id selector
Id with element selector
Attribute selector
Pseudo selector

Element selector: Ex: - element.html


<html>
<head>
<title>Element Selector</title>
<style>
h1{color:green;}
</style>
</head>
<body>
<h1>Welcome to my Website</h1>
</body>
</html>
Class selector: The class selector is used to specify a style for a group of elements. Unlike the id selector, the
class selector is most often used on several elements.
This allows you to set a particular style for many HTML elements with the same class.
The class selector uses the HTML class attribute, and is defined with a "."
In the example below, all HTML elements with class="center" will be center-aligned:

18

Ex: - class-selector.html & Class with element selector: <html>


<head>
<title>Element Selector</title>
<style>
h1{color:green;} //element selector
.x{color:red;}

// class selector

//.x{font-family:impact;}
p.x{font-size:20pt;color:black;}

// Class with element selector

</style>
</head>
<body>
<h1>Welcome to my Website</h1>
<h1 class='x'>This is new Website </h1>
<h1>hello This is my next line</h1>
<p class='x'>Hello my next page</p>
<p>Rajesh</p>
</body>
</html>
Id selector: The id selector is used to specify a style for a single, unique element.
The id selector uses the id attribute of the HTML element, and is defined with a "#".

19

The style rule below will be applied to the element with id="para1":
Ex: - id-selector.html & id with element selector
<html>
<head>
<title>Element Selector</title>
<style>
h1{color:green;} //element selector
.x{color:red;}

// class selector

//.x{font-family:impact;}
p.x{font-size:20pt;color:black;} // Class with element selector
#g{background:green;}

//id selector

p#g{text-transform:uppercase;} //id with element selector


</style>
</head>
<body>
<h1>Welcome to my Website</h1>
<h1 class='x'>This is new Website </h1>
<h1>hello This is my next line</h1>
<p class='x'>Hello my next page</p>
<p class='x' id='g'>Rajesh</p>
<h2 class='x' id='g'>Amith</h2>
<h2 class='x' id='g'>David</h3>

20

<p class='x' id='g'>Praveen</p>


<p class='x' id='g'>Karthik</p>
</body>
</html>
Attribute selector: Ex: - attribute.html
<html>
<head>
<title>Element Selector</title>
<style>
.x{
color:deeppink;
font-family:impact;
}
input[type='text']{
color:deeppink;
}
</style>
</head>
<body>
Name : <input type='text' name='name' class='x'><br>
username : <input type='text' name='uname'><br>

21

</body>
</html>
Pseudo selector: Ex: - pseudo.html
<html>
<head>
<title>Element Selector</title>
<style>
p:first-letter{
font-size:30pt;
color:deeppink;
font-family:arial black;
}
p:first-line{
color:orange;
}
</style>
</head>
<body>
<p>This is my first email to all you guys his is my first email to all you guys his is my first
email to all you guys his is my first email to all you guys his is my first email to all you
guys</p>
</body>

22

</html>
Ex2: - pseudo2.html
<html>
<head>
<title>Element Selector</title>
<style>
a{font-size:20pt;font-weight:bold;}
a:link{
color:red;
}
a:visited{
color:green;
}
a:active{
color:blue;
}
a:hover{
color:deepskyblue;
text-decoration:none;
}
</style>
</head>
<body>
<center><a href='class-selector.html'>Selector</a> | <a
href='element.html'>Elements</a></center>
</body>
</html>

23

Css ex: <html>


<head>
<link href = filename.css type = text/css ref = stylesheet/>
<title>first css page</title>
<style>
H1{color : green;}
</style>
</head>
<body>
<h1> welcome to my web site </h1>
<p style = color.red;> some large text matter </p>
<b> this is my next element </b>
</body>
</html>
Css sheat sheet: Font-styles :font-style : italic,normal
font-variant : small-caps,narmal,small,caps(capital letters)
font-weight : normal,lighter,bold, bolder, number(100->light, 900->bolder)
font-size : <num> px;
font-family : family of font
Ex: <html>
<head>
<title>First CSS Page</title>

24

<style>
.x{
font-style:italic;
font-variant:small-caps;
font-weight:900;
font-size:16px;
font-family:courier new;
}
//.y{font:normal normal 100 20pt courier new;}
</style>
</head>
<body>
<p class='x'>some large text matter </p>
<p class='y'> some large text matter </p>
</body>
</html>
Text properties:1. letter-spacing : <num>px
2. word-spacing : <num>px
3. line-height : <num>px
4. text-align : left/center/right/justify ->order from left (or) right
5. text- decoration : name, blink,underline,overline,line-through
6. text-transform : capitalize(upper case/lower case(everything convert))
7.text-indent : : <num>px (distance from line to first letter)
The text-align property is used to set the horizontal alignment of a text. Text can be
centered, or aligned to the left or right, or justified. When text-align is set to "justify",

25

each line is stretched so that every line has equal width, and the left and right margins
are straight (like in magazines and newspapers).
The text-decoration property is used to set or remove decorations from text. The textdecoration property is mostly used to remove underlines from links for design purposes:
The text-transform property is used to specify uppercase and lowercase letters in a text.It
can be used to turn everything into uppercase or lowercase letters, or capitalize the first
letter of each word.
The text-indentation property is used to specify the indentation of the first line of a text.
Ex: -text.html
<html>
<head>
<title>First CSS Page</title>
<style>
.x{
letter-spacing:1px;
word-spacing:3px;
line-height:1.1em;
text-indent:80px;
text-align:justify;
text-decoration:none;
text-transform:capitalize;
}
</style>
</head>
<body>
<p class='x'>some large text matter </p>

26

</body>
</html>
Background property: -CSS background properties are used to define the
background effects of an element.

background-color : color name;


CSS background properties are used to define the background effects of an
element.
background-image : url(image path name);
The background-image property specifies an image to use as the background of an element.
By default, the image is repeated so it covers the entire element.
The background image for a page can be set like this:
background-repeat : no-repeat,reapt-x,reapt-y,repeat(*);
By default, the background-image property repeats an image both horizontally and vertically.
Some images should be repeated only horizontally or vertically, or they will look strange, like
this:
background-attachment : fixed,scroll;
background-position :{x,y}left,center,right,bottom,top
When using a background image, use an image that does not disturb the text.
Showing the image only once is specified by the background-repeat property:
//background : order wise
Ex: <html>
<head>
<title>First CSS Page</title>
<style>
/*body{

27

background-color:silver;
background-image:url(2.png);
background-repeat:no-repeat;
background-attachment:fixed;
background-position:280px 80px;
}*/
body{
background:gold url(2.png) no-repeat fixed right bottom;
}
</style>
</head>
<body>
<h1> some large text matter </h1>
<h1> some large text matter.</h1>
<h1> some large text matter.</h1>
<h1> some large text matter.</h1>
<h1> some large text matter.</h1>
</body>
</html>
List properties: list-style-type : none,disk,circle,square,decimal,upper-alpha,lower-alpha,upper-roman,lowerroman;
list-style-position : outside (*) / inside;
list-style-image:url(image path name);
Ex: - listproperties.html
<html>
<head>

28

<title>First CSS Page</title>


<style>
ul.x{
background:#ccc;
list-style-type:none;
list-style-position:outside;
list-style-image:url(tick.png);
}
ul.x li{
background:gold;
padding:5px;
margin:2px;
}
ul.x li.c{
list-style-image:url(cross.png);
}
</style>
</head>
<body>
<ul class='x'>
<li>We Train PHP</li>
<li>We Train CMS that is Joomla,Drupal</li>
<li>We Train SAP</li>
<li class='c'>We don't Train .NET</li>
<li class='c'>We don't Train Ruby on Rails</li>
</ul>

29

</body>
</html>
Box properties: Padding : inside element
Margin auto = center
Overflow = visible (*), hidden, auto, scroll
Ex: <html>
<head>
<title>BOX properties</title>
<style>
//body{margin:0px;}
p{text-align:center;}
.z{
background:#ccc;
padding:15px;
width:50%;
height:80px;
margin:auto;
overflow:auto;
text-align:justify;
}
</style>
</head>
<body>
<p>

30

<input type='checkbox' name='t&c' />Terms & Conditions


<p class='z'>
Some large text matter</p>
</p>
</body>
</html>
Border: border-width : <num>px;
border-style : solid,groove,inset,outset,double,dotted,dashed;
border-color : <color name>
//border: order wise
Ex: - border.html
<html>
<head>
<title>BOX properties</title>
<style>
.a{
border-width:5px;
border-style:solid;
border-color:gold;
}
.b{border:10px dashed red;padding:10px;}
.c{
border-bottom:5px double black;
padding:10px;
}

31

</style>
</head>
<body>
<p class='a'>
This is a place for social network where people would have the choices to vote there views
</p>
<p class='b'>
This is a place for social network where people would have the choices to vote there views
</p>
<b class='c'>
This is a place for social network where people would have the choices to vote there views
</b>
</body>
</html>
Div tag: - div tag stand for division tag div tag is the block level element. A block level element
creates a block with coming left and right breaks in it
Ex:- div tag, p tag, h1 to h6, table tag, ul and li tags
In-line element: - these particular elements will take the content span only and does not have
breaks init
Span tag is the natural tag
Ex: <html>
<head>
<title>in-line element</title>
<style>
h1 {
background : green; display : inline;

32

}
b
{
Background: gold;
}
a.{text-align : center; background : yellow; display : block;
}
</style>
</head>
<body>
<h1>hello</h1><b>hello</b><i>hello</i><p>hello</p>
<hr>
<span class = a>hello</span>
<div class = a>hello</div>
<hr>
<h3> converting block & inline & respectively<h3>
<h1> hello</h1>
</bold>
</html>
Display property: Visibility : - we have visible (or) hidden
Display: - none, in-line, block;
Padding : - <num>px
Padding:

top
0px

all sides

left
0px

Bottom right

33

Margin: <num> all sides


Margin : top right bottom left
0px

0px

0px

0px

Ex: <html>
<head>

<title>display property</title>
<style>
div{
background:blue;color:#fff;padding:10px;font-size:20pt;margin:2px;
}
.h{visibility:hidden;}
.v{visibility:visible;}
//.n{display:none;background:#ddd}
//.i{display:inline;}
</style>
</head>
<body>
<div>Normal Element</div>
<div class='h'>Hidden Element</div>
<div class='v'>Visible Element</div>
<hr><br><br>
<div>Display Element</div>
<div class='n'>Please Pay the Bill to avoid late payment charges</div>
<div class='i'>Display Inline Element</div>

34

</body>
</html>
Templates: Position properties: - position in css we have absolute relative and fixed position
Relative position: - working from the current position we can move the element any ware on to
the web page but cannot be moved on the top of the position place
Absolute & fixed position: - placing from the current position we can move the element to all
corner of the web page and also one top of the position place .once an element declare as fixed
(or) absolute this will turn to in-line element and this will also carry 7 index init
Ex: - position.html
<html>
<head>
<title>Position properties</title>
<style>
div{background:blue;color:#fff;font-size:17pt; font-weight:bold;padding:10px;margin:4px;}
.r{background:gold;color:#000;position:relative;left:30px;top:120px;}
.a{background:blue;position:absolute;top:50px;left:6px;}
.f{background:deeppink;color:#000;position:fixed;bottom:0px;right:0px;}
</style>
</head>
<body>
<div>Normal Position</div>
<div class='a'>Absolute Position</div>
<div class='r'>Relative Position</div>

35

<div class='f'>Fixed Position</div>


<h1>some large text matter </h1>
<h1> some large text matter </h1>
<h1> some large text matter </h1>
<h1> some large text matter </h1>
</body>
</html>
Hmenu: Ex: - hmenu.html
<html>
<head>
<title>Position properties</title>
<style>
ul#hmenu{
list-style-type:none;
text-align:center;
margin-top:50px;
}
ul#hmenu li{
display:inline;
margin:0px -2px;
}
ul#hmenu li a{
text-decoration:none;
font-size:17pt;

36

padding:10px 20px;
font-weight:bold;
}
ul#hmenu li a:link,ul#hmenu li a:visited,ul#hmenu li a:active{
background:#000;
color:#fff;
}
ul#hmenu li a:hover{
background:#ddd;
color:#000;
}
</style>
</head>
<body>
<ul id='hmenu'>
<li><a href='#'>Home</a></li>
<li><a href='#'>About-Us</a></li>
<li><a href='#'>Products</a></li>
<li><a href='#'>Contact Us</a></li>
<li><a href='#'>Login</a></li>
</ul>
</body>
</html>
Vmenu: Ex: - vmenu.html
<html>

37

<head>
<title>Position properties</title>
<style>
ul#vmenu{
list-style-type:none;
padding:0px;
background:gold;
width:120px;
margin:0px;
}
ul#vmenu li a{
text-decoration:none;
}
</style>
</head>
<body>
<ul id='vmenu'>
<li><a href='#'>Home</a></li>
<li><a href='#'>About-Us</a></li>
<li><a href='#'>Products</a></li>
<li><a href='#'>Contact Us</a></li>
<li><a href='#'>Login</a></li>
</ul>
</body>
</html>
About: -

38

Ex:- aboutus.html
<html>
<head>
<title>Web Layout</title>
<style>
body{margin:0px;}
div{background:brown;color:#fff;}
.h{text-align:center;}
.l{background:green;width:150px;float:left;}
.r{background:green;width:150px;float:right;}
.m{background:#fff;color:#000;margin:0px 150px;padding:20px;text-align:justify;}
div.m img#img1{float:right;}
div.m img#img2{float:right;padding:10px;clear:both;}
</style>
</head>
<body>
<div class='h'>Heading</div>
<div class='l'>
<ul id='vmenu'>
<li><a href='layout.html'>Home</a></li>
<li><a href='aboutus.html'>About-Us</a></li>
<li><a href='#'>Products</a></li>
<li><a href='#'>Contact Us</a></li>
<li><a href='#'>Login</a></li>
</ul>
</div>

39

<div class='r'>Right Content</div>


<div class='m'><h2>We Are in About us Page</h2>
</div>
</body>
</html>
Layout: Ex: <html>
<head>
<title>Web Layout</title>
<style>
body{margin:0px;}
div{background:brown;color:#fff;}
.h{text-align:center;}
.l{background:green;width:150px;float:left;}
.r{background:green;width:150px;float:right;}
.m{background:#fff;color:#000;margin:0px 150px;padding:20px;text-align:justify;}
div.m img#img1{float:right;}
div.m img#img2{float:right;padding:10px;clear:both;}
</style>
</head>
<body>
<div class='h'>Heading</div>
<div class='l'>
<ul id='vmenu'>
<li><a href='layout.html'>Home</a></li>

40

<li><a href='aboutus.html'>About-Us</a></li>
<li><a href='#'>Products</a></li>
<li><a href='#'>Contact Us</a></li>
<li><a href='#'>Login</a></li>
</ul>
</div>
<div class='r'>Right Content</div>
<div class='m'>some large text matter write here </div>
</body>
</html>

41

JavaScript

JavaScript is client side scripting language.


JavaScript is the case sensitive.
JavaScript can be used for AJAX integration and validation.
JavaScript can be embed into the head tag and body tag using script tag
JavaScript can be saved with .js as its extension.

42

Content:
Variables
Datatypes
Operators (Assignment, Arthamatic, Post/Pre [Inc/Dec], Comparission, Relational,

Conditional, Logical,Ternary)
Alert,prompt,confirm
Built in Functions (Arrays,Date,Math,String)
DOM (Document Object Module)
Navigator,images,screen,location,history
Document (getElementById, getElementsByTagName, getElementsByName)
Events :
General Events (onclick(), ondblclick(), onload(), onunload(), onreset(),

onsubmit(), onfocus(), onblur(), onchange())


Mouse Events (onmouseover(), onmousemove(), onmousedown(), onmouseout()

)
Key Board Events (onkeyup() , onkeydown() )

Document. write (): - document.write is the printing method in javascript.which will output
statement to the browser
Ex: -first.html
<html>
<head>
<script src='ext.js' type='text/javascript' language='javascript'></script>
<script>
document.write('This is Called from Head Tag<br>');
</script>
</head>
<body>
<h1>Welcome</h1>
<script>

43

document.write('This is Called from Body Tag<br>');


</script>
</body>
</html>
ext.js:document.write('<h1>This is called from External Page</h1>');
Variables: - variable are case sensitive. Declaring a variable in JavaScript we have used with
var variable name = value;
Variables are "containers" for storing information.
Ex: - var a = 10;
The correct method to declare are
Var a = 10;
Var_a = 10;
Var first-name = suresh;
Var firstName = suresh;
Var $name = suresh;
Wrong method:Var #name = suresh;
Var 1a = 10;
Var first name = suresh;
Ex: -variables.html
<html>
<head>

var = default

44

<script>
document.write('This is Called from Head Tag<br>');
firstName = 10;
document.write('<h1>The Value of a is :'+firstName+'</h1>');
</script>
</head>
<body>
<h1>Welcome</h1>
</body>
</html>
Data types: String: - collection of characters inside a single (or) double cotation are known as string
working with single cotation and adding double cotation in it is valid.but adding single cotation
inside a single cotation is not valid
Ex: -datatypes.html
<html>
<head>
<script>
var a = 10;
document.write('<h1>'+a);
document.write(' - ');
document.write(typeof(a));
document.write('<br>');

45

var f = 10.25;
document.write(f);
document.write(' - ');
document.write(typeof(f));
document.write('<br>');
firstname = 'Rajesh';
document.write(firstname+' - '+typeof(firstname)+'<br>');
firstname = firstname+' Kumar';
document.write(firstname+' - '+typeof(firstname)+'<br>');
firstname += 'B';
document.write(firstname+' - '+typeof(firstname)+'<br>');
document.write('<hr>String Methods<hr>');
document.write('i\'ll Pay the Bill Tomorrow');
</script>
</head>
<body>
<h1>Welcome</h1>
</body>
</html>
Operators:Assignment operator: - = is used to assign values.
The assignment operator = is used to assign values to JavaScript variables.

46

Assignment operators are used to assign values to JavaScript variables.


Ex:<html>
<head>
</head>
<body>
<script>
document.write('<h1 align="center">Assignment Operator</h1>');
var x = 10;
document.write("The Value is : "+x);
</script>
</body>
</html>
Arithmetic operator: - The arithmetic operator + is used to add values together.
Arithmetic operators are used to perform arithmetic between variables and/or values.
Ex: <html>
<head>
</head>
<body>
<script>
document.write('<h1 align="center">Arthamatic Operator</h1>');
a = 5; b = 3;

47

document.write("Addition : "+(a+b)+'<br>');
document.write("Multiplication : "+(a*b)+'<br>');
document.write("Division : "+(a/b)+'<br>');
document.write("Minus : "+(a-b)+'<br>');
document.write("Modulus : "+(a%b)+'<br>');
</script>
</body>
</html>
Comparison operator: - Comparison operators are used in logical statements to determine
equality or difference between variables or values.
Ex: <html>
<head>
</head>
<body>
<script>
ocument.write('<h1 align="center">comparision Operator</h1>');
if(10 != '10'){
document.write('<h2>Correct</h2>');
}

else {
document.write('<h2>Not Correct</h2>');

}
document.write('<h1 align="center">Post & Pre Increment</h1>');

48

m = 10;
n = (m++)+(++m)+(m++)+(++m);
document.write('The Value of m is : '+m+'<br>The Value of n is : '+n+'<br>');
</script>
</body>
</html>
Relational operator: -

< , > , <= , >=

Logical operator: -

&&(and) -- ||(or)

Ternary operator: Syntax: Var a= 10;


Type = (a%2 == 0)? even number: odd number;
//document.write(the value you entered is : +type);
document.write(type);
Ex: - ternary.html
<html>
<head>
</head>
<body>
<script>
var x = 11;
type = (x%2==0)?'Even Number':'Odd Number';
document.write("The Value you have Entered is : "+type+'<hr>');

49

student = 'kalpana';
perc = 35;
gender = 'f';
status = (perc>55)?'Pass':'Fail';
document.write(student+' you have '+status+'ed the Exam. '+((gender == 'm')?'He':'She')+' Has
got '+perc+'% in the Exam');
</script>
</body>
</html>
Ex of pay bill: <html>
<head>
<style>
.x{background:#ddd;color:deeppink;font-weight:bold;font-family:arial black;letterspacing:5px;margin:auto;width:60%;padding:10px;text-align:justify;}
</style>
</head>
<body>
<script>
credit = 101;
curr_date = 15;
pay_date = 13;
if(credit > 100 && ((curr_date-pay_date<=3) && (curr_date-pay_date>0))){

50

document.write("<div class='x'>Please Pay the Bill to avoide Late Payment


Charges</div>");
}
</script>
<p>some large text write here </p>
</body>
</html>
Conditions: If else: - whenever a condition is if it is true that part of the constructor will be excuted.if
condition is fail else part would get executed
Conditional statements are used to perform different actions based on different
conditions
use this statement to execute some code if the condition is true and another code if the
condition is false
Syntax: If (cond)
{
//code
}
else
{
// code
};

51

If else if: - if else if (or) ladder condition will take more than one condition (or) multiple
conditions. If all the conditions fail in if else if constructor then only else part get executed
use this statement to select one of many blocks of code to be executed
Syntax: If(cond)
{
//code
}
else if (cond)
{
//code
}
else if (cond)
{
//code
}
.
.
.
else
{

52

//default value;
}
Switch: - use the case in-order wise. this is main concept in switch case
use this statement to select one of many blocks of code to be executed
Conditional statements are used to perform different actions based on different
conditions.
Use the switch statement to select one of many blocks of code to be executed.
Syntax: switch(n)
{
case 1
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
Ex: <script>
type = 'ddlj';
switch (type){
case 'Ravan':
document.write('This is a good Movie ... Review Rating is : 5 star<br>');
break;
case 'Titanic':
document.write('This is a Holly wood Movie ... Review Rating is : 5 star<br>');

53

break;
case 'don':
document.write('This is a good Movie ... Review Rating is : 4 star<br>');
break;
case 'rambo':
document.write('This is a good Movie ... Review Rating is : 3 star<br>');
break;
case 100:
document.write('This is a 100 good Movie ... Review Rating is : 3 star<br>');
break;
case 1:
document.write('This is a 3 good Movie ... Review Rating is : 3 star<br>');
break;
case 2:
document.write('This is a 2 good Movie ... Review Rating is : 3 star<br>');
break;
default:
document.write('Movie information is not Available<br>');
break;
}
</script>
Looping methods: While:

do-while:

54

Syntax:

Syntax:

Initialize method

Initialize

While (cond)

do

{
//code
//code

While: - Working with while loops it will first check the initialize part and checks the
condition. If condition is true it will get into the constructor and takes place until condition fail
and comes out of the constructor.
loops through a block of code while a specified condition is true
Do-while: -this will also checks the initialize part .but for only first time it will get into the
constructor and execute the code and checks the conditions later and if condition is true looping
takes place (or) else it come out of the constructor with at least single time execution code
For-loop: - for loop first initialize condition an inc/dec will be done on same (single) line for
the every first time it will initialize with part them check within condition if condition is true the
constructor will get excuted.condition fail will come out of the for loop (constructor)
Loops execute a block of code a specified number of times, or while a specified
condition is true.
Syntax: For (initialize; condition; inc/dec )
{
//code
}
Ex: -

55

<script>
document.write("Day - <select name='Day'>");
document.write("<option value=''>Day</option>");
day = 1;
while(day<=31){
document.write("<option>"+day+"</option>");
day++;
}
document.write("</select>");
document.write(" Month - <select name='Month'>");
document.write("<option value=''>Month</option>");
month = 1;
do{
document.write("<option>"+month+"</option>");
month++;
}

while(month<=12);

document.write("</select>");
document.write(" Year - <select name='Year'>");
document.write("<option value=''>YYYY</option>");
for(year=2012;year>=1920;year--){
document.write("<option>"+year+"</option>");
}

56

document.write("</select>");
</script>
Array: - a variable which can hold more than one value is none as array (or) super variable as
array can be defined is JavaScript as
Var a = new Array (values);

// a->super variable

To fined the length of the array we can go with length = array name.length;
If the array index is been initialize more than the current index++ then memory is vested
in JavaScript
In arrays initializing string index the printing method will not work in JavaScript
Ex: - document.write() (or) looping method will not able to print string indexes
While, do-while , for-loop will not print string indexes in JavaScript so to print string
indexes we can go with
Syntax: - for (var name in Array name)
For it is key word in JavaScript which will print the string index
The Array object is used to store multiple values in a single variable.
An array is a special variable, which can hold more than one value, at a time.
Create an Array
An array can be defined in three ways.
The following code creates an Array object called myCars:
1: var myCars=new Array(); // regular array (add an optional integer
myCars[0]="Saab";

// argument to control array's size)

myCars[1]="Volvo";
myCars[2]="BMW";
2: var myCars=new Array("Saab","Volvo","BMW"); // condensed array
3: var myCars=["Saab","Volvo","BMW"]; // literal array
Ex: - Array.html

57

<script>
var a = new Array(10,20,30,40);
document.write('The Array is : '+a+'<br>');
document.write('Length of Array : '+a.length+'<br>');
document.write('Index at 2 : '+a[2]+'<br>');
a[2] = a[2]*2;
document.write('The Array is : '+a+'<br>');
a[4] = 'New Value';
document.write('The Array is : '+a+'<br>');
var b = new Array();
b[0] = 100;
b[1] = 200;
b[2] = 300;
b[3] = 400;
b['Name'] = 'Rajesh';
b['Age'] = 30;
b[7] = 700;
b[10] = 1000;
document.write('<hr>Single string Index : '+b['Name']+'<hr>');
document.write('The Array is : '+b+'<br>');
for(i=0;i<b.length;i++){
document.write('Index at : '+i+' = '+b[i]+'<br>');

58

}
document.write('<hr>');
for(c in b){
document.write(c+' = '+b[c]+'<br>');
}
document.write('<hr>');
var d = [10,20,30];
document.write('The Array in d is : '+d+'<br>');
document.write('The Array in d is : '+d.length+'<br>');
document.write('<hr>');
var e = {'Name':'Rajesh','Age':30,10:20,'Status':'Active'};
document.write('The Array in d is : '+e+'<br>');
for(i=0;i<e.length;i++){
document.write('Index at : '+i+' = '+e[i]+'<br>');
}
for(c in e){
document.write(c+' = '+e[c]+'<br>');
}
</script>
Double dimensional array: -an array can have more than one array is called double
dimensional array
Ex: - douledimensionarray.html
<html>

59

<head>
<script>
var a = [[1,'Ajay',[45,62,49,72,55,84]],[2,'Rajesh',[48,62,94,72,38,62]],[3,'Suresh',
[48,63,82,97,45,28]]];
//document.write(a[1][1]);
document.write('Name is : '+a[2][1]);
document.write("<table border='1' align='center' width='60%' >");
document.write("<tr><th colspan='9'>Student Marks Memo Report</th>");
document.write("<tr><td rowspan='2'>Roll No</td><td rowspan='2'>Name</td><td
colspan='6' align='center'>Subjects</td><td rowspan='2'>Pass/Fail</td></tr>");
document.write("<tr><td>English</td><td>Hindi</td><td>Telugu</td><td>Maths</td><td>Sc
ience</td><td>Social</td></tr>");
document.write("<tr><td>"+a[0][0]+"</td></tr>");
</script>
</head>
<body>
<tr><td><script>document.write(a[1][0]);</script></td><td><script>document.write(a[1]
[1]);</script></td></tr>
</table>
</body>
</html>
Array built-in: Join: - join is the pre-defined key-word in the JavaScript .which will convert the given array
into the separator passed default separator is coma (,)

60

Concat: - concat is joining more than array in single array is called concat
Reverse: - reverse in JavaScript the array last being is first. First is last without (descending
order) the original array will also get affected. If we use reverse function
Sort: - sort is nothing but given the order is ascending order
Unshipt: - unshipt will add the value at the starting of the array. The variable use for unshift
will holds the length of the array and the original array would get affected
Shift: - shift function will not hold any arguments should will remove the starting value of the
array. The variable unshift will hold the remove the value
Push: - push is nothing but insert the value into the array at the end of array is called push
Pop: - pop is nothing but remove the last value in the array is called the pop
Ex: - arraybuiltin.html
<script>
var a = new Array('This','is','my','new','car');
document.write('The Original Array is : '+a+'<br>');
b = a.join(' ');
document.write('Join Method : '+b+'<br>');
var a = new Array(10,20,30);
var b = new Array(40,50);
var c = new Array(60,70,80);
document.write("Concat Two Arrays : "+a.concat(b)+"<br>");
document.write("Concat All Given Array : "+a.concat(b.concat(c))+"<br>");
var a = new Array('Ajay','Raju','Amith','Zebra','Arjun');
b = a.reverse();

61

document.write("Reverse of an Array : "+b+'<br>');


document.write("Original Array : "+a+'<br>');
var a = new Array('Ajay','Raju','Amith','Zebra','Arjun');
b = a.sort();
document.write("Assending Order : "+b+'<br>');
document.write("Original Array : "+a+'<br>');
b = a.reverse();
document.write("Reverse With Desending Order : "+b+'<br>');
document.write("Original Array : "+a+'<br>');
var x = new Array(10,20,30);
b = x.unshift(5);
document.write("Unshift Method : "+x+'<br>');
document.write("The Value Stored in B : "+b+'<br>');
var x = new Array(5,10,20,30);
b = x.shift();
document.write("shift Method : "+x+'<br>');
document.write("Removed Value is stored B : "+b+'<br>');
var x = new Array(5,10,20,30);
b = x.push(40);
document.write("Push last Value to Array Method : "+x+'<br>');
document.write("B holds the length of the Array: "+b+'<br>');
var x = new Array(5,10,20,30);

62

b = x.pop();
document.write("Pop Removes last Value in Array : "+x+'<br>');
document.write("B holds the Removed Value: "+b+'<br>');
</script>
Functions:-functions in javascript are case sensitive once declare a function name and try to redeclare. The same function name will overwrite preview function name. Functions are used to
debug the code and analyze the errors easily. Working with length of the code will be reduced.
We have mainly 4 types of the functions in JavaScript that is
1. Function without arguments and return value
2. Function with arguments and no return value
3. Function with return value and no arguments

4. Function with arguments and return value


Syntax: Function function name (arguments, arg)
{
//code
}
1. Function without arguments and return value
Ex: <script>
test();
function test(){
document.write('This is Function without Aurgument<br>');

63

document.write('This is my function Content<br>');


}
function test1(){
document.write('Overwritten is done on the previous printing methods<br>');
}
test();
test();
</script>
<body>
<script>
test();
</script>
</body>
2. Function with arguments and no return value
Ex:-

<style>
.error{background:gold;color:green;padding:10px;margin:auto;width:60%;font-size:18pt;}
.success{background:black;color:#fff;padding:10px;margin:auto;width:60%;font-size:18pt;}
</style>
<script>
function welcome(name){
document.write("Welcome ! "+name+'<br>');

64

}
welcome('Rajesh');
welcome('Amith');
function statement(type,message){
document.write("<div class='"+type+"'>"+message+"</div>");
}
//statement("error","Welcome Guest ! ");
statement("success","Welcome Rajesh");
</script>
3. Function with return value and no arguments

Ex: <script>
function test(){
document.write('This is line 01<br>');
document.write('This is line 01<br>');
return 10

2;

document.write('This is line 01<br>');


document.write('This is line 01<br>');
}
test();
var x = test();
document.write('The Value in x is : '+x+'<br>');

65

</script>
4. Function with arguments and return value
Ex:<script>
function square(num){
return num*num;
}
document.write('The Square root of 5 is : '+square(5)+'<br>');
document.write('The Square root of 5 is : '+square(square(5))+'<br>');
</script>
Math built-in function: - in JavaScript we have mainly seven kinds of math object which are
pre-defined and can be called respective key-words. Which are included in JavaScript library
Ex: -math.html
<script>
function r(txt){
document.write('<h2>'+txt+'</h2>')
}
r("<u>Javascript Predefined Math Constant Object </u>");
r('Eulers Constant : '+Math.E);
r('Pi Value : '+Math.PI);
r('SQRT OF 2 : '+Math.SQRT2);
r('Natural Log 2: '+Math.LN2);
r('Natural Log 10 : '+Math.LN10);

66

r('Log base 2 of Eulers : '+Math.LOG2E);


r('Log base 10 of Eulers : '+Math.LOG10E);
r("<u>Javascript User - defined Math Object </u>");
r('Max Value : '+Math.max(10,20,30));
r('Min Value : '+Math.min(10,20,30));
r('Sqrt Value : '+Math.sqrt(25));
r('2 pow 4 : '+Math.pow(2,4));
r('Absolute Value : '+Math.abs(-9));
r('Ceil Value : '+Math.ceil(2.11111));
r('floor Value : '+Math.floor(2.9999));
r('round Value : '+Math.round(2.5111111));
r('Random Number : '+Math.random());
r('Number Between 1 to 1000 : '+Math.round(Math.random()*1000));
</script>
String built-in function: Ex: - stringbuilt.html
<script>
function r(txt){
document.write(txt+'<br>');
}
var str = "lamp Institute";
r('String Value = '+str);

67

r("Length of the String = "+str.length);


r("Color of String = "+str.fontcolor('green'));
r('Upper Case = '+str.toUpperCase());
r('Lower Case = '+str.toLowerCase());
r('Big Font = '+str.big());
r('Bold Font = '+str.bold());
r('Small Font = '+str.small());
r('Italic Font = '+str.italics());
r('Superscript = '+str.sup());
r('sub script = '+str.sub());
r('<hr><h2><u>Slice Function([begin, stop]) </u></h2>');
r('Slice(4) = '+str.slice(4));
r('Slice(4,8) = '+str.slice(4,8));
r('Slice(-9) = '+str.slice(-9));
r('Slice(-9,8) = '+str.slice(-9,8));
r('Slice(-9,-3) = '+str.slice(-9,-3));
r('<hr><h2><u>Substring Function([From, to]) </u></h2>');
r('substring(4) = '+str.substring(4));
r('substring(4,8) = '+str.substring(4,8));
r('substring(4,2) = '+str.substring(4,2));
//r('substring(-9) = '+str.substring(-9));
r('<hr><h2><u>substr([start, length]) </u></h2>');

68

r('substr(4) = '+str.substr(4));
r('substr(5,8) = '+str.substr(5,8));
r('substr(-9) = '+str.substr(-9));
r('substr(-9,2) = '+str.substr(-9,1));
r('CharAt(0) = '+str.charAt(1));
r('charCodeAt(1) = '+str.charCodeAt(1)); //ascill Value of Index
mob = 'Z123456789';
r('charCodeAt = '+mob.charCodeAt(0));
r('Indexof = '+str.indexOf('T'));//-1
r('lastIndexof = '+str.lastIndexOf('t'));
r('indexOf = '+str.indexOf('t',9));
r('Search = '+str.search('z'));//-1
r('Match = '+str.match('z'));//null
</script>
Mobile function: -

Ex: -mob.html
<script>
function r(txt){
document.write(txt+'<br>');
}
mob = "8855644045";

69

r(isValidMobile(mob));
function isValidMobile(val){
if(val.length != 10){
return "Please Enter 10-Digit Mobile Number";
}
f = val.charAt(0);
if(f == '7' || f == '8' || f == '9'){
}

else {
return 'Please Check the First Digit of Number & try Again';
}

return isNumeric(val);
}
function isNumeric(val){
for(i=0;i<val.length;i++){
ascii = val.charCodeAt(i);
if(ascii < 48 || ascii >57){
return 'Only Numbers Allowed Please Check again';
}
}
return 'Valid Mobile Number';
}
</script>

70

Date function: - date function can be defined with variable is equal to new date. This function
is pre-defined in JavaScript which will explain the system timing (or) running the domain it will
capture the running domain
Get time (): -this is unique time constant which is created find generate number of milliseconds
right from night jan 1 1970
Ex: -date.html
<script>
function r(txt){
document.write(txt+'<br>');
}
var d = new Date();
r('The value in d is : '+d);
r('Unix Time Constant that is Midnight Jan 01,1970 (no of millseconds : ) '+d.getTime());
r('Date : '+d.getDate());
r('Day : '+d.getDay());
r('Month : '+(d.getMonth()+1));// 0 -11
r('Year : '+d.getYear());//works only in ie...
r('FullYear : '+d.getFullYear());
r('Hours : '+d.getHours());
r('Minutes : '+d.getMinutes());
r('Seconds : '+d.getSeconds());
r('Time is : '+d.getHours()+':'+d.getMinutes()+':'+d.getSeconds());
</script>

71

DOM : dom is contain this layers


IMAGES
LOCATIONS
SCREEN------------------> Get Element ById
DOCUMENTS-----------> GetElementByTagName
NAVIGATOR------------ > GetElementByName
EMBED
Ex: -dom.html
<script>
function dochange(){
document.testForm.fname.value = alert("Please Enter");
document.testForm.fname.value = 'Enter Name';
document.testForm.lname.style.border="2px solid red";
document.testForm.lname.style.width="200px";
}
</script>
<body>
<form name='testForm'>
First Name : <input type='text' name='fname' /><br>
Last Name : <input type='text' name='lname'/><br>
<input type='button' name='change' value='DoChange' onclick="javascript:dochange();"/>
</form>

72

</body>
Get Element ById:- this particular function will match the id of the element and that particular
matching function will get executed
Ex: - getElementById.html
<script>
function dochange(){
var x = document.getElementById('test').value;
document.getElementById('test').value = x.toUpperCase();
document.getElementById('test').style.color = 'red';
}
</script>
<body>
<form name='testForm'>
First Name : <input type='text' name='fname' id='test' onblur="dochange();"/><br>
First Name : <input type='text' name='lname' id='fldtest' onkeyup="dochange();"/>
</form>
</body>
GetElementByTagName:- this particular function will match tag name and excute the function
which we are passing as a tag name
Ex: - getElementsByTagName.html
<script>
function dochange(){
var a = document.getElementsByTagName('div');

73

for(i=0;i<a.length;i++){
a[i].style.width = '400px';
a[i].style.background = '#ddd';
a[i].style.border = '4px dotted green';
}
}
</script>
<body onmouseover='dochange();'>
<h1>Welcome to My Web Page</h1>
<p>This is my First Page</p>
<p>This is my First Page</p>
<p>This is my First Page</p>
<p>This is my First Page</p>
<div>What is Social Hub</div>
</body>
GetElementByName:- this particular function will match element name and that part of the
function will get excutes
Ex: - getElementsByName.html
<script>
function dochange(){
var a = document.getElementsByName('x');
for(i=0;i<a.length;i++){
a[i].style.width = '400px';

74

a[i].style.background = '#ddd';
a[i].style.border = '4px dotted green';
}
}
</script>
<body onmouseover='dochange();'>
<h1>Welcome to My Web Page</h1>
<p>This is my First Page</p>
<p>This is my First Page</p>
<p>This is my First Page</p>
<p>This is my First Page</p>
<div>What is Social Hub</div>
</body>
NOTE1:- as ids are unique we have singular matching so we can getElementById as singular
NOTE2:-GetElementByTagName & ByName works the array format and these are plural
Events: - whenever an event is trigger and then that particular matching function will excuted
innerHTML:-innerHTML is used to push the dynamic values on to the HTML page
set Interval: - setInterval is pre-defined key-word in JavaScript which takes 2 arguments the
first argument can be express (or) function the second argument can be no of milliseconds
Alert: - alert gives you a single button option until it is click It will allowed all you navigate on
the server
Ex: - alert.html
<script>

75

alert("Please Agree with Our Terms & condition");


</script>
<body>
Welcome
</body>
Confirm: -confirm is used two options until something is being click. It wont allowed to
navigate the server and if it is click based on the values it will moved to the respect pages
Ex: - confirm.html
<script>
var x = confirm("Are You legally 18+ then enter to site");
if(x == true){
document.write("Welcome to my Terrorist Site");
}

else {
document.write("Thank You for leaving Please <a href='http://www.google.com'>Click

Here</a>");
}
</script>
<body>
</body>
Eval: -eval is pre-defined function JavaScript which will evaluate the given function in between
the JavaScript (function)
parseINT: -this is pre-defined function in JavaScript which will convert the floating value into
integer value
parseFLOOR:-

76

Ex: - innerHTML & set Interval

time.html

<script>
function r(txt){
document.write(txt+'<br>');
}
function currTime(){
var d = new Date();
var time = timeFormat(d.getHours())+':'+timeFormat(d.getMinutes())
+':'+timeFormat(d.getSeconds());
return 'Present Time : '+time;
}
function timeFormat(val){
return ((val<10)?'0':'')+val;
}
function writeTime(id){
return document.getElementById(id).innerHTML = currTime();
}
</script>
<body>
<div id='currentTime' align='right'>
<script>
r(currTime());
setInterval("writeTime('currentTime')",1000);

77

</script>
</div>
</body>
Prompt: Ex: - prompt.html
<script>
var x = prompt("Please Enter User Name");
document.write("Welcome ! "+x+'<br>');
</script>
<body>
<h1>Welcome to my webpage</h1>
</body>
Calculating: - parseINT
Ex: - calculating.html
<script>
function sumcal(){
if(confirm("Are You Shore")){
document.testForm.result.value =
parseInt(eval(document.testForm.count.value));
} else {
alert("Please Try Again");
}
}

78

</script>
<body>
<form name='testForm'/>
<Strong>Please Enter the Expression</strong><br><br>
Calculate the Given Value : <input type='text' name='count' value='2+2'/><br><br>
<input type='button' value='Calculate !' onclick="javascript:sumcal();"/><br><br>
<big><b>Result</b></big> : <input type='text' name='result' value=''/><br>
</form>
</body>
Limit text: Ex: - limittext.html
<script>
function limitText(){
var s = document.testForm.Msg.value;
len = s.length;
c = 10 - len;
if(len>10){
m = s.substr(0,10);
document.testForm.Msg.value = m;
c = 0;
}
document.testForm.count.value = c;

79

}
</script>
<form name='testForm'>
<textarea rows='5' cols='25' name='Msg' onkeyup="limitText();">
</textarea>
<input type='button' name='count' value='10'/>
</form>
Gallery create: Ex: - gallery.html
<html>
<head>
<link href="gallery.css" type="text/css" rel="stylesheet"/>
<script src='gallery.js' type='text/javascript' language='javascript'></script>
</head>
<body>
<div class='header'>Gallery Thumb View</div>
<div class='thumb'>
<img src='1.jpg' onclick="alterImage('b',this.src);"/>
<img src='2.jpg' onmouseover="alterImage('b',this.src);"/>
<img src='3.jpg' ondblclick="alterImage('b',this.src);"/>
<img src='4.jpg' onclick="alterImage('b',this.src);"/>
</div>

80

<div class='big'>
<div class='butob'>
<input type='button' class='buto' value='Zoom In' onclick="zoom('b','+');"/>
<input type='button' class='buto' value='Normal' onclick="zoom('b','0');"/>
<input type='button' class='buto' value='Zoom Out' onclick="zoom('b','-');"/>
</div>
<img src='1.jpg' id='b'/>
</div>
</body>
</html>
Gallery.css: body{
background:lightblue;
margin:0px;
}
.header{
background:darkblue;
height:80px;
color:#fff;
text-align:center;
font-size:18pt;
font-family:courier new;

81

letter-spacing:5px;
font-weight:bold;
line-height:70px;
}
.thumb{
text-align:center;margin:20px 0px 10px 0px;
}
.thumb img{
width:120px;
height:100px;
cursor:pointer;
}
.big{
text-align:center;
}
.big img{
width:400px;
height:300px;
}
.butob{
margin-bottom:10px;
}

82

.buto{
font-size:18pt;
padding:8px 20px;
background:#000;
color:#fff;
}
.buto:hover{
background:#ddd;
color:#000;
cursor:pointer;
}
gallery.js: function alterImage(id,source){
document.getElementById(id).src = source;
}
function zoom(id,type){
var min_W = 120;
var min_H = 100;
var max_W = 1000;
var max_H = 900;
var n_W = 400;
var n_H = 300;

83

img = document.getElementById(id);
var curr_W = parseInt(img.width);
var curr_H = parseInt(img.height);
switch (type){
case '+':
new_W = curr_W+(curr_W*.1);
new_H = curr_H+(curr_H*.1);
break;
case '-':
new_W = curr_W-(curr_W*.1);
new_H = curr_H-(curr_H*.1);
break;
case '0':
new_W = n_W;
new_H = n_H;
break;
}
if((new_W<min_W || new_H<min_H) || (new_W>max_W || new_H>max_H)){
}

else {
img.style.width = new_W;
img.style.height = new_H;

84

DHTML: innerHTML.html
<script>
function showText(v){
document.getElementById('Msg').innerHTML = v;
}
</script>
<body>
<form name='testForm'/>
First Name : <input type='text' name='fname' value=''
onkeyup="javascript:showText(this.value);"/> <span id='Msg'></span>
</form>
</body>
innerHTML2.html
<script>
function showText(v){
len = v.length;
//alert(len);
if(len<6){
document.getElementById('Msg').innerHTML = " Min 6 char"

85

document.getElementById('Msg').style.color = "red";
}

else{
document.getElementById('Msg').innerHTML = ""

}
}
</script>
<body>
<form name='testForm'/>
First Name : <input type='text' name='fname' value=''
onkeyup="javascript:showText(this.value);"/> <span id='Msg'></span>
</form>
</body>
search.html
<script>
function clearText(){
if(document.testForm.Query.value == 'Search'){
document.testForm.Query.value = '';
}
}
function showText(){
if(document.testForm.Query.value == ''){

86

document.testForm.Query.value = 'Search';
}
}
</script>
<body>
<form name='testForm'/>
Enter Search : <input type='text' name='Query' value='Search' onfocus="clearText();"
onblur="showText();"/>
</form>
</body>
search2.html
<body>
<form name='testForm'/>
Enter Search : <input type='text' name='Query' value='Search' onfocus="javascript:if(this.value
== 'Search') this.value = '';" onblur="javascript:if(this.value == '') this.value = 'Search';"/>
</form>
</body>
checkbox.html
<script>
function validate(){
count = 0;
for(i=0;i<4;i++){
if(document.testForm.course[i].checked){

87

count++;
}
}
if(count<2){
alert("Please Check Atleast 2 Courses");
}
}
</script>
<body>
<form name='testForm'/>
<u><big><b>Select Atleast 2 - Languages for this Job</b></big></u><br><br>
<input type='checkbox' name='course' value='c' /> C - Language <br>
<input type='checkbox' name='course' value='p'/> PHP <br>
<input type='checkbox' name='course' value='j'/> JAVA <br>
<input type='checkbox' name='course' value='m'/> MySQL <br><br>
<input type='button' name='Check' value="Validate !" onclick="validate();"/>
</form>
</body>
checkbox1.html
<script>
function validate(){
count = 0; gend = 0;

88

len = document.testForm.elements.length;
//alert(len);
for(i=0;i<len;i++){
elt = document.testForm.elements[i];
if(elt.type == 'checkbox' && elt.name == 'course' && elt.checked){
count++;
}
if(elt.type == 'radio' && elt.name == 'gender' && elt.checked){
gend++;
}
}
if(count<3){
alert("Please Select At least 3 Courses");
}
if(gend == 0){
alert("Select Gender");
}
}
</script>
<body>
<form name='testForm'/>
<u><big><b>Select Atleast 2 - Languages for this Job</b></big></u><br><br>

89

<input type='checkbox' name='course' value='c' /> C - Language <br>


<input type='checkbox' name='course' value='p'/> PHP <br>
<input type='checkbox' name='course' value='j'/> JAVA <br>
<input type='checkbox' name='course' value='my'/> MySQL <br>
<input type='radio' name='gender' value='m'/> Male <input type='radio' name='gender'
value='f'/> Female<br><br>
<input type='button' name='Check' value="Validate !" onclick="validate();"/>
</form>
</body>
passwordstrength.html
<script>
function findStrength(v){
len = v.length;
if(len>12) len = 12;
document.getElementById('pic').src = "pic/"+len+".png";
if(len<6){
document.getElementById('Msg').innerHTML = "Weak Password";
document.getElementById('Msg').style.color = "red";
}
else if(len>=6 && len<9){
document.getElementById('Msg').innerHTML = "Normal Password";
document.getElementById('Msg').style.color = "green";
}

90

else if(len>=9 && len<=12){


document.getElementById('Msg').innerHTML = "Strong Password";
document.getElementById('Msg').style.color = "blue";
}
}
</script>
<body>
<form name='testForm'/>
Password : <input type='password' name='pwd' value=''
onkeyup="javascript:findStrength(this.value);"/> <img src="pic/0.png" id='pic' border='1'/>
<span id='Msg'></span>
</form>
</body>
isd.html
<script>
function validIsd(){
i = document.testForm.country.selectedIndex;
v = document.testForm.country.options[i].value;
document.testForm.ISD.value = v;
}
</script>
<body>
<form name='testForm'/>

91

<select name='country' onchange="validIsd();">


<option value=''>Please Select</option>
<option value='91'>INDIA</option>
<option value='001'>USA</option>
<option value='004'> United Kingdom</option>
<option value='0458'> Japan</option>
</select> <input type='text' name='ISD' value='' size='3' readonly /> - <input type='text' name='Mob'
value='' size='10'/>
</form>
</body>
Isd1.html
<body>
<form name='testForm'/>
<select name='country' onchange="document.testForm.ISD.value = this.value">
<option value=''>Please Select</option>
<option value='91'>INDIA</option>
<option value='001'>USA</option>
<option value='004'> United Kingdom</option>
<option value='0458'> Japan</option>
</select> <input type='text' name='ISD' value='' size='3' readonly /> - <input type='text' name='Mob'
value='' size='10'/>

92

</form>
</body>
selectall.html

<script>
function selectAll(){
len = document.testForm.elements.length;
for(i=0;i<len;i++){
elt = document.testForm.elements[i];
if(elt.type == 'checkbox' && elt.name == 'course'){
elt.checked = true;
}
}
}
function selectNone(){
len = document.testForm.elements.length;
for(i=0;i<len;i++){
elt = document.testForm.elements[i];
if(elt.type == 'checkbox' && elt.name == 'course'){
elt.checked = false;
}
}

93

}
</script>
<a href="javascript:selectAll();">Select All</a> || <a href="javascript:selectNone();"/>Select
None</a><br><br>
<form name='testForm'>
<input type='checkbox' name='course' value='c'>C - Language<br>
<input type='checkbox' name='course' value='p'>PHP<br>
<input type='checkbox' name='course' value='j'>JAVA<br>
<input type='checkbox' name='course' value='m'>MySQL<br>
</form>
reset.html
<script>
function clearForm(){
c = confirm("Are You Shore");
return c;
}
</script>
<form name='testForm' onreset="javascript: return clearForm();">
Name : <input type='text' name='fname' value=''/><br><br>
Password : <input type='password' name='pwd' value=''/><br><br>
<input type='submit' name='submit' value='Register' /> <input type='reset' name='refresh'
value='Cancel !'/>
</form>

94

toggle button.html
<script>
function toggle(){
c = document.testForm.TnC.checked;
document.testForm.submit.disabled = !c;
}
</script>
<form name='testForm'>
<input type='checkbox' name='TnC' value='' onclick="javascript:toggle();"/>Terms &
Conditions <br><br>
<input type='submit' name='submit' value='Register !' disabled />
</form>
<hr>
<br>
<form name='testForm1'>
<input type='checkbox' name='TnC' value=''
onclick="javascript:document.testForm1.submit.disabled = !this.checked;"/>Terms &
Conditions <br><br>
<input type='submit' name='submit' value='Register !' disabled />
</form>
pics.html
<img src="1.jpg" width="200px" height="180px" id="pic"
onmouseover="document.getElementById('pic').src='2.jpg';"
onmousedown="this.src='3.jpg';"/>

95

controlling.html
<script>
function r(txt){
document.write('<hr>');
}
name = 'Rajesh';
n_pat = /^[a-z]{5,8}$/;
if(!n_pat.test(name)){
document.write("Invalid Name Please Try Again");
}
r();
cname = "R ajesh";
cn_pat = /^[a-z]{5,8}$/i;
if(!cn_pat.test(cname)){
document.write("Invalid Name Please Try Again");
}
r();
fname = 'B Pr*aveen Kumar';
f_pat = /^[a-z ]{6,}$/i;
if(!f_pat.test(fname)){
document.write("Invalid Name Please Try Again");
}

96

r();
username = 'maddy11*';
u_pat = /^[a-z0-9 ,.]{6,}$/i;
if(!u_pat.test(username)){
document.write("Invalid Name Please Try Again");
}
r();
mob = '785664309';
m_pat = /^[7-9][0-9]{9}$/;
if(!m_pat.test(mob)){
document.write('Invalid Mobile please Try Again');
}
r();
img = 'flower.jpg';
i_pat = /\.(jpe?g|png|gif|psd)$/;
if(!i_pat.test(img)){
document.write("Invalid Image Format Please Upload Only jpg,gif,png images");
}
</script>
navigators.html
<script>
function r(txt){

97

document.write(txt+'<br>');
}
r('<h1>Navigator in javascript</h1>');
r("User Agent = "+window.navigator.userAgent);
r("App Name = "+navigator.appName);
r("App Version = "+navigator.appVersion);

</script>
<input type='button' value='Previous Page' onclick="history.back();"/>
<input type='button' value='Screen Page' onclick="location.href='screens.html';"/>
locations.html
<h1>Location subject</h1>
<input type='button' value='Reload' name='refresh'
onclick="javascirpt:window.location.reload();"/>
<input type='button' value='Redirect Facebook' name='redirect'
onclick="javascript:location.replace('http://www.facebook.com');"/>
<input type='button' value='Redirect Facebook' name='redirect'
onclick="javascript:location.href='http://www.facebook.com';"/>
<input type='button' value='Redirect internal' name='sdaoa'
onclick="location.href='navigators.html';"/>
<input type='button' value='Print Page' name='print' onclick="window.print();"/>
screens.html
<script>
function r(txt){

98

document.write(txt+'<br>');
}
r('<hr><h1>Screen in javascript</h1>');
r("Screen Width = "+window.screen.width);
r("screen Height = "+screen.height);
r("Available Width = "+screen.availWidth);
r("Available Width = "+screen.availHeight);
</script>
<input type='button' value='Previous Page' onclick="history.back();"/>
<input type='button' value='go back Page' onclick="history.go(-1);"/>
<input type='button' value='location Page' onclick="history.go(-2);"/>
images.html
<img src='1.jpg' name='pic1' id='pic_1' width='200px' height='180px'/>
<img src='2.jpg' name='pic2' id='pic_2' width='200px' height='180px'/>
<script>
function r(txt){
document.write('<h2>'+txt+'</h2>');
}
r("Image length = "+document.images.length);
r(' 1 st image Width = '+document.images[0].width);
r(' 2 nd image height = '+document.images[1].height);
r("Image Width = "+document.pic1.width);

99

r("Image Height = "+document.pic_2.height); </script>


registerform.html
<html>
<head>
<script>
function validateForm(f){
n = f.name.value;
m = f.mob.value;
error = '';
n_pat = /^[a-z]{6,}$/i;

if(!n_pat.test(n)){
error += 'Invalid Name<br>';
}
m_pat = /^[7-9][0-9]{9}$/;
if(!m_pat.test(m)){
//error += 'Invalid Mobile<br>';
document.getElementById('mobid').innerHTML = "Invalid Mobile";
document.getElementById('mobid').style.color = "red";
}
if(error == ''){
return true;

100

else {
document.getElementById('error-box').style.display = 'block';
document.getElementById('error-msg').innerHTML = error;
return false;

}
}
function hideBox(){
document.getElementById('error-box').style.display = 'none';
}
</script>
<style>
#error-box{
background:#ddd;
border:5px solid orange;
margin-bottom:10px;
}
#error-msg{
padding:10px;
}
</style>
</head>
<body>

101

<div id='error-box'>
<div id='error-msg'>
</div>
<a href="javascript:hideBox();">Hide</a>
</div>
<form name='textForm' onsubmit="javascript: return validateForm(this);"/>
<table align='center' cellpadding="5px" cellspacing="0" width='70%' border='1'>
<tr><th colspan='3'>Please Register</th></tr>
<tr><td>Name</td><td>:</td><td><input type='text' name='name' value='' /></td></tr>
<tr><td>Username</td><td>:</td><td><input type='text' name='uname' value='' /></td></tr>
<tr><td>E-Mail</td><td>:</td><td><input type='text' name='email' value='' /></td></tr>
<tr><td>Password</td><td>:</td><td><input type='password' name='pwd' value=''
/></td></tr>
<tr><td>Confirm Password</td><td>:</td><td><input type='password' name='cpwd'
value='' /></td></tr>
<tr><td>Mobile</td><td>:</td><td><input type='text' name='mob' value='' /> <span
id='mobid'></span></td></tr>
<tr><td>Image Upload</td><td>:</td><td><input type='file' name='pic' value='' /></td></tr>
<tr><td colspan='3'><input type='submit' name='submit' value='Register !' /> <input
type='reset' name='refresh' value='Cancel !' /></td></tr>
</table>
</form>
</body>
</html>

102

103

PHP
Rasmus Lerdorf is the founder of the PHP in 1995.
PHP is the server side scripting language.
Php needs a server to excute the file.
Php files should be saved with .php as its extension ".php3", or ".phtml"
Or else our server will not excute unknown extension apart from .html, .cpi, .cgs,
Php support all the data base . that present in the market
Ex:-mySql,mssql,infonix,Sybase,ibmdb2,postgresqletc
Php can be worked on all the operating systems that is windows,linux,max,solariesetc
Php can communicate with different servers
Ex:-SMTP(Simple mail transfer protocal), imap (internet max access protocal), LDAP,

Informix, Oracle, Sybase, Solid, PostgreSQL


PHP can be install as a software tags we get many of the server files
Ex: -Xampp, Wamp, easy php, mamp
PHP stands for PHP: Hypertext Preprocessor
PHP is an open source software
PHP is free to download and use
PHP is easy to learn and runs efficiently on the server side

104

Xampp: - xampp stands for


x----------------------------->platform(windows,linux,mac,solaries)
a----------------------------->apache(web server)
m---------------------------->mysql(database file)
p---------------------------->perl(perl scripting in php)
p---------------------------->php/my admin (web database tool)
php current version is 5.3.8

wamp: - wamp stands for


w---------------------------->window exv
a----------------------------->apache(web server)
m---------------------------->mysql(database file)
p---------------------------->php/my admin (web database tool)
Mamp: - mamp stands for
m----------------------------->mac os
a----------------------------->apache(web server)
m---------------------------->mysql(database file)
p---------------------------->php/my admin (web database tool)
Apache contain the 1-65535 ports
1-1024 pre-reserved ports
Tem: - temp holds session details & temp upload files
Htdocs: - after installing xampp we have to store our files into the folder called htdocs. Once
files are saved in htdocs we can open with the location path as

105

http://localhost/abc(folder name)/first.php

echo:-echo is the output method in php

Basic PHP Syntax: <?php


echo universal way of writing php<br>;
?>
<script language = php>
echo javascript way of writtting php<br>;
</script>
<?
echoshort tag way of writing php<br>;
?>
<%
1echo asp way of writing php<br>;
%>

Comments in PHP
In PHP, we use // to make a one-line comment or /* and */ to make a comment block:
<html>
<body>
<?php
//This is a comment

106

/*
This is
a comment
block
*/
?>
</body>
</html>
Printing methods in php: Echo:-echo as the arguments can print multiple arguments. Echo as a function can print only
one argument
Print: -print as an argument can print only one argument.print also a function
Ex: - printarg<br>;
Printf: - printf will take formatting string with respected values as print
Ex: -printf((int%d) (float%f) (string %s) (asci%c));
Print-r: - print-r will print array of string
Ex: - $g = array (10,20,30,true,kalam);
Print-r($g);
Var-dump: -it is also printing method which is used debugging the errors very easily. This not
used in production level (live environmental)
Ex: - var-dump($g);
<h1>Printing Methods in PHP</h1>
<?php
$a = 10; $b = 20; $c = 30;
echo "Arg01","Arg02","Arg03<br>";

107

echo $a,$b,$c,'<br>';
echo ("Arg01<hr>");
print "Arg01<br>";
print("Arg01<hr>");
printf("(int %d) (float%.2f) (string %s) (Ascii %c) ",22.25,10.2545,'Rajesh',97);
echo '<hr>';
$g = array(10,20,30,true,'Rajesh');
print_r($g);
echo '<hr>';
var_dump($g);
?>
Controlling: Ex: - controlling.php
<style>
b{color:green;}
</style>
<?php
echo "line 01<br>";
echo "line 02<br>";
echo "line 03<br>";
?>
<b>This is Bold Tag</b><hr>

108

<?php
if(false){
echo "<b>The 1<sup>st</sup> is Executed<br></b>";
}

else {
echo "<b>The 2<sup>nd</sup> is Executed<br></b>";

}
?>
<hr>
<h2>Alternate Method</h2>
<?php
if(true){
?>
<b>The 1<sup>st</sup> is Executed<br></b>
<?php
}
else
{
?>
<b> The 2<sup>nd</sup> is Executed<br></b>
<?php
}
?>

109

Variables: Variables are "containers" for storing information.


Variables in PHP starts with a $ sign, followed by the name of the variable
The variable name must begin with a letter or the underscore character
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,

and _)
A variable name should not contain spaces
Variable names are case sensitive (y and Y are two different variables)
Ex: - variables.php
<h1>Variables in php</h1>
<?php
$a = 10;
$name = 'Rajesh';
$_name
$_name
$n123
$_1232
$1_name
$first_Name
echo 'The Value is : ',$a.'<br>';
echo 'The Name is : ',$name,'<br>';
?>
<script>

110

var a = 15;
document.write('The Value of a is : '+a+'<br>');
</script>
In PHP, a variable does not need to be declared before adding a value to it.
In the example above, notice that we did not have to tell PHP which data type the
variable is.
PHP automatically converts the variable to the correct data type, depending on its value.
In a strongly typed programming language, you have to declare (define) the type and
name of the variable before using it.
PHP has four different variable

local

global

static

Local variable: - A variable declared within a PHP function is local and can only be accessed
within that function.
Ex:- localvariable.php
<?php
function test(){
$a = 10;
echo 'The Value of $a inside function is : ',$a,'<br>';
}
test();
echo 'The Value of $a Outside Function is : ',$a,'<br>';

111

?>
Static variable: - When a function is completed, all of its variables are normally deleted.
However, sometimes you want a local variable to not be deleted.
To do this, use the static keyword when you first declare the variable.
Ex: - staticvariable.php
<?php
function test(){
$a = 10;
static $b = 20;
echo 'The Value of $a inside function is : ',$a,'<br>';
echo 'The Value of $a inside function is : ',$b,'<br>';
$a++;
$b++;
}
echo 'The Value of $b outside is : ',$z,'<br>';
test();
test();
?>
Global variable: - Global scope refers to any variable that is defined outside of any function.
Global variables can be accessed from any part of the script that is not inside a function.

112

To access a global variable from within a function, use the global keyword:
Ex: - global.php
<?php
$x = 10;
echo 'The Value of $x = ',$x,'<br>';
function test(){
//global $x;
echo 'The Value of $x inside Function = ',$x,'<br>';
echo '$GLOBALS["x"] = ',$GLOBALS['x'],'<br>';
}
test();
?>
4. Super global array of variable: -$global is the super global array variable. This is the predefined keyword. In php we have mainly some of the super global variables. This can be used
with their keywords.
i) $_EVN: - this is used for getting the information of your operating system ($_ENV (PATH))
ii) $_SERVER: - will give you the information about your server(apache information)
iii) $_GET: - it is used for form processing through get method (or) query string
iv) $_POST: -this is used for form processing through post method in secure manner
v) $_REQUEST: -will send the form through both get and post and cookie

113

vi)$_COOKIE: - this is used to get the information about the browser who is using the
web(computer)
vii)$_SESSION: -it is used to get the information of the user in between login and logout
details are store at server machine
Operators:1. Assignment operator:
2. Arithmetic operator:

= is used to assign values to variables in PHP


+,-,/,*,%

3. Increment & decrement operator:

i++,++I & i--, --i

4. Comparison operator:

==,!= ,===

5. Relational operator:

<=, >=, <>

6. Logical operator:

&&, ||, and, or

7. Error handling operator: 8. scope resolution & this operator:

::----->scope, &------->this

Ex: -operator.php
<?php
echo '<h1 align="center">Assignment Operator</h1>';
$a = 10;
echo 'The Value is : '.$a.'<br>';
echo 'The Value is Added by 2 : ',$a += 2,'<br>';
$name = 'Rajesh';

114

echo 'My name is : '.$name,'<br>';


$name .= ' Kumar';
$name = $name.' Kumar';
echo 'My name is : ',$name,'<br>';
echo '<h1 align="center">Arthamatic Operator</h1>';
echo 'The value of 2+3 : ',2+3,'<br>';
echo 'The Value of 2-3 : ',2-3,'<br>';
echo 'The Value of 2/3 : ',2/3,'<br>';
echo 'The Value of 2*3 : ',2*3,'<br>';
echo 'The Value of 2%3 : ',2%3,'<br>';
echo '<h1 align="center">Increment & Decrement [INC/DEC]</h1>';
echo '<h2>POST & PRE increment</h2>';
$x = 10;
echo 'The Value of $x = ',$x,'<br>';
echo 'The Value of $x++ = ',$x++,'<br>';
echo 'The Value of $x = ',$x,'<br>';
echo 'The Value of ++$x = ',++$x,'<br>';
echo 'The Value of $x = ',$x,'<br>';
echo '<h2>POST & PRE Decrement</h2>';
echo 'The Value of $x-- = ',$x--,'<br>';

115

echo 'The Value of $x = ',$x,'<br>';


echo 'The Value of --$x = ',--$x,'<br>';
echo 'The Value of $x = ',$x,'<br>';
echo '<h1 align="center">Comparision Operator</h1>';
var_dump(10 == 10);echo'<br>';
var_dump(10 != '10');echo'<br>';
echo '<h1 align="center">Relational Operator</h1>';
var_dump(10<=10);echo '<br>';
var_dump(10<>'10');echo '<br>';//not Equal to
echo '<h1 align="center">logical Operator</h1>';
var_dump(true && true);echo '<br>';
var_dump(true && false);echo '<br>';
var_dump(true || true);echo '<br>';
var_dump(true || false);echo '<br>';
var_dump(false AND FALSE);echo '<br>';
var_dump(false OR FALSE);echo '<br>';
echo '<h1 align="center">Error Handling Operator</h1>';
echo @sqrt();
//@test();
echo 'Some Data';

116

echo '<h1 align="center">Scope Resolution & this Operator {:: & ->(this)}</h1>';
class A{
static $z = 100;
public $a = 20;
public $k = 50;
protected $b = 30;
private $c = 40;
function test(){
echo "A Test Function called inside Class A";
}
}
$obj = new A;
echo $obj->a,'<br>';
echo $obj->k,'<br>';
//echo $obj->b,'<br>';
//echo $obj->c,'<br>';
echo ' The Static Value is : ',A::$z,'<br>';
echo 'The Function inside Class is : ',$obj->test(),'<br>';
?>

117

Type costing: - conversion of the one data type into another data type is known as type costing.
in php we have mainly two types of costing
1. Temporary type costing
2. Permanent type costing
1. Temporary type costing: - costing which can be done for single step by pre-defined the data
type keyword. That particular variable will hold Temporary type costing
Ex : - temporary.php
<?php
$x = "10.254Kgs";
var_dump($x);echo "<br>";
var_dump((int)$x); echo "<br>";
var_dump($x); echo '<br>';
var_dump((float)$x); echo '<br>';
var_dump((boolean)$x);echo'<br>';
var_dump((string)$x);echo "<br>";
var_dump($x);echo "<br>";
var_dump(floatval($x)); echo '<br>';
var_dump(intval($x)); echo '<br>';
var_dump($x);echo "<br>";
?>

118

2. Permanent type costing: - this can be done by using pre-defined key-word set type.which
hold two arguments
Syntax: - set type (var name,int);
Ex: - Permanent type costing.php
<?php
echo '<h1>Parmanent Type Casting</h1>';
$x = "10.254Kgs";
settype($x,'float');
var_dump($x);echo "<br>";
settype($x,'int');
var_dump($x);echo "<br>";
settype($x,'boolean');
var_dump($x);echo "<br>";
settype($x,'int');
var_dump($x);echo "<br>";
var_dump($x);echo "<br>";
settype($x,'float');
var_dump($x);echo "<br>";
?>
Type juggling: -conversion of data types by using expression to another data types are known
as type juggling

119

Ex: -typejuggling.php
<?php
echo 'true + true : ',true+true,'<br>';
if(null){
echo "Printed";
}

else {
echo "Not Printed";

}
?>
Variable validation function: i) Isset: -Isset of variables will check with the variable initialize are not and return Boolean
ii) empty(var name): - empty function will check the variable are not and return Boolean
iii) Unset (var name): -this function will remove the variable (or) delete the variable (or)
initialize variable
iv) get type(var name): - this function will let us known the argument the data type in the form
of string .this should be used because the coming variable this would be depreciated
Ex: -variable_validation.php
<?php
$x = 10;
var_dump($x);echo '<br>';
var_dump(isset($x));

120

var_dump(isset($a));echo '<hr>';
$z = '';
var_dump(empty($z));
var_dump(empty($y));
$k = 10;echo '<br>';
var_dump(gettype($k));
unset($x);
var_dump(isset($x));
?>
Data types: -php supports mainly 8 kinds of data types among which four are stable data types,
two are compound data types and another two are special data types
Stable data types: i) int (or) integer
ii) Float (or) real (or) decimal
iii) Boolean data types
iv) string data types
i) int (or) integer:- all non decimal values . range in between 2(32-1) to -2(32-1)
ex: <?php
echo "<h1 align='center'>Stable Data types</h1>";

121

echo "<h2>Integer Data Type</h2>";


$x = 10;
var_dump($x);echo '<br>';
$x = (pow(2,32-1)-1);
var_dump($x); echo '<br>';
$judge = 2147483647;
var_dump($judge);
?>
ii) Float (or) real (or) decimal: -all decimal values. Range in between 10(38) to 10(-38)
ex: <?php
echo "<h2>Float Data Type</h2>";
$a = 10.25;
var_dump($a);echo '<br>';
?>
iii) Boolean data types: -boolean data types written in the form of true (or) false
Ex: <?php
echo "<h2>Boolean Data Type</h2>";
$a = false;

122

var_dump($a);
?>
iv) String data types: - a collection of characters enclose in between single (or) double
cotations are known as string data types
Ex: <?php
echo "<h2>String Data Type</h2>";
$x = 10;
echo '<br>The Value of $x is ',$x,'<br>';
echo "The Value of $x is :$x";
$name = "Rajesh";
echo '<br>my name is $name <br>';
echo "my name is $name <br>";
$x = 10;
$y = 20;
echo 'The value of $x+$y = ',$x+$y,'<br>';
echo "The value of $x+$y = ",$x+$y,'<br>';
?>
Compound data types: - compound data types again two types
1. Array data type

123

2. Object data type


1. Array data type: - array data type which can hold more than one value. In php we have
mainly 3 kinds of arrays
i) Numerical array
ii) Associative array
iii) Mixed array
Declaring an array in php can be done by two types
array as the function
array as a square bracket
i) Numerical array: A numeric array stores each array element with a numeric index.
There are two methods to create a numeric array.
1. In the following example the index are automatically assigned (the index starts at 0):
$cars=array("Saab","Volvo","BMW","Toyota");

2. In the following example we assign the index manually:


$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
Ex: <?php
$cars[0]="Saab";
$cars[1]="Volvo";

124

$cars[2]="BMW";
$cars[3]="Toyota";
echo $cars[0] . " and " . $cars[1] . " are Swedish cars.";
?>
ii) Associative array: - An associative array, each ID key is associated with a value.
When storing data about specific named values, a numerical array is not always the best way to
do it.
With associative arrays we can use the values as keys and assign values to them.

Example 1
In this example we use an array to assign ages to the different persons:
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);

Example 2
This example is the same as example 1, but shows a different way of creating the array:
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
The ID keys can be used in a script:
<?php
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
echo "Peter is " . $ages['Peter'] . " years old.";
?>
The code above will output:
Peter is 32 years old.

125

iii) Mixed array: - mixed array is nothing but combination of numerical & associative array
are known as mixed array
Ex:- mixedarrays.php
<?php
$a = array("Name"=>"Rajesh","Age"=>30);
print_r($a);
echo '<hr>';
echo '<h1 align="center">Mixed Arrays</h1>';
define('A','ABC');
define('B','XYZ');
$c = 10;
$d = 20;
$g = array(0=>10,1=>20,'Name'=>'Raj','Age'=>30,5=>500,5.55=>600,-9=>'Negative
value',true=>200,false=>200,''=>'Empty Value',NULL=>'Null Value',A=>B,$c=>$d);
echo '<pre>';
print_r($g);
echo '</pre>';
?>
2. Object data type: - object is an instance of class. Class can be denoted with in class name.
Collection of variables and functions are known as class. Calling class name should be create an
object variable then that particular variable is known as object variable

126

Ex: <?php
echo "<h2>Object Data Type</h2>";
class A{
public $x = 10;
public $a = 20;
function test(){
echo 'A test Function called<br>';
}
}
$b = new A;
var_dump($b);
echo '<br>Public Value $x = ',$b->x,$b->test(),'<br>';
?>
Special data types: - special data types are again two types
i) Resource data types
ii) Null data types
i) Resource data types:- resource data type is calling an external variable value into another
variable using (&) resource variable
ii) Null data types:- this is the pre-defined key-word data type. When a variable not initialize
and by asking through printing method. This will result in null value

127

ex: <?php
echo "<h1 align='center'>Special Data types</h1>";
echo "<h2>Reference Data Type</h2>";
$x = 10;
$y = $x;
echo 'The Value of $x = ',$x,'<br>The Value of $y = ',$y,'<br>';
$x = 12;
echo 'The Value of $x = ',$x,'<br>The Value of $y = ',$y,'<br>';
$y = 'Rajesh';
echo 'The Value of $x = ',$x,'<br>The Value of $y = ',$y,'<hr>';
echo "<h2>Resourse Data Type</h2>";
$a = 10;
$b = &$a;
echo 'The Value of $a = ',$a,'<br>The Value of $b = ',$b,'<br>';
$a = 'Raj';
echo 'The Value of $a = ',$a,'<br>The Value of $b = ',$b,'<br>';
$b = 'Amith';
echo 'The Value of $a = ',$a,'<br>The Value of $b = ',$b,'<br>';
echo "<h2>Null Data Type</h2>";

128

var_dump($z);
?>
Constant:
Define: - define is the pre-defined key-word in php. This will take two arguments. The first
argument being the constant identifier which identifier its second argument value. We can pass
third argument as Boolean to make case in-sensitive
Ex:- constant.php
<?php
define('x',10,true);
echo x,'<br>';
echo X;
echo '<hr>';
define('url','http://www.socialhub.com',true);
echo uRl,'/register.php';
echo '<hr>';
define('SITE_NAME','http://www.socialhub.in-hyderabad','Social Hub');
?>
<h1>About us</h1>
we at <?php echo SITE_NAME;?> are in training ........
<h1>Contact Us</h1>
<?php echo SITE_NAME;?>

129

street ......
<h1>FAQ</h1>
what we do at <?php echo SITE_NAME;
?>
Conditions: - Conditional statements are used to perform different actions based on different
conditions
If condition:
IN PHP

IN PERL

If (cond)

if (cond) :

//code

//code

else if (code) :

//code

else if (cond)
{

//code

//code
}
else (cond)
{
//code
}
Switch condition: Syntax: -

else (cond) :

end else if ;

130

switch (cond) :
{

switch (cond):
|

Case1 :

|
//code

Break;

|
|

Case2:
//code
Break;
|
|
Default:
//code
}
Ex: <html>
<body>
<?php
$x=1;
switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;

|
end switch;

131

case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and 3";
}
?>
</body>
</html>
While condition: - The while loop executes a block of code while a condition is true
Syntax: While (cond)
{

//code inc/dec

//const code inc/dec


}
Ex: <html>
<body>
<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?>
</body>
</html>

while (cond):

endwhile

132

Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
Do-while condition: - The do...while statement will always execute the block of code once, it
will then check the condition, and repeat the loop while the condition is true.
Syntax: Do

do:

//code

inc/dee
//code

endoowhile(cond);

}
While (cond)
Example
The example below defines a loop that starts with i=1. It will then increment i with 1, and write
some output. Then the condition is checked, and the loop will continue to run as long as i is less
than, or equal to 5:
<html>
<body>
<?php
$i=1;
do
{
$i++;
echo "The number is " . $i . "<br />";

133

}
while ($i<=5);
?>
</body>
</html>
Output:
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
For loop: - Loops execute a block of code a specified number of times, or while a specified
condition is true. The for loop is used when you know in advance how many times the script
should run.
Syntax: For(initialize;cond;inc/dec)
//code

for(initialize;code;inc/dec
//code
end for

Example
The example below defines a loop that starts with i=1. The loop will continue to run as long as i
is less than, or equal to 5. i will increase by 1 each time the loop runs:
<html>
<body>
<?php
for ($i=1; $i<=5; $i++)
{
echo "The number is " . $i . "<br />";
}

134

?>
</body>
</html>
Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
Ex: -conditions.php
<?php
echo '<h1 align="center">PHP way of writing</h1>';
if(false){
echo 'First Line';
}

else {

echo 'Second Line';


}
echo '<hr>';
echo '<h1 align="center">PERL way of writing</h1>';
if(false):
echo 'First Line';
else:
echo 'Second Line';
endif;

135

?>
for each:- for each is usefull for all non-sequence data of an array. Associative array ,numerical
array object data of an array
The general syntax is
foreach (arrayName as arr[value]))
{
echo arr [value];
}
Another syntax is
foreach (arrayname as key=>value)
{
echo key-value

(or)

echo key-value;

}
Ex: -foreach.php
<?php
$a = array("Name"=>"Rajesh","Age"=>30);
/*foreach(arrayname as value){
echo arr[value];
}*/
foreach($a as $v){
echo $v,'<br>';
}echo '<hr>';
/*foreach(arrayname as key=>value){

136

echo key,' - ',value;


}*/
foreach($a as $k=>$v){
echo "$k - $v<br>";
//echo $k,' - ',$v,'<br>';
}
?>
Functions: -functions are case in-sensitive. Function once can be declare cont be re-declare in
the program
The real power of PHP comes from its functions.
In PHP, there are more than 700 built-in functions

To keep the script from being executed when the page loads, you can put it into a function.
A function will be executed by a call to the function.
You may call a function from anywhere within a page.

Give the function a name that reflects what the function does

The function name can start with a letter or underscore (not a number)

Syntax: function function name (arg)


{
//code
Return value
}

137

There are mainly 8 kinds of functions in php


1. Conditional function: - a function which is enclose inside condition is considered as
conditional function
Ex: - conditional.php
<?php
if(false){
function test(){
echo "I am a Conditional Function <br>";
}
}
@test();
2. Variable function: - when a function name is told In variable. Variable can be used for
excuting the function in a place of function name
Ex: - variables.php
?php
function test(){
echo "I am a Variable Function <br>";
}
test();
$a = 'test';
echo $a;echo '<br>';
$a();
$a();

138

3. function function: - function is define inside another function is called as function-function


Ex: - function's function.php
<?php
Function parent f(){
echo iam write the function function<br>;
If(!function_exists(childF))
{
function child F()
{
echo I need some one to open parent file for me to excute<br>;
}
}
}
Parent F();
Child F();
Parent F()
?>
4. Function with arguments: - function can be defined with one (or) more arguments. It an
arguments is not passed through is define its creates warning in the program
Ex: <?php
function test($x,$y){
echo 'The Value of $x = ',$x,'<br>';

139

echo 'The Value of $y = ',$y,'<br>';


}
test('Raj','Kiran');
test(10,20);
test('Amith');
test();
?>
5. default argument: - a function at the time of a declaration if argument are assign with some
values they will be treated as optional (or) default argument value and they can be passed with
value (or) can left without passing the value. Works at the side default argument must be passing
last in the program at the argument list
Ex: <?php
function test($x=10,$y=20){
echo 'The Value of $x = ',$x,'<br>';
echo 'The Value of $y = ',$y,'<br>';
}
test(100,200);
test('Raj','Kiran');
test();
?>
6. Overloaded argument: - a function can be define with argument (or) that the defined
arguments they are still acknowledge inside the function using various pre-defined function
i) func_num_args(): - return the total number of arguments which are passed in the function

140

ii) func_get_args(): - return the array with all the argument with the function
iii) func_get_args(position): - return the argument value at the specified position
Ex: <?php
function test(){
echo "<h1>Overloaded Concept</h1>";
echo 'The Overloaded Length = ',func_num_args(),'<br>';
print_r(func_get_args());
echo '<hr>';
for($i=0;$i<func_num_args();$i++){
echo 'Index at : ',$i,' - ',func_get_arg($i),'<br>';
}
echo '<hr><h1>For Each Method</h1>';
$y = func_get_args();
foreach($y as $k=>$v){
echo "$k => $v<br>";
}
}
test(10,20,'Rajesh');
7. function with return value: - return key-word can be stop the execution of the
function.return key-word can optionally followed with a value which is return
variable.whenever a function is a valid another one value cont be passed after the return
statement multiple value cont be club as array (or) object and cont be return wherever a
function is called

141

Ex: <?php
function test(){
echo "This is Return Information<br>";
//return 10;
echo "I am second info<br>";
return = 82;
echo "I am second info<br>";
}
test();
$y = test();
echo $y;
//echo $y;
8. i) arguments passed by value: - when an arguments pass by value any change for the value
inside the function owned be reflected in the variable outside the function
ii) Arguments passed by reference: - when an argument pass by resource and change for the
inside with be refer to the variable outside the function

Ex: <?php
function test($x,&$y){
$x +=2;
$y +=10; // $y = $y+10;

142

echo 'The Value of $x = ',$x,'<br>';


echo 'The Value of $y = ',$y,'<br>';
}
$a = 5;
$b = 10;
echo '$a = ',$a,'<br>';//5
echo '$b = ',$b,'<br>';//10
test($a,$b);
echo '$a = ',$a,'<br>';//5
echo '$b = ',$b,'<br>';//10
?>
Built-in functions: Math functions: Ex: <?php
echo 'Math Pi Value = ',M_PI,'<br>';
echo 'Math Pi Value = ',M_PI_2,'<br>';
echo 'Math Pi Value = ',M_PI_4,'<br>';
echo 'Eulers Constant = ',M_E,'<br>';
echo 'SQRT 2 = ',M_SQRT2,'<br>';
echo 'SQRT 2 = ',M_SQRT1_2,'<br>';
echo 'Log of 2 = ',log(2),'<br>';

143

echo 'Log base 10 of 2 = ',log10(2),'<br>';


echo 'Absolute Value = ',abs(-9),'<br>';
echo 'Exponent of 1 = ',exp(2),'<br>';
echo 'pi() = ',pi(),'<br>';
echo 'ceil value = ',ceil(2.1111),'<br>';
echo 'Floor Value = ',floor(2.9999),'<br>';
echo 'round = ',round(2.51458),'<br>';
echo 'round = ',round(2.51558,2),'<br>';
echo 'rad2deg(M_PI) = ',rad2deg(M_PI),'<br>';
echo 'rad2deg(M_PI) = ',rad2deg(M_PI_2),'<br>';
echo 'rad2deg(M_PI) = ',rad2deg(M_PI_4),'<br>';
echo 'deg2rad = ',deg2rad(180),'<br>';
echo 'sin 90 = ',sin(M_PI_2),'<br>';
echo 'tan 45 = ',tan(M_PI_4),'<br>';
echo 'hypot value = ',hypot(3,4),'<br>';
echo 'rand(min,max) = ',rand(100,1000),'<br>';
echo 'min value = ',min(10,20,30),'<br>';
echo 'max Value = ',max(2.999,2.998),'<br>';
?>
Date & time functions: Date: - date is the pre-defined constant in php. It will generate current date according to the no
of arguments pass
Mktime: - which can have arguments (hr, min, sec, month, day, year) unique time stamp

144

Check date(): - let us known the validate in a year


j----> represents day of the month without leading zeros
l---->view letter represents of the day of the way
L---> whether its a leap year (or) not
W---> week number of year weeks starts from Monday
w----> numerical represents of day of the way 0 for Monday through 6 for Saturday
S---> English original safix for the day of the month two character ex: -st ,nd, rd,th
F----> a full representation of the month such as January (or) March
M---> short representation of the month such as jan (or) mar
m---> numerical representation of the month with leading zeros means 0-12
n---> numerical representation of month without zeros which is 1-12
d---> number of days given in a month 28 (or) 31
y---> two digits representation of a year
Y---> it is representation of the full year
Time: -no of milliseconds sec right from unique time stamp
a---> lowercase ante meridiem and post meridiem
A---> uppercase ante meridiem and post meridiem
B---> swatch internet time
g---> 12- hours format of an hour without leading zeros
G---> 24- hour format of an hour without leading zeros
h---> 12- hours format of an hour with leading zeros
H--->24- hours format of an hour with leading zeros

145

i---> minutes with leading zeros


s---> seconds with leading zeros
u---> microseconds (added in php 5.2.2)
Ex: <?php
echo 'Time zone set to : ',@date_default_timezone_get(),'<br>';
date_default_timezone_set('America/Denver');
echo 'Time zone set to : ',@date_default_timezone_get(),'<br>';
echo 'Today Date : ',@date("M-dS-Y, h:i:s a"),'<br><hr>';
date_default_timezone_set('America/Los_Angeles');
echo 'Time zone set to : ',@date_default_timezone_get(),'<br>';
echo 'Today Date : ',@date("M-dS-Y, h:i:s a"),'<br><hr>';
date_default_timezone_set('Asia/Calcutta');
echo 'Time zone set to : ',@date_default_timezone_get(),'<br>';
echo 'Today Date : ',@date("M-dS-Y, h:i:s A"),'<br><hr>';
var_dump(checkdate(02,29,1975));
echo '<hr>No of milliseconds from Unix time Constant ',time(),'<br>';
echo '<hr>Feature Date & time <br>';
echo 'Event is on : ',(date("M-dS-Y, h:i:s a",mktime(7,9,52,8,23,2012))),'<br><hr>';
echo date('Y');

?>

Array built-in function: <?php

146

$a = array(10,20,30);
function r($arr,$func=''){
if(!empty($func)){
echo "<h2 align='center'><u>$func</u></h2>";
}
foreach($arr as $k=>$v){
echo "$k = $v<br>";
}
echo '<hr>';
}
echo 'Array count = ',count($a),'<br>';
echo 'Size of = ',sizeof($a),'<br>';
echo 'Sum of Array = ',array_sum($a),'<br>';
echo 'Product of Array = ',array_product($a),'<br>';
$a =
array('Name'=>'Rajesh','Age'=>30,'Status'=>'Active','Email'=>'Raj@gmail.com','Gender'=>'Mal
e');
r($a,'Normal Array');
$b = array_change_key_case($a,CASE_UPPER);
r($b,'Upper Case');
$b = array_change_key_case($a,CASE_LOWER);
r($b,'Lower Case');
$b = array_flip($a);

147

r($b,'Array Flip');
$b = array_change_key_case(array_flip($a),CASE_UPPER);
r($b,'Array Flip Values');
$a = array('Doctor','Fruit','Software');
$b = array('Patient','Orange','PHP');
r(array_combine($a,$b),'Array Combine');
$a =
array('Name'=>'Rajesh','Age'=>30,'Status'=>'Active','Email'=>'Raj@gmail.com','Gender'=>'Mal
e');
echo '<h2 align="center">Array Chunk</h2>';
$b = array_chunk($a,3);
echo '<pre>';
print_r($b);
echo '</pre>';
$a = array(10,20,30);
$b = array(10,20,40,50);
r(array_merge($a,$b),'Array Merge');
r(array_intersect($a,$b),'Array Intersect');
r(array_diff($a,$b),'Array Diff');
$a =
array('raj@gmail.com','amith@gmail.com','rohan@gmail.com','sumit@gmail.com','raj@gmail.c
om');
r(array_unique($a),'Array Unique');
r(array_reverse($a),'Array Reverse');

148

$a = array(10,20,30);
array_unshift($a,5);
r($a,'Unshift Method');
array_shift($a);
r($a,'shift Method');
array_push($a,40);
r($a,'Push Method');
array_pop($a);
r($a,'Pop Method');
$ns = $ss = $as = $ks =
array('Name'=>'Rajesh','Age'=>30,'Status'=>'Active','Email'=>'Raj@gmail.com','Gender'=>'Mal
e');
r($ns,'Normal Array');
sort($ss);
r($ss,'Sorted Array');
rsort($ss);
r($ss,'Reverse Sort Array');
asort($as);
r($as,'Associative Sort Array');
arsort($as);
r($as,'Associative Reverse Sort Array');
ksort($ks);
r($ks,'Key Sort Method');

149

krsort($ks);
r($ks,'Key Sort Reverse Method');
echo "<h2 align='center'>array_key_exists , array_search , in_array</h2>";
$a =
array('Name'=>'Rajesh','Age'=>30,'Status'=>'Active','Email'=>'Raj@gmail.com','Gender'=>'Mal
e');
echo 'Do i have Email Feild : ',var_dump(array_key_exists('Gender',$a)),'<br>';
echo 'Do we have Value with some : ',var_dump(array_search(30,$a)),'<br>';
echo 'Do we have Value with some : ',var_dump(in_array('Male',$a)),'<br>';
$a =
array('Name'=>'Rajesh','Age'=>30,'Status'=>'Active','Email'=>'Raj@gmail.com','Gender'=>'Mal
e');
r(array_keys($a),'Array Keys Calling');
r(array_values($a),'Array Value Calling');
$str = 'Hey i am from India & my name is Praveen';
$b = explode(" ",$str);
//print_r($b);echo '<br>';
echo 'The Length of your total Words = ',count($b),'<br><hr>';
for($i=0;$i<count($b);$i++){
echo 'The index at ',$i,' = ',$b[$i],'<br>';
}
$a =
array('raj@gmail.com','amith@gmail.com','raju@gmail.com','suresh@gmail.com','raj@gmail.co
m','amith@gmail.com','raju@gmail.com','suresh@gmail.com');

150

print_r($a);
$b = implode(',',$a);
<br><br>
To : <input type='text' name='name' value='<?php echo $b;?>' size='60'/>
<hr>
<?php
$a = array('born','child','teen','father','dead');
r($a,'Normal Array');
echo 'The Present Pointer is at : ',current($a),'<br>And the Key is at ',key($a),'<br>';
echo 'Next : ',next($a),'<br>';
echo 'The Present Pointer is at : ',current($a),'<br>And the Key is at ',key($a),'<br>';
echo 'Previous location : ',prev($a),'<br>';
echo 'The Present Pointer is at : ',current($a),'<br>And the Key is at ',key($a),'<br>';
echo 'End Value : ',end($a),'<br>';
echo 'The Present Pointer is at : ',current($a),'<br>And the Key is at ',key($a),'<br>';
echo 'The Present Pointer is at : ',current($a),'<br>And the Key is at ',key($a),'<br>';
echo 'Reset ',reset($a),'<br>';
echo 'The Present Pointer is at : ',current($a),'<br>And the Key is at ',key($a),'<hr>';
$a = array('Name'=>'Rajesh','Age'=>30);
r(Each($a),'Each Method');
r(Each($a),'Each Method');
$a = array('ram','processor','computer');

151

list($gb,$intel,$dell) = $a;
echo "$gb & $intel together makes $dell faster<br><hr>";
$str = "write some large text matter.";
echo $str,'<br><hr>';
echo '<h2>Wordwrap</h2>';
echo wordwrap($str,20,'<br>',true);
?>
String builtin function: <?php
echo '<h2>';
$str = "lamp institute";
echo "Normal String = ",$str,'<br>';
echo "Length of String = ",strlen($str),'<br>';
echo "To Upper Case = ",strtoUpper($str),'<br>';
echo "To Lower Case = ",strtoLower($str),'<br>';
echo "Upper case First Word = ",ucfirst($str),'<br>';
echo "Upper case words = ",ucwords($str),'<br>';
echo 'Reverse = ',strrev($str),'<br>';
echo '<hr>';
echo 'Position of str = ',strpos($str,'t'),'<br>';
echo 'last Position of str = ',strrpos($str,'t'),'<br>';
echo 'Postion of str after t again = ',strpos($str,'t',9),'<br>';

152

echo 'Position insensitive = ',stripos($str,'lamp'),'<br>';


echo 'last position at t insensitive = ',strripos($str,'T'),'<br>';
echo 'strstr will extract the entire string : ',strstr($str,"In"),'<br>';
echo 'strstr will extract the entire string : ',stristr($str,"in"),'<br>';
$name = 'Rajesh Kumar';
echo "substr = ",substr($name,0),'<br>';
echo "substr = ",substr($name,7,4),'<br>';
echo "substr = ",substr($name,-5,-1),'<br>';
$url = 'http://www.google.com?status=active';
$url .= '&';
echo 'substr = ',substr($url,0,-1),'<br>';
echo 'replace = ',str_ireplace('lamp','Apache',$str),'<br>';
$a = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
echo str_shuffle($a),'<hr>';
echo substr(str_shuffle($a),0,12);
echo '<hr>';
$name = "O'henry";
echo $name,'<br>';
echo addslashes($name),'<br>';
echo stripslashes('O\'henry'),'<br>';
echo strip_tags("<b><i>Hi i am not feeling well</i></b>");
echo '<hr>';echo '<h2>';

153

$pwd = 'computer';
echo 'Original Name : ',$pwd,'<br>';
echo '<h1 align="center">One Way Encrypt</h1>';
echo 'Encrypt with MD5 = ',md5($pwd),'<br>';//32 char value
echo 'Encrypt with MD5 strict = ',md5($pwd,true),'<br>';//16 bit binary format
echo 'Encrypt with sha1 = ',sha1($pwd),'<br>';//40 char vlaue
echo 'Encrypt with sha1 strict= ',sha1($pwd,true),'<br>';//20 binary vlaue
echo 'Crypt = ',crypt($pwd),'<br>';
echo 'crypt salt = ',crypt($pwd,'d4'),'<br>';
echo '<h1 align="center">Encrypt & Decrypt Method</h1>';
echo 'encrypt = ',base64_encode($pwd),'<br>';
echo 'decrypt = ',base64_decode('Y29tcHV0ZXI='),'<br>';
echo '<h1 align="center">Url Encode & Decode</h1>';
$url = 'http://www.lamp.com?status=success&id=7&pid=20';
echo 'Original url = ',$url,'<br>';
echo 'encode = ',urlencode($url),'<br>';
echo 'decode = ',urldecode('http%3A%2F%2Fwww.lamp.com%3Fstatus%3Dsuccess%26id
%3D7%26pid%3D20'),'<br><hr>';
echo '<pre>';
$name = "

Rajesh

";

echo 'My name is :',$name,'<br>';


echo 'My name is :',rtrim($name),'<br>';
echo 'My name is :',ltrim($name),'<br>';

154

echo 'My name is :',trim($name),'<br>';


echo '</pre>';
Path: FILE:- The full path and filename of the file. If used inside an include, always contains an
absolute path with symlinks
LINE:-The current line number of the file.
DIR:-The directory of the file.
Realpath:-Returns absolute pathname
Basename:-Returns filename component of path
Ex: <?php
echo "File Information : ",__FILE__,'<br>';
echo "Base Name : ",basename(__FILE__),'<br>';
echo "Directory Name : ",dirname(__FILE__),'<br>';
echo "Directory Name : ",__dir__,'<br>';
echo "real Path : ",realpath(__FILE__),'<br>';
//echo "real Path : ",realpath('../..'),'<br>';
echo "Line NO : ",__LINE__,'<br>';
echo '<hr>';
$a = pathinfo(__FILE__);
//print_r($a);
foreach($a as $k=>$v){
echo $k,' = ',$v,'<br>';

155

}
File-function: 1) stat(file path) : file function Return an array with file information
2)is_file(file path) : checks wheather the file exist or not & Returns boolean.
3)file_get_contents(file Path) : Returns the file content as a string.
4)file_put_contents(fiel path,data) : writes the content to the file overwriting old content &
iffile does not exists, creates a new file & adds the content..This function is introduced in 5th
version)
5)file(file path) : Returns the file content as an array with each line in the file at a particular
index position.
6)filectime(path) : creates the time of the file.
7)fileatime(file path) : last access time of the path file.
8)filemtime(file path) : last modified time of the file.
9)unlink(file path) : Removes the file from the location.
10)filesize(file path) : Returns the size of the file in bites..
11)filetype(file Path) : Returns the type of the file..(dir or file)
fopen(file path,mode) : Opens the file in the specified mode &returns a file handler for
handling the file.
fread(file handler, size) : Reads the file content from the current file handler position upto the
specified size.
$fp -> file Pointer ..The internal handler which is used for handling the file.
fgetc(file handler) : Reads a single char in the string.
fgets(file handler) : Reads a single line from the file..
fgetss(file handler) : Reads a single line from the file stripping of html tags in the file...

156

fwrite(file handler) : This function is used to write the content to the file..
ftell(file handler) : retruns the file handler position in the file
fseek(file handler) : Moves the file handler to the specified position in the file
fclose(file handler) : Closes the File handler connection.
List of Modes :
r

--> Read Mode

r+

--> Read and Write.

--> Write Mode

w+

--> Write & Read.

--> Append (also writing but without overwriting files)

a+

--> append & read.

--> Creates a new file & write..

x+

--> Creat a new file for write and read.

rb,rb+,wb,wb+,ab,ab+,xb,xb+ are the modes to be used for binary files


for above specified action...
fileput.php
<?php
$file = 'a.txt';
file_put_contents($file,str_repeat("MOd ",5));
create.php
<?php

157

$file = 'c.txt';
$fp = fopen($file,"x");
fwrite($fp," Created");
fclose($fp);
if(is_file($file)){
echo file_get_contents($file);
}
write.php
<?php
$file = 'b.txt';
$fp = fopen($file,"w");
fwrite($fp,"Modified");
fclose($fp);
if(is_file($file)){
echo file_get_contents($file);
}
read.php
<?php
$file = 'test.txt';
$fp = fopen($file,"r");
echo "Pos : ",ftell($fp),'<br>';
echo fread($fp,3),'<br>';

158

echo "Pos : ",ftell($fp),'<br>';


echo fgetc($fp),'<br>';
echo "Pos : ",ftell($fp),'<br>';
echo fgets($fp),'<br>';
echo fgets($fp),'<br>';
echo 'Pos : ',ftell($fp),'<Br>';
echo fgets($fp),'<br>';
fseek($fp,35);
echo fgetss($fp),'<br>';
fclose($fp);
func.php
<?php
$file = 'test.txt';
var_dump(is_file($file));
echo '<br>';
echo "size : ",filesize($file),'<br>';
echo "Type : ",filetype($file),'<br>';
echo "Created : ",date("d-m-y h:i:s",filectime($file)),'<br>';
echo "Accessed : ",date("d-m-y h:i:s",fileatime($file)),'<br>';
echo "Modified : ",date("d-m-y h:i:s",filemtime($file)),'<br>';
echo file_get_contents($file),'<br>';
echo "<pre>";

159

print_r(file($file));
echo '<br>';
print_r(stat($file));
append.php
<?php
$file = 'b.txt';
$fp = fopen($file,"a");
fwrite($fp,"Append");
fclose($fp);
if(is_file($file)){
echo file_get_contents($file);
}
unlink.php
<?php
$file = 'a.txt';
unlink($file);
Directory files: getcwd() : current working directory,
chdir(path) : change current working dir to argumented path.
is_dir(path) : checks wheather the argumented dir exist or not and return boolean.
mkdir(dirname) : makes a directory on the current working location.
rename(old name,new name): changes the name of the directory.

160

rmdir(dir name) : removes the directory.


scandir(path) : scan the dir & return the directory content as an array .. Returns an array with
path related information.
getcwd.php
<?php
echo 'Cwd : ',getcwd(),'<br>';
$a = scandir('.',0);
foreach($a as $k=>$v){
echo "$k == $v<br>";
}
chdir('..');echo '<hr>';
echo 'Cwd : ',getcwd(),'<br><hr>';
$a = scandir('.',0);
foreach($a as $k=>$v){
echo "$k == $v<br>";
}
mkdir.php
<?php
$dir = 'test';
if(!is_dir($dir)){
mkdir($dir);
echo "Directory is created";
}

161

else {
echo "Directory already exists";
}
rename.php
<?php
$dir = 'test';
$new = "modified";
if(is_dir($dir)){
rename($dir,$new);
echo "Directory name is $new";
}
else {
echo "Directory does not exists";
}
rmdir.php
<?php
$new = "modified";
if(is_dir($new)){
rmdir($new);
echo "Directory is removed";
}
else {

162

echo "Directory does not exists";


}
scandir.php
<?php
echo '<pre>';
var_dump(scandir('.'));
Super globals: Difference between GET and POST:-

GET

POST

1.GET data transfers through URL.

POST data is send through request headers

2.GET is insecure

POST is secure

3.File cannot be transfered using GET

Files can be transfered

4.Limited data can be send based on length


scaled

We can send huge data(8MB) which can be

of URL supported by browser(2KB).

up by using POST_MAX_SIZE

5.It is fast

It is not as fast as GET.

6.$_GET is used for accessing the GET parameters $_POST is used for accessing the POST
Get ex: - get.php
<?php
if(isset($_GET['submit'])){
echo 'Name : ',$_GET['fname'],'<br>';
echo 'Email Address : ',$_GET['email'],'<br>';
$gend = ($_GET['gender'] == 'm')?'Male':'Female';

163

echo 'Gender : ',$gend,'<br>';


}

echo '<hr>';
echo urldecode($_SERVER['QUERY_STRING']);echo '<hr><br>';
get.html
<form method='GET' action='get.php'>
Name : <input type='text' name='fname' value=''><br>
E-Mail : <input type='text' name='email' value=''><br>
Gender : <input type='radio' name='gender' value='m'> Male <input type='radio' name='gender'
value='f'> Female<br>
<input type='submit' name='submit' value='Register !'>
</form>
Post ex: - post.php
<?php
if(isset($_POST['submit'])){
echo 'Name : ',$_POST['fname'],'<br>';
echo 'Email Address : ',$_POST['email'],'<br>';
$gend = ($_POST['gender']=='m')?'Male':'Female';
echo 'Gender : ',$gend,'<br>';
$a = $_POST['course'];
echo $a,'<br><hr>';
print_r($a);

164

}
echo '<hr>';
echo 'The query string : ',$_SERVER['QUERY_STRING'],'<br>';
post.html
<form method='POST' action='post.php'/>
Name : <input type='text' name='fname' value=''/><br>
E-Mail : <input type='text' name='email' value=''/><br>
Gender : <input type='radio' name='gender' value='m'/> Male <input type='radio' name='gender'
value='f'/> Female <br>
Hobbies : <br>
<input type='checkbox' name='course[]' value='c'/> C-Language <br>
<input type='checkbox' name='course[]' value='p'/> PHP <br>
<input type='checkbox' name='course[]' value='j'/> Java <br>
<input type='submit' name='submit' value='Register'/>
</form>
Server variables: servervariables.php
<?php
echo 'Get Environment : ',getenv('os'),'<br>';
echo 'Environment Path : ',getenv('path'),'<br>';
echo '<hr>';
echo 'Document Root : ',$_SERVER['DOCUMENT_ROOT'],'<br>';
echo 'Http Host : ',$_SERVER['HTTP_HOST'],'<br>';

165

echo 'Referer : ',$_SERVER['HTTP_REFERER'],'<br>';


echo 'Method : ',$_SERVER['REQUEST_METHOD'],'<br>';
echo 'User Agent : ',($_SERVER['HTTP_USER_AGENT']),'<br>';
echo 'Name of Script : ',$_SERVER['SCRIPT_NAME'],'<br>';
echo 'Query String : ',$_SERVER['QUERY_STRING'],'<br>';
echo 'Remote Ip Address : ',$_SERVER['REMOTE_ADDR'],'<br>';
echo 'PHP Self : ',$_SERVER['PHP_SELF'],'<br>';
echo 'Request URL : ',$_SERVER['REQUEST_URI'],'<br>';
echo 'Script File Name : ',$_SERVER['SCRIPT_FILENAME'],'<br>';
phpinfo.php
<?php
echo phpinfo();
Include_once and required _once: - these both will include file very first time and if already
file has been included this will not include for the second time.
Defference between include_once & include: - include and include _once will include the
files. But if the path of the file is wrong include and include_once will generate the wrong
message and rest of the code will be excuted
Required and required_once: - if location of the path is given wrong this will through a wrong
as well as path error and code gets alted for the execution will be stop
Note: -include and require if you are calling a file you have to be predation whether the file
having aret if function exist if you have to make function as it using function exist as a method
Ex: - a.php
<style>
b{color:green;}

166

</style>
<b>I am included</b><br><hr>
<?php
$a = 10;
if(!function_exists('r')){
function r(){
echo 'I am in a.php and working fine<br>';
}
}
?>
b.php
<?php
include_once("a.php");
include("a.php");
include("a.php");
$b = 20;
echo 'The Value of $a = ',$a,'<br>';
echo 'The Value of $b = ',$b,'<br>';
r();
?>
------------------------------------------------------------------------------------------------------------------Headers: - Headers are the information which are exchanged between client and server for
every request and response.

167

Headers are of two types.


a) Request Headers.
b) Response Headers.
a) Request Headers:-These are send from client to server.
b) Response Headers:-These are send from server to client.

Request Headers:
HTTP Request : GET/php7/info.php HTTP/1.1
Host

: localhost

User_Agent

: Mozilla/5.0

Accept

: text/HTML, application/html

Accept_encoding

: gzip,deflate

Connection

: keep-alive

keep-alive

: 115

Accept_char : ISO-88591-1 utf-8;q=0.7


Ex:-

apache_request_headers()

Response Headers:
X-powered-by

: php/5.3.1

keep_Alive

: timeout=5,max=100

connection

: Keep_Alive

Transfer_Encoding

: chunted

content_type

: text/html

Ex:-apache_response_headers()
HTTP methods: - For every request from the client to server can be made through various
HTTP methods like
GET, POST, PUT, DELETE, HEAD
Headers can be send from php program to the server.

168

1. headers_list():- Returns an array to the list of the headers which can be shared from server to
client.
2. headers_sent ():-Returns the boolean value above whether the headers were send to the
client or not.
3.header("<name>:<value>"):-header function should be used in the page before any output
is send to the page.
header functions are used for redirection. header function is used for sending the output of the
php content in different formats(content type like html,xhtml,images,pdf,flash,video etc).
header function is used for downloading of the files.
Ex: - hrds.php
<?php
ob_start();
print_r(apache_request_headers()); echo '<hr>';
var_dump(headers_sent());
header("Name:Rajesh");
header("location:info.php");
print_r(headers_list());
echo '<hr>';
print_r(apache_response_headers());
?>
info.php
<?php
echo phpinfo();
?>
-------------------------------------------------------------------------------------------------------------------

169

Dwonloading: -Download of a file is done by sending few headers followed with reading of
source file from the server sending a content type header
header("Content-Type:<mine Type>");
pdf -> application/pdf.
html -> text/html.
jpg/png/gif -> image/(jpg || png || gif).

Step 2: Sending a content Disposition header which will tells the browser to open the file or to
ask the user about the file.
header("Content-Disposition:<mode>;filename=<filename>");

----->Inline
----->attachement

Optionally we can sent content length header with the size of the file.
Step 3: header("Content-Length:<filesize(finename)>");

Reading the Original file: readfile(<path of file>)-- -> Reads the file Content & prints to the browser..
Ex: - download.php
<?php
$file="01.jpg";
$type="image/jpg";

170

$mode="inline";
header("Content-Type:".$type);
header("Content-Disposition:".$mode.";filename=".$file);
header("Content-Length:".filesize($file));
readfile($file);
?>
down.php
mage down <a href="download.php"/>View Please</a>
------------------------------------------------------------------------------------------------------------------File Uploading: upload_tmp_dir(<path>) -> default is set to c:\xampp\tmp The temporary location to which
the file can be uploaded to the server
upload_max_filesize : (<128>) The max size for a single file which can be uploaded to the
server -> max_file_uploads : 20..
Functions in upload: copy of source destination :- copy the file from source location to destination folder
is_upload_file(source path): - checks wheather file upload or not and return boolean..
move_upload_file (<source path, destination>): -moves the file from source location to
destination location
Predefined variables: - $_FILES is predefined super global file which will be loaded with the
Properties of uploaded file.
Properties in file upload:1. $_FILES[<file_field_name>]['name']:- It returns the original name of the uploaded file.

171

2. $_FILES[<file_field_name>]['tmp_name']:- It returns the temporary path to the uploaded


file.
(It acts as the source path of the uploaded file in the program).
3. $_FILES[<file_field_name>]['size']:- It returns the size of the uploaded file in bytes.
4. $_FILES[<file_field_name>]['type']:- It gives the MIME(Multipurpose Internet Main
Extension)
type for the uploaded file.
5. $_FILES[<file_field_name>]['error']:- It returns the error code associated with the file
upload.
If its value is configured to zero indicates no error
Ex :- testupload1.php
<?php
if(isset($_POST['submit'])){
if(isset($_FILES['photo'])){
$src = $_FILES['photo']['tmp_name'];
$desc = "pics/".getRandString(12).$_FILES['photo']['name'];
if(move_uploaded_file($src,$desc)){
echo 'Image saved successfully<br>';
}

else {
echo 'Image not saved<br>';

}
}
}

echo '<hr>';
function getRandString($size){

172

$a =
str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789
0');
return addslashes(substr($a,0,$size));
}
Ex: - testupload2.php
<?php
if(isset($_POST['submit'])){
if(isset($_FILES['photo'])){
$src = $_FILES['photo']['tmp_name'];
$desc = "pic/".getRandString(40).' - '.$_FILES['photo']['name'];
if(move_uploaded_file($src,$desc)){
echo 'Image saved successfully<br>';
}

else {
echo 'Image not saved<br>';

}
}
}

echo '<hr>';
function getRandString($size){
$a =
str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789
0');
return crypt(substr($a,0,$size));
}
test.php
<form action='testupload.php' method='POST' enctype='multipart/form-data'/>

173

Upload Photo : <input type='file' name='photo'/> <input type='submit' name='submit'


value='Upload'/>
</form>

COOKIES
Cookies are super global variables which can be stored at client machine.

$_COOKIE:- It is a predefined super global variable which can be used for reading cookie
data.
setcookie(<name>,<value>):- It is a predefined function for creating, updating or deleting the
cookie variable at server machine.
cookie values are stored at the browser of client's machine
cookiews are not safe for storing the information.
Every webbrowser is limited to a certain no. of cookies to be stored at the client's machine(~20).
Cookies information will be exchanged between the client and server every request and
response
through headers.
If Cookie is once created can be accessed from the next request from the server to the client but
not in the same page.
setcookie(<name>,<value>,[<lifetime>],[<domain>],[<path>],[<secure protocol>])
lifetime:- timestamp upto which cookie must be active.
time()+24*60*60
domain:-news.abc.com
gmail.com
path:-Default path is current working directory
/-->points to root directory
/abc--->cookie is shared with all files in abc folder

174

secure_protocol:-If it is true then it will be exchanged with https protocol otherwise with http
protocol
Cookie can be created in two ways.
1. By creating cookie with empty value.
2. By creating the cookie in the past
Ex: - create.php
<?php
ob_start();
print_r($_COOKIE);
setcookie('c',10,time()+3600);//set cookie
echo "<br>";
print_r($_COOKIE);
setcookie('c',88,time()+3600);//modify or update
echo "<br>";
setcookie('c',"",time()+3600);//delete
echo "<br>";
setcookie('c',"abc",time()-3600);//delete
echo "<br>";
?>
setcookie will sends a header to the server(No output is sent before using.
If output is started before it use output buffering

SESSIONS:It is used for maintaining the state of the user between his login and logout.
$_SESSION is a predefined super global used for managing session data.

175

session information is stored at the server machine and is accessable with the pages
where session is started.
Configuration settings:session.auto_start(OFF):-Controls whether the session must be automatically started or not
session.name=PHPSESSID:- The default name at which session id is stored at a client
machine
as cookie variable
session.use_cookie(ON*/OFF):-Using the cookies for storing the session id value.
session.use_only_cookies:-Using cookies only for storing the session id.
session.use_trans_sid(0/1_:-Using a transferable session id through URL.
session.gc_maxlifetime(1440(24minutes)):-The maximum time for which the session data can
be
maintaines when the user is idle before sending to gc(garbage collector).
FUNCTIONS in SESSIONS:session_start():- starts a new session for the user, if session already axists uses the already
existing session.
session_name[<optional_name>]:-Gets or sets the name of the session
session_id():- It returns the session id created for the user. A session id is a unique 32 character
length alphanumeric value.
session_regenerate_id:- changes the session id to new one for the user.
session_unset:-Erases the session data for the user.
session_destroy:-session will be destroyed.
Ex: - session.php
<?php
ob_start();
session_start();
echo 'Session Name : ',session_name(),'<br>';

176

echo 'Session Id : ',session_id(),'<br>';


echo 'Session Name : ',session_name('Rajesh'),'<br>';
echo 'Session Name : ',session_name(),'<br>';
echo 'Session generate Id : ',session_regenerate_id(),'<br>';
echo 'Generated Id : ',session_id(),'<br>';
echo 'Life time : ',(ini_get('session.gc_maxlifetime')/60),' mins<br>';
echo 'Session save Path : ',ini_get('session.save_path'),'<br>';
echo 'Cookie Save Path : ',ini_get('session.cookie_path'),'<br>';
$_SESSION['Name'] = 'Praveen';
$_SESSION['Email'] = 'raj@gmail.com';
print_r($_SESSION); echo '<hr>';
print_r($_COOKIE);echo '<hr>';
session_destroy();
echo 'Session Id : ',session_id(),'<br>';
print_r($_SESSION);
unset($_SESSION['Name']);echo '<hr>';
print_r($_SESSION);
echo '<hr>';
print_r($_COOKIE);

global configuration settings: Understanding Configuration settings in PHP:

1) POST_MAX_SIZE: - max size of post data that a php will accept

177

2) magic_quotes_gpe: (default value is ON)


escaping of " Quotations with a backslash for the data which is sent through
GET,POST,COOKIE & ENV variables
3) Register_globals: - possible values are (ON or OFF)
default is OFF..
Registering of super global variable as regular variables in this page is controlled with
this settings

4) variables_order: - "GPCS";
The order with which superglobal variable are loaded with the current working page

5) Register_long_arrays: - ON or OFF
The availability of superglobals array with logn array names used in the older version of
PHP is controlled with this settings

6) file_uploads: ( ON) wheather to allow HTTP Files to upload or not;

Buffer: - Buffering of the output before sending with browser can be handled by using output
buffering.
Configuration setting:output_buffering = 4096
Buffers the output upto 4KB and releases the output
Functions:ob_start():- Starts buffering the output if buffering is inactive.
ob_get_length:- It returns the size of buffer content in the page
ob_flush():- It sends the buffer content to the browser.
ob_get_flush():- It returns the buffer content as a string and sends the buffer to the browser.

178

ob_clean():- It clears the buffer and stops the buffering.


ob_get_clean:- It cleans the buffer content and returns it as a string.
Note:- output buffering is used when we are working with sessions using headers with in the
page.
Ex: - buffer.php
<?php
ob_start();
echo 'Line 01<br>';
echo 'Line 02<br>';
echo ob_flush(); //implicit_flush = Off;
header("Name:Rajesh");
//echo ob_get_length();
echo '<hr>';
echo ob_get_contents();
?>

179

180

MySQL
MySQL is a Open Source database server which is developed on top of c & c++ Languages.
MySQL supports many programming & Scripting languages for providing access to the data
like C,C++,Java,.Net,PHP,PERL,Python etc..
MySQL was initally developed by MySQL-AB Group of sweaden, which was merge with Sun
Microsoft system in Aug 8th, 2008..
MySQL Supports ANS Based SQL FOR Communicating with database server MySQL will
allow the SQL statement to get executed through various channel like..
1) GUI Tools(Graphic user Interface),MySQL Administrator, SQLyog, SQL etc
2) Web Based Tools(phpmyadmin, SQL ETC...)
3) COMMAND lINE INTERFACE : Accessing local database Server Locally
4) Data : This is collection of information
Database : It is a collection of Data
DBMS (Data Base Management System) is Suggests the internal Organization in Database
Server.
DBMS is used for defining Structural architecture of db & internal Organization of the data in
Various types of DBMS
1)HDBMS (Hierarchical Data Base Management System)
2)NDBMS (Network Data Base Management System)
3)RDBMS (Relational Data Base Management System)
4)ODBMS (Object Data Base Management System)

181

5)ORDBMS(Object Based Relational Data Base Management System)

RDBMS : In RDBMS a db is considered as a collection of tables, each table is a collection of


records, each record consist of collection of data set (cols,rows).
E.F.CODD:- 12 Rules of RDBMS..can be found at (http://www.cse.ohiostate.edu/~sgomori/570/coddsrules.html)
NormaliZation : 5 Forms(1st three has to understood);
SQL : Structural Query Language which is used for Communication with data base Server.
Database Server: It is a Software which will receive the request in SQL & sends the data as the
response...
Eg: MySQL,Oracle,Sybase,Postgre SQL,DB2,MSSQL,MS AXIS etc..
SQL:
DDL(Data Defination Language)
CREATE -------------|---> Database
|---> Table
|
|
DROP ---------------|---> Database
|---> Table
|
ALTER---------------|--->Used for Tables
|--->ADD
|--->CHANGE

182

|--->DROP
TRUNCATE------------|--->TABLE
DML:(Data Manupulation Language)
|-->INSERT INTO
|-->UPDATE SET
|-->DELETE FROM
DRL :(Data Retrivel Language)
|-->SELECT |---> WHERE <cond>
|---> ORDERED BY <field-Name>
|---> GROUP BY <field-Name>
|---> LIMIT <start>,<end>
DCL :(Data Controlling Language)
|--> ADMIN ZONE
DGL :(Data Grant Language)
|--> Giving Special Permission.
Data Base Level Query :
SHOW DATABASES --> Return the List of Databases
CREATE DATABASE --> <db_name> Creates a database if it is not Existing.
a)

USE <db_name> --> Select a database for executing further Queries in the Table

b)

DROP DATABASE<db_name> Deletes the database from the database server

Completely with its Tables and data...


Table Level Query :
SHOW TABLES[FROM <db_name>];

183

CREATE TABLE
<table_name>(<field_name><datatype>[<size>]<add_parementers><field_info);
ALTER TABLE <table_name> ADD <field_info>;
CHANGE <field_name> <new_field_info>;
ALTER TABLE <table_name> DROP <field_name>;
RENAME <new_name>;(Renaming a Table)
TRUNCATE <table_name>;
This will empty the table.. Removes the complete data of the table but the
structure of table remains in the database..
DROP<table_name>;Removes the table data & its Structure;
Data Level Query : Data manupulation Language:
INSERT INTO <tbl_name> [(<field_list>)] VALUES [(<value_list>),(<value_list2),
(value_list3)...];
UPDATE <tbl_name> SET <field_name> = <new_value> WHERE <cond>;
DELETE FROM <tbl_name> WHERE <cond>;
Data RETRIVAL QUERY:
SELECT (* or <field_list>) FROM <tbl_name> [WHERE <cond>] ORDERED BY
<field_name> ASC/DESC [GROUP BY <field_name> LIMIT <start_index>[,<length>]];
Numerical Datatypes in MYSQL :
1) Tiny Int : [2pow8 -1] 0-255 --->UNSIGNED
[-128-127] --> SIGNED
2) Small Int : 2 bytes [2pow16-1]UNSIGNED
-32767 TO -32767 --> SIGNED
3) Mediun Int : 3 bytes [2pow24-1]

184

UNSIGNED int [16777215]


SIGNED int [-8388607]
4) Int : 4 bytes [2pow31-1]
SIGNED Int Range [2147483647]
5) BigInt : 8 bytes [2pow64-1]
0 - 1.84467440737096e+14 20digits
Size of integer will specify the total number of digits
Additional Parameter SIGNED OR UNSIGNED default Value is SIGNED.
6) float(<no of digits>,<precision>);
A small number wit a floating Value
10POW38 0-24(falls in float)
7) Double(no of digits>,<precision>); A Large Number with a floating Decimal Point(25-5
8) Decimal() :- A double stored as a string, allowing for a fixed decimal point.
9) Char() : A fixed Section from 0 to 255 character Long.
10) varchar(): A variable section from 0-255 char long.
Miscellaneous Types:
ENUM() : short for Enumeration which means that each coloum may have one of a specified
possible Value;
Text : String Content 65kb for this size is needed...
medium text : 0 - 16777215 char (16mb) can be accomidated in medium text..
long text: 0 to upto 4gb long text

185

Data types: ENUM : Enumeration field used for storing Optional values amone which one
value can be selected while inserting (0-65535) max no of optional which are allowed all string
value must be enclosed in "Quotations" while inserting...
Date Date types:
Date : YYYY-MM-DD
(0000-9999) allowed dates
Time : hh:mm:ss
Date & Time : YYY-MM-DD hh:mm:ss
TIME STAMP : Default insert the current date & time values..
yyyymmdd hhmmss -- 14
yyyymmdd hhmm -- 12
yymmddhhmm -- 10
yyyymmdd -- 8
yymmdd -- 6
Year : 4-digits Year number All date values must be enclosed in Quotation during insertion.
Binary Data Types
Binary : Fixed length binary content (similar to char)
Var binary : it is variable length binary content similar to varchar...
Blob : binary Large Object similar to text data type
Medium Blob : Similar to medium Text..
Long Blob : similar to Long Text..
Additional Parameters:

186

1) PRIMARY KEY :- Atleast one field in a table must be declared as primary key, it is
UNIQUE it is by default an INDEX for the table. it can't be NULL.
2) FOREIGN KEY:- The field which establish a relation to the primary key field of ther table
is foreign Key.
3) UNIQUE :- The field apart from primary Key which needs to be UNIQUE can be applied
with this field..
4)CURRENT_TIMESTAMP :- Predefined constant which can store current time stamp value
by default at the time of inserting the date or time.. On update current-time stamp it is used for
adding current time stamp at the time of updation...
5) AUTO_INCREMENT :-Increase the value by one automatically for every row record entry..
Create
CREATE TABLE eg_user(
Id SMALLINT(5) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
EmailId VARCHAR(100) NOT NULL UNIQUE,
Pword CHAR(32) NOT NULL,
Gender ENUM('Male', 'Female') NOT NULL,
DateOfBirth DATE NOT NULL,
RegisteredOn TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
uStatus ENUM('Inactive', 'Active') NOT NULL
)
DESC eg_user;
DESCRIBE eg_user;
EXPLAIN eg_user;
//inserting record

187

INSERT INTO eg_user


(EmailId, Pword, Gender, DateOfBirth)
VALUES
('mra@xyz.com', MD5('abc'), 'Male', '12-12-1980')
//list all records of table
SELECT * FROM table_name
//inserting multiple records
INSERT INTO eg_user
(EmailId, Pword, DateOfBirth, Gender)
VALUES
('mrb@xyz.com', MD5('1'), '1979-10-19', 'Male'),
('msc@xyz.com',MD5('a'), '1980-5-12', 'Female'),
('mrd@xyz.com',MD5('ab'), '1972-6-10', 'Male'),
('mse@xyz.com', MD5('AB'), '1989-12-12', 'Female')
//modifying the record
UPDATE eg_user SET DateOfBirth='1980-12-8', uStatus='Active' WHERE Id=1
DELETE FROM eg_user WHERE Id=5;
TRUNCATE TABLE tbl_name;
//create emp table
CREATE TABLE eg_emp(
Id SMALLINT(5) UNSIGNED PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(30) NOT NULL,

188

Salary DECIMAL(10,2) NOT NULL,


Location VARCHAR(50) NOT NULL) AUTO_INCREMENT=101;
//INSERTING RECORDS
INSERT INTO eg_emp
(Name, Salary, Location)
VALUES
('Mr. A', 5000, 'Hyd'),
('Mr. B', 4500, 'Mumbai'),
('Ms. C', 6000, 'Delhi'),
('Mr. D', 7000, 'Delhi'),
('Mr. B', 5000, 'Hyd'),
('Ms. E', 3000, 'Hyd');
//read records for only specified columns Name, location
SELECT Name, Location FROM eg_emp;
//list emps with salaries < 5000
SELECT * FROM eg_emp WHERE Salary<5000;
//list emps whose salary is either 3000, 5000, 4000, 7000
SELECT * FROM eg_emp WHERE
Salary=3000 OR Salary=5000 OR Salary=4000 OR Salary=7000
SELECT * FROM eg_emp WHERE
Salary IN(3000,5000,4000, 7000)
//list emps whose salaries are between 5000 & 8000

189

SELECT * FROM eg_emp WHERE Salary>=4500 AND Salary<=8000;


SELECT * FROM eg_emp WHERE
Salary BETWEEN 5000 AND 8000;
//list users born between 1-1-1970 and 31-12-1980
SELECT EmailId, DateOfBirth, Gender
FROM eg_user WHERE
DateOfBirth BETWEEN '1970-1-1' AND '1980-12-31';
SELECT CURRENT_DATE
SELECT CURRENT_TIME;
SELECT MONTH(CURRENT_DATE)
SELECT MONTHNAME(CURRENT_DATE);
SELECT WEEKDAY(CURRENT_DATE)
SELECT DAY(CURRENT_DATE)
SELECT DAYNAME(CURRENT_DATE)
SELECT EmailId, DateOfBirth
FROM eg_user
WHERE
MONTH(DateOfBirth) = 12;
SELECT COUNT(Id) FROM eg_user;
SELECT SUM(Salary) FROM eg_emp;
SELECT SUM(Salary) FROM eg_emp
WHERE Location='Hyd';

190

SELECT MAX(Salary) AS HighestSalary


FROM eg_emp;
SELECT MIN(Salary) LeastSalary
FROM eg_emp;
//no. of emps for every location
SELECT COUNT(*) TotalEmps, Location
FROM eg_emp
GROUP BY Location;
//no. of emps for every location with salary > 4000
SELECT COUNT(*) TotalEmps, Location
FROM eg_emp
WHERE Salary>4000
GROUP BY Location;
//list of locations with 2 or more emps having salary>4000
SELECT COUNT(*) TotalEmps, Location
FROM eg_emp
WHERE Salary>4000
GROUP BY Location
HAVING TotalEmps>1;
//Salary in descending order
SELECT * FROM eg_emp
ORDER BY Salary DESC;

191

//Salary in desc, with Id desc


SELECT * FROM eg_emp
ORDER BY Salary DESC,
Id DESC;
//list second highest earner
SELECT * FROM eg_emp
ORDER BY Salary DESC
LIMIT 1,4;
CREATE TABLE brand(
Id TINYINT(2) UNSIGNED PRIMARY KEY AUTO_INCREMENT,
BrandName VARCHAR(50) NOT NULL
);
INSERT INTO brand(BrandName) VALUES
('Adidas'),('Nike'),('Nokia'),('Titan'),('Lg');
CREATE TABLE category(
Id TINYINT(2) UNSIGNED PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(50) NOT NULL
);
INSERT INTO category(Name) VALUES
('Mobiles'),('T-Shirts'),('Jeans'),('Watches'),('Electronics'),('books');
CREATE TABLE products(
Id SMALLINT(5) UNSIGNED PRIMARY KEY AUTO_INCREMENT,

192

Name VARCHAR(50) NOT NULL,


Amount DECIMAL(10,2) NOT NULL,
in_Stock TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
c_id TINYINT(2) UNSIGNED NOT NULL,
b_id TINYINT(2) UNSIGNED NOT NULL
);
INSERT INTO products(Name,Amount,c_id,b_id) VALUES
('Smart watch',612.954,4,4);
SELECT * FROM products,category;
SELECT p.Name,p.Amount,c.Name FROM products p,category c;
SELECT p.Name Products,p.Amount,p.in_Stock,c.Name Category FROM products p,category
c WHERE p.c_id = c.Id;
SELECT p.Name Products,p.Amount,p.in_Stock,c.Name Category,b.BrandName FROM
products p,category c,brand b WHERE p.c_id = c.Id AND p.b_id = b.Id ORDER BY Amount
DESC;
PHP by Default Support With Mysql library,,
PHP communication with Mysql can be Splitted int some steps like
1) Connecting to the Database
2) Selecting to the Database
3) Query the Database
4) Fetching the Records of Getting the records From Query or Query String..
5) Close the Connection...
---> Among them We have

193

A) Normal Connection

B) Persistance Connection

Normal Connection:- will be active for the Single Program, A Normal Connection can be
Closed by Using mysql_close();
Normal Connection : mysql_connect('hostname','username','password');
B) Persistance Connection : A Persistance Connection is a Parmanent Connection Once
establish it cannot be closed..
mysql_pconnect('hostname','username','password');
Selecting the Database:
mysql_select_db('dbname',[Optional Conn Handler]);
Selects the Argumented data as current data...
Error Handling in Database :
MYSQL_ERROR() : Returns the last Error Message Occured with the data base server..
MYSQL_ERRNO() : returns the last error code associated with the mysql database Server...
Querying the Database:
1) mysql_query(SQL) : Executes the Query with the dbserver & returns the Query Handler.
2) mysql_affected_rows : Returns the num of row affected for the last insert, Update or delete
Query..
3) mysql_num_rows(Query handler) : Returns the no of records in the resultant for the select
Query ,,
Fetching Records:
1) mysql_fetch_row(Query handler) : Returns a single record set from the db server, as a
numerical array and moves the query handler to next record if record does not exist return
false...
2) mysql_fetch_assoc(Query handler) : Returns the record Set as an associative array with
field names as its index position - if record does not exist return false..

194

3) mysql_fetch_array(Query handler) : Returns the record set as an array with numerical or


associative or both arrays .. Returns false if no record found,
4) mysql_fetch_object(Query handler) : Returns the record set as an object with field names
as its values ...
close the connection : mysql_close: Close the connection with the db...
There are 2 other function in php.. which gives a message...
if not able to connect to database the we can read the message as
die('Message');
die(mysql_errno().' - '.mysql_error());
or
exit;
crudApplications:connectdb.php
<?php
$host = 'localhost';
$user = 'root';
$pwd = '';
$con = @mysql_connect($host,$user,$pwd) or die(mysql_errno().' - '.mysql_error());
if($con){
echo 'I am Connected<br>';
}

else {
echo 'Not Connected<br>';

195

?>
createdb.php
<?php
$host = 'localhost';
$user = 'root';
$pwd = '';
@mysql_connect($host,$user,$pwd) or die(mysql_errno().' - '.mysql_error());
$sql = "CREATE DATABASE crud";
mysql_query($sql) or die(mysql_errno().' - '.mysql_error());
?>
connect.php
<?php
$host = 'localhost';
$user = 'root';
$pwd = '';
$db = 'crud';
@mysql_connect($host,$user,$pwd) or die(mysql_errno().' - '.mysql_error());
@mysql_select_db($db) or die(mysql_errno().' - '.mysql_error());;
?>
createtb.php
<?php
include_once('connect.php');

196

$sql = "CREATE TABLE user(


Id SMALLINT(5) UNSIGNED PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(50) NOT NULL,
Gender ENUM('Male','Female') NOT NULL,
Salary DECIMAL(10,2) NOT NULL,
DOB DATE NOT NULL
)";
mysql_query($sql) or die(mysql_errno().' - '.mysql_error());
register.php
<html>
<head>
<link href='style.css' rel='stylesheet' type='text/css'/>
</head>
<body>
<?php
if(isset($_GET['status'])){
switch ($_GET['status']){
case 'failed':
echo "Not Able to Register Please Try Again<hr>";
break;
}
}

197

?>
<form name='testForm' method='POST' action='adduser.php'/>
<table width='70%' align='center' cellpadding='5' cellspacing='0' border='1'>
<tr><th colspan='3'>Register Form</th></tr>
<tr><td>Name</td><td>:</td><td><input type='text' name='name' value=''/></td></tr>
<tr><td>Gender</td><td>:</td><td><input type='radio' name='gender' value='m'/> Male
<input type='radio' name='gender' value='f'/> Female </td></tr>
<tr><td>Salary</td><td>:</td><td><input type='text' name='salary' value=''/></td></tr>
<tr><td>Date Of Birth</td><td>:</td><td><input type='text' name='dob' value=''/></td></tr>
<tr><td align='right' colspan='3'><input type='submit' name='submit' value='Register !'/>
<input type='reset' name='refresh' value='Cancel !'/></td></tr>
</table>
</form>
</body>
</html>
style.css
table tr th{
background:olive;color:#fff;
font-size:18pt;
letter-spacing:5px;
}
table tr td{
font-size:18pt;

198

}
table tr td input{
font-size:18pt;
}
.x{
color:red;
font-family:arial black;
}
adduser.php
<?php
if(isset($_POST['submit'])){
$name = $_POST['name'];
$gender = $_POST['gender'];
$gend = ($gender == 'm')?'Male':'Female';
$salary = $_POST['salary'];
$dob = $_POST['dob'];
include_once('connect.php');
$sql = "INSERT INTO user(Name,Gender,Salary,DOB) VALUES
('$name','$gend',$salary,'$dob')";
mysql_query($sql);
if(mysql_affected_rows()>0){
header("location:showusers.php");

199

exit;
}

else{
header("location:register.php?status=failed");
exit;

}
}
showusers.php
<script>
function deleteinfo(){
$v = confirm("Are You Shore to Delete the User");
return $v;
}
</script>
<?php
include_once('connect.php');
$sql = "SELECT * FROM user";
$res = mysql_query($sql);
//$user = mysql_fetch_array($res);
//print_r($user);
if(isset($_GET['status'])){
switch ($_GET['status']){
case 'update':

200

echo "Details Updated Successfully<hr>";


break;
case 'notupdate':
echo "Unable to Update Please Try Again<hr>";
break;
case 'delete':
echo 'User Details got Deleted Successfully<hr>';
break;
case 'notdelete':
echo 'Details not able to delete Please try Again Later<hr>';
break;
}
}
?>
<table width='60%' align='center' cellpadding='10' cellspacing='0' border='1'>
<tr><th colspan='3'>Employee Details</th></tr>
<?php
while($user = mysql_fetch_row($res)){
echo "<tr><td><a href='showuser.php?id=".$user[0]."'>".$user[1]."</a></td><td><a
href='edituser.php?id=".$user[0]."'><img src='edit.png' width='18px'/></a></td><td><a
href='deleteuser.php?id=".$user[0]."'><img src='delete.png' width='18px'
onclick='javascript:return deleteinfo();'/></a></td></tr>";
}

201

?>
<tr><td colspan='3' align='right'><input type='button' name='back' value='Previous page'
onclick="javascript:history.back();"/> <input type='button' name='back' value='User profile'
onclick="location.href='register.php';"/></td></tr>
</table>
showuser.php
<html>
<head>
<link href='style.css' rel='stylesheet' type='text/css'/>
</head>
<body>
<?php
$id = $_GET['id'];
//echo $id;
include_once('connect.php');
$sql = "SELECT * FROM user WHERE Id = $id";
$res = mysql_query($sql);
$user = mysql_fetch_assoc($res);
//print_r($user);
$gend = ($user['Gender'] == 'Male')?'m.png':'f.png';
?>
<form name='testForm'/>
<table width='70%' align='center' cellpadding='5' cellspacing='0' border='1'>

202

<tr><th colspan='4'>Employee Personal Details</th></tr>


<tr><td>Name</td><td>:</td><td><?php echo $user['Name'];?></td><td rowspan='4'
align='right'><img src="<?php echo $gend;?>" width='120px'/></td></tr>
<tr><td>Gender</td><td>:</td><td><?php echo $user['Gender'];?></td></tr>
<tr><td>Salary</td><td>:</td><td><?php echo 'Rs : ',round($user['Salary']);?></td></tr>
<tr><td>Date Of Birth</td><td>:</td><td><?php echo $user['DOB'];?></td></tr>
<tr><td align='right' colspan='4'> <input type='reset' name='refresh' value='Go Back !'
onclick="location.href='showusers.php';"/></td></tr>
</table>
</form>
</body>
</html>
edituser.php
<html>
<head>
<link href='style.css' rel='stylesheet' type='text/css'/>
</head>
<body>
<?php
$id = $_GET['id'];
//echo $id;
include_once('connect.php');
$sql = "SELECT * FROM user WHERE Id = $id";

203

$res = mysql_query($sql);
$user = mysql_fetch_array($res);
//print_r($user);
?>
<form name='testForm' method='POST' action='updateuser.php'/>
<table width='70%' align='center' cellpadding='5' cellspacing='0' border='1'>
<tr><th colspan='3'>Please Update Your Profile</th></tr>
<tr><td>Name</td><td>:</td><td><input type='text' name='name' value='<?php echo
$user[1];?>'/></td></tr>
<tr><td>Gender</td><td>:</td><td><input type='radio' name='gender' value='m' <?php
if($user['Gender'] == 'Male') echo 'checked';?>/> Male <input type='radio' name='gender'
value='f' <?php if($user['Gender'] == 'Female') echo 'checked';?>/> Female </td></tr>
<tr><td>Salary</td><td>:</td><td><input type='text' name='salary' value='<?php echo
$user['Salary'];?>'/></td></tr>
<tr><td>Date Of Birth</td><td>:</td><td><input type='text' name='dob' value='<?php echo
$user[4];?>'/></td></tr>
<tr><td align='right' colspan='3'><input type='hidden' name='id' value='<?php echo $id;?>'/>
<input type='submit' name='submit' value='Update Profile !'/> <input type='reset'
name='refresh' value='Cancel !' onclick="location.href='showusers.php';"/></td></tr>
</table>
</form>
</body>
</html>
updateuser.php
<?php

204

if(isset($_POST['submit'])){
$name = $_POST['name'];
$gender = $_POST['gender'];
$gend = ($gender == 'm')?'Male':'Female';
$salary = $_POST['salary'];
$dob = $_POST['dob'];
$id = $_POST['id'];
include_once('connect.php');
$sql = "UPDATE user SET Name='$name',Gender='$gend',Salary=$salary,DOB='$dob'
WHERE id = $id";
mysql_query($sql);
if(mysql_affected_rows()>0){
header("location:showusers.php?status=update");
exit;
}

else {

header("location:showusers.php?status=notupdate");
exit;
}
}
deleteuser.php
<?php
$id = $_GET['id'];
include_once('connect.php');

205

$sql = "DELETE FROM user WHERE Id = $id";


mysql_query($sql);
if(mysql_affected_rows()>0){
header("location:showusers.php?status=delete");
exit;
}

else {
header("location:showusers.php?status=notdelete"); exit;

} ?>

206

Oops
Class:-It is a collection of properties (variables) and methods
Syntax:class <class_name>
{
//code
}

207

[abstract|final] class <class_name>


{
//code
}
Property (or) member:- A property or member of a class is an identifier which
is used for storing data which can be accessible throughout the class.
<public|protected| private>[static] <var> =<value>;
ex:public $x=10;
protected $account_no=null;
static public $conv_rate=0.87;
Method:-A method is an action for a class (or) a method is a function inside yhe class
Syntax:[static][final|abstract][public*|protected|private] function <fun_name>([args])
{
//code
}

Ex:function getName()
{
return $this->name;
}
Object:- It is an instance of a class. Object is used for accessing class properties(public). Object
can execute methods(public).

208

Syntax :-<object>=new <class_name>[args];


->:-It is the operator which is used for accessing class properties
and excuting class methods using an object
Ex:<?php
class A
{
public $x=20;
public function test()
{
echo "Test function<br>";
}
}
$obj=new A;
var_dump($obj);
echo '$obj->x=',$obj->x,'<br>';
$obj->test();
$obj->x=21;
echo '$obj->x=',$obj->x,'<br>';
$obj2=new A;
echo '$obj2->x=',$obj2->x,'<br>';
?>
Constructor:- It is a predefined method which is automatically executed within the class when
a class is instantiated. any arguments must be passed to the class at the time of instatiation.
__constructor():- It is the predefined name which can be used for the constructor in a
class(php>=5.0). For PHP<5 constructor name must be similar to class name.

209

ex: <?php
class Human
{
public $name="ram";
public $age=0;
function getName(){
return $this->name;
}
function getAge(){
return $this->age;
}
function setName($n){
$this->name=$n;
}
?>
$this is a predefined variable which will be instantiated in a class when an object is called.
$surya=new Human;
$surya->name='suryaprakash';
$surya->age=32;
$juli=new Human;
$juli->name='julia robert';
$juli->age=45;
Destructor (>=PHP5.0):- The method which will be automatically called when the class object
is uninitialised in the program.
__destructor() is the prereserved name for the destructor.

210

H.W:1. create a class with properties and methods


2. create an object using the class.
3. Access the class property using the object.
4. Execute the class method using the object.
5. Access the class property within the method of the same class
6. execute the method of the class within the class.
7. create a class with a constructor __constructor.
8. Create a class with the constructor as the same name of class name.
9. Create a class with constructor and argument
10. Instantiate above class and observe the behaviour.
Class constant:const <name>=<value>;
Ex:const X=10;
Class constants are case sensitive. They are suggested to begin with uppercase.
Class constants are specific to in class, they must be unique with in the class.
::(scope resolution voperator):-It is used for accessing static properties, class constants and
Executing static methods.
Accessing the class constant:Syntax:<class_name>::<constant_name>
self:- self is a predefined keyword used for refering the same class within the class in scope
resolution operator convertion.
Parent:-parent keyword refers to the parent class.
Ex : -

211

<?php
class Person {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function getTitle() {
return $this->getName()." the person";
}
public function sayHello() {
echo "Hello, I'm ".$this->getTitle()."<br/>";
}
public function sayGoodbye() {
echo "Goodbye from ".self::getTitle()."<br/>";
}
}
class Geek extends Person {
public function __construct($name) {
parent::__construct($name);
}
public function getTitle() {
return $this->getName()." the geek";
}

212

}
$geekObj = new Geek("Ludwig");
$geekObj->sayHello();
$geekObj->sayGoodbye();
?>
Inheritance:- It inherites the properties and methods of a base class to an extended class is
known as inheritance.
Base class:- A class from which properties and methods are inherited to child class.Base class
can be called as parent class or super class. Extended class or child class or sub class:- The class
which inherits the properties and methods from a base is known as an extended class
Note:-PHP supports multi-level inheritance but won't support multiple inheritance.
Multilevel inheritance:class A
{
}
class B extends A
{
}
class c extends b
{
}
Multiple inheritances:class X extends Y,Z,W
{
}//wrong
Extends:- A predefined key word which is used for inheriting a class.

213

Ex: class A
{
public $x=20;
function test()
{
echo "test method<br>";
}
}
class B extends a
{
}
$b=new B;
echo $b->test();
Overriding:- Redeclaring a method in the base class with the extended class is known as
overriding
Encapsulation:-Hiding of the properties and methods of class using access
specifiers(public,private and protected) is known as Encapsulation
Access Specifiers:- These are pre reserved keywords which are used forcontrolling the
visibility of properties and methods. They are public,protected and private.
Public:-A public property or method which can be accessed or executed through the object and
method of same class or through the method of extended class
Protected:-A protected property or method which can be accessed through method of same
class or extended class(They are not accessible through object of same class or extended class)
Private:-A private property or method which can be accessed through the method of same class.
(It cannot be accessed through object of parent or child class and through method of child
class).

214

|object of

|Method of

|Object of

|Method of

|same class

|same class

|extended class

|Extended class

--------------------------------------------------------------------------------Public

Yes

Yes

Yes

Yes

Yes

--------------------------------------------------------------------------------Protected

No

Yes

No

--------------------------------------------------------------------------------Private

No

Yes

|
|

|
No

--------------------------------------------------------------------------------Ex:<?php
class A{
public $pub="public property<br>";
protected $pro="protected property<br>";
private $pri="private property<br>";
public function pub()
{
"public Method<br>";
}
protected function pub()
{
"protected Method<br>";
}
private function pub()

|
No

215

{
"private Method<br>";
}
function accessAll()
{
echo "<b>Method of same class</b><br>";
echo $this->pub;
echo $this->pro;
echo $this->pri;
echo $this->pub();
echo $this->pro();
echo $this->pri();
}
}
class B extends A{
function accessAllB{
echo "<hr><b>Method of Extended class</b><br>";
echo $this->pub;
echo $this->pro;
echo $this->pri; //no
echo $this->pub();
echo $this->pro();
echo $this->pri();//no
}
}
$a=new A;//Object of same class

216

echo "<b>Object of same class</b><br>";


echo $a->pub;
echo $this->pro; //no
echo $this->pri; //no
echo $this->pub();
echo $this->pro();//no
echo $this->pri();//no
$a->accessAll();
$b=new B; //Object of extended class
echo "<b>Object of extended class</b><br>";
echo $b->pub;
echo $b->accessAllB();
?>
It is a predefined keyword used for declaring static properties or methods. A property defined as
static can be accessed through scope resolution operator. It cannot be accessed through object
instance. A static method must be executed through scope resolution operator(::). A static
method should not use $this keyword inside its code.
Final:- It is a predefined keyword used for specifying a class as final or a method as final.
Final class:- A class specified as final cannot be extended to other class.
Final method:- A method specified as final cannot be overriddenin extended class.
Abstraction:- abstact is a predefined keyword which is used for defining abstract class or
method.
Abstract class:- A class with atleast one abstract method must be declared as abstract class. An
abstract class cannot be instantiated directly. An abstract class must be extended where abstract
methods must be implemented with the code. An abstract class can have properties and
constants. An abstract class should not contain private methods.
Abstract methods:- An abstract method should not contain body. An

217

abstract method cannot be private. abstract method must be


declared in its extended class along with its code.
Ex: <?php
abstract class a{
public $x=10;
const X=12;
function abs(){
echo "abstract method<br>";
}
}
class B extends A{
function abs(){
echo "abstract method of extende class<br>";
}
}
?>
Interface:-An interface is a collection of bodyless method without any access specifier. An
interface won't allows the usage of declaration of properties or normal methods. An interface
cannot be instantiated directly whereas it can be implemented by a class. The class which
implements the interface must redeclare its bodyless methods in the class. M<ultiple interfaces
can be implemented by a class.
Implements:-It is a predefined keyword which is used for loading an interface to a class.

218

219

Ajax

AJAX stands for asynchronous JavaScript and XML. It is a client side JavaScript method which
is used for communication with the server machine Without any page refresh.
1. To achieve asynchronous communication between browser and server
2. Updating of certain portions of the current webpage without Reloading the entire webpage.
AJAX is introduced in 2000 by Microsoft it became very popular From 2005 onwards.
AJAX is browser dependent client side coding which is used for Getting the dynamic content
from the server for JavaScript event in the WebPages.
AJAX communication will takes place in few steps.
1. Creating a cross browser compatible AJAX.
2. Opening the request to the server page.
3. Sending the request.
4. Checking the status of the request.
5. On compilation of request loading the responded content
at the target element.
Object in internet explorer:new ActiveXObject('Microsoft.XMLHTTP');
new ActiveXObject('MSXML.XMLHTTP');
new ActiveXObject('MSXML2.XMLHTTP');
new ActiveXObject('MSXML3.XMLHTTP');
new ActiveXObject('MSXMLC.XMLHTTP');
Other then IE:new XMLHttpRequest();
Opening request:-

220

if(window.ActiveXObject){
document.write("IE");
}
else if(window.XMLHttpRequest){
document.write("Other than IE");
}
else {
document.write("No Ajax support");
}
Open:open(method,url,async,[user_name],[password]);
ex:-ajax.open("Get","getuser.php?id=2",true);
Sending the request:Send:send(null|<parameters>)
Ex:-send(ajax.send(null);
Properties of AJAX:a) Ready state:0->uninitialised(Ajax engine is created,connection is not established)
1->initialised(open method will be called,connection establishes)
2->sent(send method is called,request is sent to server)
3->loading(request is under process)
4->compleated(response received,process by AJAX engine compleates)
b) On ready state Change:-Predefined event which will be
called whenever readystate property value is updated.
Ex:- ajax.onreadystatechange=function(){

221

if(ajax.readystate==4)
{
document.write("ready state"<br>");
}
else
{
document.write("Not ready state<br>");
}
}
c) Status:-Here we will have the status code of the AJAX.
200-> successful
5xx->server issue
4xx->page issue
3xx->redirection
d) Response Text: - The information send from the server as text content.
ajax.responseText
e) ResponseXML:- used for accessing response XML
ajax.responseXML
Flow of AJAX based Application:1. User action is performed on any of the HTML components Like button, hyperlink, selectbox,
textbox etc.
2. Certain JavaScript event is raised because of the above User action
3. Specific user defined JavaScript function is called to handle The above raised JavaScript
event.
4. In the above JavaScript function
a. Logic is written to create Ajax engine

222

b. Partial form data is gathered


c. Callback (user-defined) function is set to onreadystatechange Property of AJAX engine.
d. URL is prepared along with every string
e. Connection is established (open method is called)
f. Request is sent to server (send () is called)
5. Request related response comes to AJAX engine as text or XML data.
6. Once again callback function is called. Inside callback function
a. Logic to take response received by AJAX engine using JavaScript
b. Logic is written to update certain portions of the currentwebpages
Without reloading the entire webpage with the receiver response.

223

224

JOOMLA
JOOMLA is a content management system. It is a CMS tool.
It is developed on php using mysql as its backend.
JOOMLA is a object oriented based tool which was developed on the
Top of MVC architecture.
JOOMLA comes with various Predefined templates, components, modules, languages
And plug-ins.
JOOMLA software is available in various versions.
(JOOMLA1.0.x,JOOMLA1.5.x,JOOMLA1.6.x)
JOOMLA software consists of two interfaces.
1. User interface (front end)
2. Admin interface (Backend)
1. User Interface: - Front end is the actual website Which is shown to the actual users of the
website.
2. Admin interface: - Backend is the interface Which is accessible for the backend users for
Managing the website with various actions.
User Management: - It allows the management of the Users to the website. Various types of
users are observed
Front end users:-registered
Special:-editor, publisher
Backend users:-Manager, Adminstrator, Super administrator
Media Management:-It is used for managing media files in the software.
Section management:Section:-It is a top level hierarchy for content Classification. It allows the management of
sections.

225

Category management:-A category is the child category For a section used for sub classifying
the content.
Article Management:-It can be considered as a webpage In the site which can be classified to
a category Or a section
Component: - A component is a functional block in the Website which can be considered as
Database Interaction and can be loaded at the main (center) Portion of the website.
Module:- It is a functional block which can occupy Various predefined positions in the software
like top,left,right,user1,user2,...usern, footer etc. A module can be controlled for its display in
One or more pages.
Plug-in:-A plug-in is a logical part which will Enhance the way in which we will display the
Content of the website.
Template management:- A template is a predefined Interface which is used for switching the
user Interfaces on the fly.
Language management: - JOOMLA supports multilingual Sites where we can install language
extension for Adding support with additional language.
www.joomla.org
Latest version is 1.7
Installation of JOOMLA:1. Install joomla without sample data
2. Add all the users for each role
3. Create few categories
4. Create few articles.
5. Add the menu links for the articles category
6. Download free JOOMLA templates and install.
Switch between the templates
7. Try to change logo of the template
8. Install the external modules plug-ins

226

9. Activate free loaded modules and plug-ins.


Check their functionality
10. create a website with few links using JOOMLA

227

JQUERY
JQuery is a JavaScript framework which is used For writing less code and doing more
action
JQuery is developed on top of java platform and it is used for creating rich website
interface.
JQuery is a fast and concise JavaScript library. That simplifies HTML document
traversing, event Handling, animating and Ajax interaction for Rapid web
development. JQuery is designed to Change the way that you write JavaScript.
www.jquery.com
Syntax:$(selector).method
Special effects:Hide ()
Show ()
JQuery
JQuery documents
JQuery core selector
JQuery supports css page selector
Traversing
CSS
Effects
Events
AJAX
: implements JQuery plug-ins
Use JQuery pop calendar
Write JQuery cursors

228

JQuery based tool tips


JQuery based light box
JQuery based form validations
JQuery based news agrigation using AJAX

--------------------------THE END------------------------

229

Javascrtipt_Interview_Quesions
PHP_Interview_questions

230

Javascrtipt_Interview_Quesions
1) <script type="text/javascript">
x=4+"4";
document.write(x);
</script>
Output------?
a) 44
b) 8
c) 4
d) Error output
Ans: a
2) <script type="text/javascript" language="javascript">
var qpt = "Vempower Solutions";
var result = qpt.split(" ");
document.write(result);
</script>
a) Vempower
b) V,e,m,p,o,w,e,r, S,o,l,u,t,I,o,n,s
c) Vempower Solutions
d) VempoweSolutions
Ans: c
3) Is it possible to nest functions in JavaScript?
a) True
b) False
Ans: a

231

4) <script>
document.write(navigator.appCodeName);
</script>
a) get code name of the browser of a visitor
b) set code name of the browser of a visitor
c) None of the above
Ans: a
5) Which of the following is true?
a) If onKeyDown returns false, the key-press event is cancelled.
b) If onKeyPress returns false, the key-down event is cancelled.
c) If onKeyDown returns false, the key-up event is cancelled.
d) If onKeyPress returns false, the key-up event is canceled.
Ans: a
6) Scripting language are
a) High Level Programming language
b) Assembly Level programming language
c) Machine level programming language
Ans: a
7) <script language="javascript">
function x()
{
var s= "Good 100%";
var pattern = /\D/g;
var output= s.match(pattern);
document.write(output);
}
</script>
a) Good %
b) 1,0,0
c) G,o,o,d,%

232

d) Error
Ans: c
8) <script language="javascript">
var qpt="Sample String ";
alert(qpt.charAt(qpt.length-1));
</script>
a) p
b) e
c) g
d) Error
Ans: c

9) Are java and javascript the same?


a) NO
b) YES
Ans: a
10) Syntax for creating a RegExp object:
(a). var txt=new RegExp(pattern,attributes);
(b). var txt=/pattern/attributes;
Which of the above mentioned syntax will correct?
a) (a) only
b) (b) only
c) Both (a) and (b)
d) None of the above
Ans: c
11) <script language="javascript">
function x(z,t)
{
alert(x.length);
}

233

</script>
output:
?
a) Error
b) 2
c) 1
d) 3
Ans: b
12) What is mean by "this" keyword in javascript?
a) It refers current object
b) It referes previous object
c) It is variable which contains value
d) None of the above
Ans: a
13) In JavaScript, Window.prompt() method return true or false value ?
a) False
b) True
c) None of above
Ans: a
14) Math. round(-20.51)=?
a) 20
b) -21
c) 19
d) None
Ans: b
15) <script language="javascript">
function x()
{
var s = "Quality 100%!{[!!";
var pattern = /\w/g;
var output = s.match(pattern);

234

document.write(output);
}
</script>
a) %,!,{,[,!,!
b) Q,u,a,l,i,t,y,1,0,0
c) Quality 100
d) Error
Ans: b
16) <script type="text/javascript" language="javascript">
var qpt= new Array();
qpt[0] = "WebDevelopment";
qpt[1]="ApplicationDevelopment"
qpt[2]="Testing"
qpt[3] = "Vempower Solutions";
document.write(qpt[0,1,2,3]);
</script>
a) Error
b) Vempower Solution
c) WebDevelopment
d) WebDevelopmnet,ApplicationDevelopment,Testing,Vempower Solutions
Ans: b
17) parseFloat(9+10)=?
a) 19
b) 910
c) None
Ans: c
18) <script language="javascript">
function x()
{
document.write(2+5+"8");
}

235

</script>
a) 258
b) Error
c) 7
d) 78
Ans: d
19) In Javascript, Which of the following method is used to evaluate the regular expression?
a) eval(2*(3+5))
b) evaluate(2*(3+5))
c) evalu(2*(3+5))
d) None of the above
Ans: a
20) <script language="javascript">
function x()
{
var s= "quality 100%";
var pattern = /\d/g;
var output= s.match(pattern);
document.write(output);
}
</script>
a) 100
b) 1,0,0
c) q,u,a,l,i,t,y,%
d) Error
Ans: b
21) <script type="text/javascript" language="javascript">
qpt=((45%2)==0)? "hello" : "bye";
document.write(qpt);
</script>
a) hello

236

b) bye
c) Error in string handling
d) None of the above
Ans: b
22) How do you create a new object in JavaScript?
a) var obj = {};
b) var obj = Object();
c) var obj=new {};
d) None of the above
Ans: a
23) In Javascript, What does isNaN function do ?
a) Return true if the argument is not a number.
b) Return false if the argument is not a number.
c) Return true if the argument is a number.
d) None of the above
Ans: a
24) Which of the following properties hold the values of the pixels of the length of the width
and height of the viewer's screen resolution?
a) screen.width and screen.height
b) Resolution.width and Resolution.height
c) screen.pixels.width and screen.pixels.height
d) ViewerScreen.width and ViewerScreen.height
Ans: a
25)How to assign a function to a variable with the JavaScript Function contructor ?
a) var f=Function("x","y","return x+y");
b) var f=Function(x,y){ return x+y;}
c) var f= new Function("x", "y", "return x + y");
Ans: b
26) In JavaScript, Window.alert() is used to allow user to enter something
a) True
b) False

237

c) None of above
Ans: b
27) Is Javascript has any date data type?
a) Yes
b) No
Ans: b
28) ?_name is it valid javascript identifier?
a) Yes
b) No
Ans: a
29) <script type="text/javascript" language="javascript">
var qpt="V-Empower Solutions ";
var result =qpt.lastIndexOf("s");
document.write(result);
</script>
a) -1
b) 18
c) 17
d) 19
Ans: 18
30) <script language="javascript">
function sum(x)
{
function add(y)
{
return x+y;
}
return add;
}
function callme() { result=sum(5)(5); alert(result); }
</script>

238

If you call the function callme(), what will happen ?


a) 10
b) Error in calling Function
c) 5
d) None of the above
Ans: a
31) <script type="text/javascript">
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
</script>
Can you write HTML tag inside the javascript ?
a) No
b) Yes
c) Impossible
Ans: b
32) How to speicfy the color of the hypertext links with JavaScript ?
a) document.linkColor="#00FF00";
b) document.LColor="#00FF00";
c) document.LinkC="#00FF00";
d) document.hyperTextLink="#00FF00":
Ans: a
33) ------------- converts a string to floating point numbers.
a) eval
b) ParseInt
c) ParseFloat
d) None
Ans: c
34) In Javascript, Which of the following method is used to find out the character at a position

239

in a string?
a) charAt()
b) CharacterAt()
c) CharPos()
d) characAt()
Ans: a
35) <script type="text/javascript" language="javascript">
var qpt = "V-Empower Solutions";
var result =qpt.substring(7,8);
document.write(result);
</script>
36) What are the following looping structures are available in javascripts?
a) for,forecach
b) foreach,whileloop
c) do-while loop,foreach
d) for , while loop
Ans: d
37) Which of these is not a method of the Math object?
a) atan()
b) atan2()
c) eval()
d) acos()
Ans: c
38) <script type="text/javascript">
var s = "9123456 or 80000?";
var pattern = /\d{4}/;
var output = s.match(pattern);
document.write(output);
</script>
a) 9123

240

b) 91234
c) 80000
d) None of the above
Ans: a
39) In javascript, RegExp Object Method test() is used to search a string and returns
a) true or false
b) found value
c) index
d) None of the above
Ans: a
40) What property would you use to redirect a visitor to another page?
a) document.URL
b) window.location.href
c) .document.location.href
d) link.href
Ans: c
41) -------------- method is used to remove focus from the specified object.
a) blur()
b) focus()
c) None
Ans: a
42)Javascript is a ________ typed language.
a) tightly
b) loosely
Ans: b
43)Choose the built-in object:
a) Password
b) Math
c) Link
d) Hidden
Ans: b

241

44)Choose the object(s) associated with the onFocus event handler:


a) Password
b) Hidden
c) Both
d) Neither
Ans: a
45)Choose the object(s) associated with the onKeyPress event handler:
a) Document
b) Layer
c) Both
d) Neither
Ans: a
46)Choose the best pattern for the string: 840-21-3688
a) /\d+-\d{2,}-?\d*/
b) /\w+-\w+-\w+/
c) /\d+\d+\d+/
d) /\d+-\d?-\d+/
Ans: a
47) Which would JavaScript assign to an uninitialized variable?
a) NaN
b) null
c) undefined
d) false
Ans: c
48)Which is not a built-in function?
a) parseInt()
b) exec()
c) eval()
d) parseFloat()
Ans: b

242

49)Seek the truth about setTimeOut():


a) The statement(s) it executes run(s) only once.
b) It pauses the script in which it is called.
c) clearTimeOut() won't stop its execution.
d) The delay is measured in hundredths of a second.
Ans: a
50)How do you call a function named "myFunction"?
a) call function myFunction
b) myFunction()
c) call myFunction()
Ans: c
51) What is the correct JavaScript syntax for opening a new window called "window2" ?
a)new("http://www.w3schools.com","window2")
b)new.window("http://www.w3schools.com","window2")
c)window.open("http://www.w3schools.com","window2")
d)open.new("http://www.w3schools.com","window2")
Ans: c
52)How do you find the client's browser name?
a)client.navName
b)browser.name
c)navigator.appName
Ans: c
53) Semicolons are optional at the end of a JavaScript statement.
a)True
b)False
Ans: a
54)Which of the following are capabilities of functions in JavaScript?

243

a) Return a value
b) Accept parameters and Return a value
c) Accept parameters
d) None of the above
Ans: c
55)Which popup box you use when want a value from user before open a page?
a) alert("Write some text here")
b) confirm("Write some text here")
c) prompt("Write here some text")
d) None of the above
Ans: c
56)What is the correct way to write a JavaScript array?
a) var txt = new Array("tim","kim","jim")
b) var txt = new Array="tim","kim","jim"
c) var txt = new Array:1=("tim")2=("kim")3=("jim")
d) var txt = new Array(1:"tim",2:"kim",3:"jim")
Ans: a
57) How to submit form data with javascript?
a) document.formname.submit();
b) submit()
c) document.submit()
d)None of the above
Ans: a
58) When a user views a page containing a JavaScript program, which machine actually
executes the script?
a) The User's machine running a Web browser
b) The Web server
c) A central machine deep within Netscape's corporate offices
d) None of the above
Ans: a

244

59) Which of the following is not a valid JavaScript variable name?


a) 2names
b) _first_and_last_names
c) FirstAndLast
d) None of the above
Ans:a
60) To set up the window to capture all Click events, we use which of the following statement?
a) window.captureEvents(Event.CLICK);
b) window.handleEvents (Event.CLICK);
c) window.routeEvents(Event.CLICK );
d) window.raiseEvents(Event.CLICK ); Ans: a

PHP_Interview_questions

Question: 1 Who is the father of PHP?


Answer: Rasmus Lerdorf is known as the father of PHP.
Question: 2 What is the difference between $name and $$name?
Answer: $name is variable where as $$name is reference variable
like $name=sonia and $$name=singh so $sonia value is singh.
Question: 3 How can we submit a form without a submit button?
Answer: 3 Java script submit () function is used for submit form without submit button
on click call document.formname.submit()
Question : 4 In how many ways we can retrieve the data in the result set of
MySQL using PHP?

245

Answer : 4 We can do it by 4 Ways


1. mysql_fetch_row.
2. mysql_fetch_array
3. mysql_fetch_object
4. mysql_fetch_assoc
Question : 5 What is the difference between mysql_fetch_object and
mysql_fetch_array?
Answer : 5 mysql_fetch_object() is similar tomysql_fetch_array(), with one difference an object is returned, instead of an array. Indirectly, that means that
you can only access the data by the field names, and not by their
offsets (numbers are illegal property names).
Question : 6 What are the differences between get and post methods.
Answer : 6 There are some defference between GET and POST method
1. GET Method have some limit like only 2Kb data able to send for 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 for send sensetive request
Question : 7 How can we extract string "pcds.co.in " from a string
"http://info@pcds.co.in using regular expression of PHP?
Answer : 7 preg_match("/^http:\/\/.+@(.+)$/","http://info@pcds.co.in",$matches);
echo $matches[1];
Question : 8 How can we create a database using PHP and MySQL?
Answer : 8 We can create MySQL database with the use of
mysql_create_db("Database Name") .
Question : 9 What are the differences between require and include?
Answer : 9 Both include and require used to include a file but when included file not found
Include send Warning where as Require send Fatal Error .

246

Question : 10 Can we use include ("xyz.PHP") two times in a PHP page "index.PHP"?
Answer : 10 Yes we can use include("xyz.php") more than one time in any page. but it create a
prob when xyz.php file contain some funtions declaration then error will come for already
declared function in this file else not a prob like if you want to show same content two time in
page then must incude it two time not a prob.
Question : 11 What are the different tables(Engine) present in MySQL, which one is
default?
Answer : 11 Following tables (Storage Engine) we can create.
1. MyISAM(The default storage engine IN MYSQL Each MyISAM table is stored on disk in
three files. The files have names that begin with the table name and have an extension to
indicate the file type. An .frm file stores the table format. The data file has an .MYD (MYData)
extension. The index file has an .MYI (MYIndex) extension. )
2. InnoDB(InnoDB is a transaction-safe (ACID compliant) storage engine for 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 preferred
term, although HEAP remains supported for backward compatibility. )
5. BDB (BerkeleyDB)(Sleepycat Software has provided MySQL with the Berkeley DB
transactional storage engine. This storage engine typically is called BDB for short. BDB tables
may have a greater chance of surviving crashes and are also capable of COMMIT and
ROLLBACK operations on transactions)
6. EXAMPLE
7. FEDERATED (It is a storage engine that accesses data in tables of remote databases rather
than in local tables. )
8. ARCHIVE (The ARCHIVE storage engine is used for storing large amounts of data without
indexes in a very small footprint. )
9. CSV (The CSV storage engine stores data in text files using comma-separated values format.)
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).
Question : 12 What is use of header() function in php ?

247

Answer : 12 The header() function sends a raw HTTP header to a client.We can use herder()
function for redirection of pages. It is important to notice that header() must be called before
any actual output is seen.
Question: 13 How can I execute a PHP script using command line?
Answer : 13 Just run the PHP CLI (Command Line Interface) program and
provide the PHP script file name as the command line argument.
Question : 14 Suppose your Zend engine supports the mode <? ?> Then how can u
configure your PHP Zend engine to support <?PHP ?> mode ?
Answer : 14 In php.ini file: set short_open_tag=on to make PHP support .
Question : 15 Shopping cart online validation i.e. how can we configure Paypal, etc.?
Answer : 15 Nothing more we have to do only redirect to the payPal url after
submit all information needed by paypal like amount,adresss etc.
Question : 16 What is meant by nl2br()?
Answer : 16 Inserts HTML line breaks (<BR />) before all newlines in a string.
Question : 17 What is htaccess? Why do we use this and Where?
Answer : 17 .htaccess files are configuration files of Apache Server which provide
a way to make configuration changes on a per-directory basis. A file,
containing one or more configuration directives, is placed in a particular
document directory, and the directives apply to that directory, and all
subdirectories thereof.
Question : 18 How we get IP address of client, previous reference page etc?
Answer : 18 By using $_SERVER['REMOTE_ADDR'],$_SERVER['HTTP_REFERER'] etc.
Question : 19 What are the reasons for selecting lamp (Linux, apache, MySQL, PHP)
instead of combination of other software programs, servers and perating systems?
Answer : 19 All of those are open source resource. Security of Linux is very
very more than windows. Apache is a better server that IIS both in

248

functionality and security. MySQL is world most popular open source


database. PHP is more faster that asp or any other scripting language.
Question : 20 How can we encrypt and decrypt a data present in a MySQL table using
MySQL?
Answer : 20 AES_ENCRYPT () and AES_DECRYPT ().
Question : 21 How can we encrypt the username and password using PHP? Answer : 21
The functions in this section perform encryption and decryption, and
compression and uncompression:
encryption

decryption

AES_ENCRYT()

AES_DECRYPT()

ENCODE()

DECODE()

DES_ENCRYPT()

DES_DECRYPT()

ENCRYPT()

Not available

MD5()

Not available

OLD_PASSWORD()

Not available

PASSWORD()

Not available

SHA() or SHA1()

Not available

Not available

UNCOMPRESSED_LENGTH()

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


programming?
Answer : 22 One of the main advantages of OO programming is its ease of
modification; objects can easily be modified and added to a system there
by reducing maintenance costs. OO programming is also considered to be
better at modeling the real world than is procedural programming. It
allows for more complicated and flexible interactions. OO systems are

249

also easier for non-technical personnel to understand and easier for


them to participate in the maintenance and enhancement of a system
because it appeals to natural human cognition patterns.
For some systems, an OO approach can speed development time since many
objects are standard across systems and can be reused. Components that
manage dates, shipping, shopping carts, etc. can be purchased and easily
modified for a specific system.
Question : 23 What are the differences between procedure-oriented languages and objectoriented language?
Answer : 23 There are lot of difference between procedure language and object oriented like
below
1>Procedure language easy for new developer but complex to understand whole software as
compare to object oriented model
2>In Procedure language it is difficult 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 of
thing not available in procedure language on that our Fonda use COPY and PASTE .
Question : 24 What is the use of friend function?
Answer : 24 Sometimes a function is best shared among a number of different
classes. Such functions can be declared either as member functions of
one class or as global functions. In either case they can be set to be
friends of other classes, by using a friend specifier in the class that
is admitting them. Such functions can use all attributes of the class
which names them as a friend, as if they were themselves members of that
class.
A friend declaration is essentially a prototype for a member function,
but instead of requiring an implementation with the name of that class
attached by the double colon syntax, a global function or member
function of another class provides the match.

250

Question : 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 defines the item).
Private: Private limits visibility only to the class that defines
the item.
Static: A static variable exists only in a local function scope,
but it does not lose its value when program execution leaves this scope.
Final: Final keyword prevents child classes from overriding a
method by prefixing the definition with final. If the class itself is
being defined final then it cannot be extended.
transient: A transient variable is a variable that may not
be serialized.
volatile: a variable that might be concurrently modified by multiple
threads should be declared volatile. Variables declared to be volatile
will not be optimized by the compiler because their value can change at
any time.
Question : 26 What are the different types of errors in PHP?
Answer : 26 Three are three types of errors:1. Notices: These are trivial,
non-critical errors that PHP encounters while executing a script for
example, accessing a variable that has not yet been defined. By default,
such errors are not displayed to the user at all although, as you will
see, you can change this default behavior.2. Warnings: These are more serious errors for
example, attempting
to include() a file which does not exist. By default, these errors are
displayed to the user, but they do not result in script termination.3. Fatal errors: These are
critical errors for example,
instantiating an object of a non-existent class, or calling a
non-existent function. These errors cause the immediate termination of

251

the script, and PHP's default behavior is to display them to the user
when they take place.
Question : 27 What is the functionality of the function strstr and stristr? Answer : 27
strstr Returns part of string from the first occurrence of needle(sub string that we finding out )
to the end of string.
$email= 'sonialouder@gmail.com';
$domain = strstr($email, '@');
echo $domain; // prints @gmail.com
here @ is the needle
stristr is case-insensitive means able not able to differentiate between a and A.
Question : 28 What are the differences between PHP 3 and PHP 4 and PHP 5?
Answer : 28 There are lot of difference among these three version of php
1.Php3 is oldest version after that php4 came and current version is php5 (php5.3) where php6
have to come
2.Difference mean oldest version have less functionality 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 of exceptions and exception handling
2. Type hinting which allows you to force the type of a specific argument
3. Overloading of methods through the __call function
4. Full constructors and destructors etc through a __constructor and __destructor function
5. __autoload function for dynamically including certain include files depending on the class
you are trying to create.
6 Finality : can now use the final keyword to indicate that a method cannot be overridden by a
child. You can also declare an entire class as final which prevents it from having any children at
all.
7 Interfaces & Abstract Classes
8 Passed by Reference :
9 An __clone method if you really want to duplicate an object.
Question : 29 How can we convert asp pages to PHP pages?

252

Answer : 29 there are lots of tools available for asp to PHP conversion. you can
search Google for that. the best one is available athttp://asp2php.naken.cc./.
Question : 30 What is the functionality of the function htmlentities? Answer : 30 Convert
all applicable characters to HTML entities
This function is identical to htmlspecialchars() in all ways, except
with htmlentities(), all characters which have HTML character entity
equivalents are translated into these entities.
Question : 31 How can we get second of the current time using date function?
Answer : 31 $second = date("s");
Question : 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');
// Output 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>';?>
Question : 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 followed by two hex digits and spaces
encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is

253

encoded, that is the same way as in


application/x-www-form-urlencoded media type.
urldecode decodes any %##
encoding in the given string.
Question : 34 What is the difference between the functions unlink and unset?
Answer : 34 unlink() deletes the given file from the file system.
unset() makes a variable undefined.
Question : 35 How can we register the variables into a session?
Answer : 35 $_SESSION['name'] = "sonia";
Question : 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 exif_imagetype () function
To know the Image size use getimagesize () function
To know the image width use imagesx () function
To know the image height use imagesy() function.
Question : 37 How can we get the browser properties using PHP?
Answer : 37 By using $_SERVER['HTTP_USER_AGENT']
variable.
Question : 38 What is the maximum size of a file that can be uploaded using PHP and how
can we change this?
Answer : 38 By default the maximum size is 2MB. and we can change the following
setup at php.ini upload_max_filesize = 2M.
Question : 39 How can we increase the execution time of a PHP script? Answer : 39 by
changing the following setup at php.ini max_execution_time = 30
; Maximum execution time of each script, in seconds.
Question : 40 How can we take a backup of a MySQL table and how can we restore it. ?

254

Answer : 40 To backup: BACKUP TABLE tbl_name[,tbl_name] TO


'/path/to/backup/directory'. RESTORE TABLE tbl_name[,tbl_name] FROM
'/path/to/backup/directory'mysqldump: Dumping Table Structure and DataUtility to dump a
database or a collection of database for backup or
for transferring the data to another SQL server (not necessarily a MySQL
server). The dump will contain SQL statements to create the table and/or
populate the table.
Question : 41 How can we optimize or increase the speed of a MySQL select
query?
Answer :

First of all instead of using select * from table1, use select


column1, column2, column3.. from table1

Look for the opportunity to introduce index in the table you are
querying.

Use limit keyword if you are looking for any specific number of
rows from the result set.

Question : 42 How many ways can we get the value of current session id?
Answer : 42 session_id() returns the session id for the current session.
Question : 43 How can we destroy the session, how can we unset the variable of a session?
Answer : 43 session_unregister to Unregister a global variable from the current
session session_unset to Free all session variables.
Question : 44 How can we set and destroy the cookie n php?
Answer : 44 By using setcookie(name, value, expire, path, domain); function we can set the
cookie in php ;
Set the cookies in past for destroy. like

255

setcookie("user", "sonia", time()+3600); for set the cookie


setcookie("user", "", time()-3600); for destroy or delete the cookies;
Question : 45 How many ways we can pass the variable through the navigation between
the pages?
Answer : 45.

GET/QueryString

POST

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


Answer : 46 eregi_replace() function is identical to ereg_replace() except that
this ignores case distinction when matching alphabetic
characters.eregi_replace() function is identical to ereg_replace()
except that this ignores case distinction when matching alphabetic
characters.
Question : 47 What are the different functions in sorting an array?
Answer : 47 Sort(), arsort(),asort(), ksort(),natsort(), natcasesort(),
rsort(), usort(),array_multisort(), and uksort().
Question : 48 How can we know the count/number of elements of an array?
Answer : 48 2 ways
a) sizeof($urarray) This function is an alias of count()
b) count($urarray)
Question : 49 what is session_set_save_handler in PHP?
Answer : 49 session_set_save_handler() sets the user-level session storage functions which are
used for storing and retrieving data associated with a session. This is most useful when a storage
method other than those supplied by PHP sessions is preferred. i.e. Storing the session data in a
local database.

256

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


JavaScript?
Answer : 50 bool is_numeric ( mixed var) Returns TRUE if var is a number or a numeric string,
FALSE otherwise.or use isNaN(mixed var)The isNaN() function is used to check if a value is
not a number.
Question : 51 List out some tools through which we can draw E-R diagrams for mysql.
Answer : 51 Case Studio Smart Draw.
Question : 52 How can I retrieve values from one database server and store them in other
database server using PHP?
Answer : 52 we can always fetch from one database and rewrite to another. here
is a nice solution of it.$db1 = mysql_connect("host","user","pwd")
mysql_select_db("db1", $db1);
$res1 = mysql_query("query",$db1);$db2 = mysql_connect("host","user","pwd")
mysql_select_db("db2", $db2);
$res2 = mysql_query("query",$db2);At this point you can only fetch records from you previous
ResultSet,
i.e $res1 But you cannot execute new query in $db1, even if you
supply the link as because the link was overwritten by the new db.so at this point the following
script will fail.
$res3 = mysql_query("query",$db1); //this will failSo how to solve that?
take a look below.
$db1 = mysql_connect("host","user","pwd")
mysql_select_db("db1", $db1);
$res1 = mysql_query("query",$db1);
$db2 = mysql_connect("host","user","pwd", true)
mysql_select_db("db2", $db2);
$res2 = mysql_query("query",$db2);
So mysql_connect has another optional boolean parameter which
indicates whether a link will be created or not. as we connect to the

257

$db2 with this optional parameter set to 'true', so both link will
remain live.
now the following query will execute successfully.
$res3 = mysql_query("query",$db1);
Question : 53 List out the predefined classes in PHP?
Answer : 53 Directory stdClass __PHP_Incomplete_Class exception php_user_filter.
Question : 54 How can I make a script that can be bi-language (supports
English, German)?
Answer : 54 You can maintain two separate language file for each of the
language. all the labels are putted in both language files as variables
and assign those variables in the PHP source. on runtime choose the
required language option.
Question : 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
define. The definition of those methods must be in its extending class.Interface: Interfaces are
one type of class where all the methods are
abstract. That means all the methods only declared but not defined. All
the methods must be define by its implemented class.
Question : 56 How can we send mail using JavaScript?
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 for an email to send. this requires the client
to approve it.
Question : 57 How can we repair a MySQL table?

258

Answer : 57 The syntex for repairing a MySQL table is


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

259

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

Identifier

Maximum Length
(bytes)

Database

64

Table

64

Column

64

Index

64

Alias

255

There are some restrictions on the characters that may appear in


identifiers:
Question : 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.
Question : 61 What are the other commands to know the structure of table using MySQL
commands except explain command?
Answer : 61 describe Table-Name;
Question : 62 How many tables will create when we create table, what are they?
Answer : 62 The '.frm' file stores the table definition.
The data file has a '.MYD' (MYData) extension.
The index file has a '.MYI' (MYIndex) extension.
Question : 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 default table type is MyISAM.
Each MyISAM table is stored on disk in three files. The files have names
that begin with the table name and have an extension to indicate the

260

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

261

Answer : 65 The generic syntax for grant is as following


GRANT [rights] on [database/s] TO [username@hostname] IDENTIFIED BY [password] now
rights can be
a) All privileges
b) combination of create, drop, select, insert, update and delete etc.We can grant rights on all
databse by using *.* or some specific
database by database.* or a specific table by database.table_name
username@hotsname can be either username@localhost, username@hostname
and username@%
where hostname is any valid hostname and % represents any name, the *.*
any condition
password is simply the password of userThe generic syntax for revoke is as following
REVOKE [rights] on [database/s] FROM [username@hostname] now rights can be as
explained above
a) All privileges
b) combination of create, drop, select, insert, update and delete etc.
username@hotsname can be either username@localhost, username@hostname
and username@%
where hostname is any valid hostname and % represents any name, the *.*
any condition
Question : 66 Explain Normalization concept?
Answer : 66 The normalization process involves getting our data to conform to
three progressive normal forms, and a higher level of normalization
cannot be achieved until the previous levels have been achieved (there
are actually five normal forms, but the last two are mainly academic and
will not be discussed).First Normal FormThe First Normal Form (or 1NF) involves removal of
redundant data
from horizontal rows. We want to ensure that there is no duplication of
data in a given row, and that every column stores the least amount of
information possible (making the field atomic).Second Normal FormWhere the First Normal
Form deals with redundancy of data across a

262

horizontal row, Second Normal Form (or 2NF) deals with redundancy of
data in vertical columns. As stated earlier, the normal forms are
progressive, so to achieve Second Normal Form, your tables must already
be in First Normal Form.Third Normal Form
I have a confession to make; I do not often use Third Normal Form. In
Third Normal Form we are looking for data in our tables that is not
fully dependant on the primary key, but dependant on another value in
the table
Question : 67 How can we find the number of rows in a table using MySQL? Answer : 67
Use this for mysql SELECT COUNT(*) FROM table_name;
Question : 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";
Question : 69 How many ways we can we find the current date using MySQL?
Answer : 69 SELECT CURDATE();
CURRENT_DATE() = CURDATE()
for time use
SELECT CURTIME();
CURRENT_TIME() = CURTIME()
Question : 70 What are the advantages and disadvantages of Cascading Style Sheets?
Answer : 70 External Style SheetsAdvantagesCan control styles for multiple documents at
once. Classes can be created for use on multiple HTML element types in many documents.
Selector and grouping methods can be used to apply styles under complex
contextsDisadvantagesAn extra download is required to import style information for each
document The rendering of the document may be delayed until the external style sheet is loaded
Becomes slightly unwieldy for small quantities ofstyle definitions Embedded Style Sheets
Advantages Classes can be created for use on multiple tag types in the document. Selector and

263

grouping methods can be used to apply styles under complex contexts. No additional downloads
necessary to receive style information
Disadvantages
This method can not control styles for multiple documents at once
Inline Styles
Advantages
Useful for small quantities of style definitions. Can override other style specification methods at
the local level so only exceptions need to be listed in conjunction with other style methods.
Disadvantages
Does not distance style information from content (a main goal of SGML/HTML). Can not
control styles for multiple documents at once. Author can not create or control classes of
elements to control multiple element types within the document. Selector grouping methods can
not be used to create complex element addressing scenarios
Question : 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 sing the keyword 'extends'.
Question : 72 What is the difference between Primary Key and
Unique key?
Answer : 72 Primary Key: A column in a table whose values uniquely identify the
rows in the table. A primary key value cannot be NULL.
Unique Key: Unique Keys are used to uniquely identify each row in the table. There can be one
and only one row for each unique key value. So NULL can be a unique key.There can be only
one primary key for a table but there can be more than one unique for a table.
Question : 73 what is garbage collection? default time ? refresh time?

264

Answer : 73 Garbage Collection is an automated part of PHP , If the Garbage Collection


process runs, it then analyzes any files in the /tmp for any session files that have not been
accessed in a certain amount of time and physically deletes them. Garbage Collection process
only runs in the default session save directory, which is /tmp. If you opt to save your sessions in
a different directory, the Garbage Collection process will ignore it. the Garbage Collection
process does not differentiate between which sessions belong to whom when run. This is
especially important note on shared web servers. If the process is run, it deletes ALL files that
have not been accessed in the directory. There are 3 PHP.ini variables, which deal with the
garbage collector: PHP ini value name default session.gc_maxlifetime 1440 seconds or 24
minutes session.gc_probability 1 session.gc_divisor 100.
Question : 74 What are the advantages/disadvantages of MySQL and PHP? Answer : 74
Both of them are open source software (so free of cost), support
cross platform. php is faster then ASP and JSP.
Question : 75 What is the difference between GROUP BY and ORDER BY in Sql? Answer
: 75 ORDER BY [col1],[col2],,[coln]; Tels DBMS according to what columns it should sort
the result. If two rows will hawe the same value in col1
it will try to sort them according to col2 and so on.GROUP BY [col1],[col2],,[coln]; Tels
DBMS to group results with same value of
column col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, if
you want to count all items in group, sum all values or view average.
Question : 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 if u r storing a value of n-m bytes Set
varchar to occupy n bytes and it will take only the required space and will not use the n bytes
eg. name char(15) will waste 10 bytes if we store 'romharshan', if each char
takes a byte
eg. name varchar(15) will just use 5 bytes if we store 'romharshan', if each
char takes a byte. rest 10 bytes will be free.
Question : 77 What is the functionality of md5 function in PHP?

265

Answer : 77 Calculate the md5 hash of a string. The hash is a 32-character hexadecimal
number. I use it to generate keys which I use to identify users etc. If I add random no techniques
to it the md5 generated nowwill be totally different for the same string I am using.
Question : 78 How can I load data from a text file into a table?
Answer : 78 you can use LOAD DATA INFILE file_name; syntax to load data from a text file.
but you have to make sure thata) data is delimited b) columns and data matched correctly.
Question : 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");
Question : 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);
Question : 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 spl_autoload_register('autoloader::funtion');
Like below
class autoloader
{
public static function moduleautoloader($class)
{
$path = $_SERVER['DOCUMENT_ROOT'] . "/modules/{$class}.php";
if (is_readable($path)) require $path;
}
public static function daoautoloader($class)

266

{
$path = $_SERVER['DOCUMENT_ROOT'] . "/dataobjects/{$class}.php";
if (is_readable($path)) require $path;
}
public static function includesautoloader($class)
{
$path = $_SERVER['DOCUMENT_ROOT'] . "/includes/{$class}.php";
if (is_readable($path)) require $path;
}
}
spl_autoload_register('autoloader::includesautoloader');
spl_autoload_register('autoloader::daoautoloader');
spl_autoload_register('autoloader::moduleautoloader');
Question : 82 How many types of Inheritances used in PHP and how we achieve it.
Answer : 82 As far PHP concern it only support single Inheritance in scripting.
we can also use interface to achieve multiple inheritance.
Question : 83 PHP how to know user has read the email?
Answer : 83 Using Disposition-Notification-To: in mailheader we can get read receipt.Add the
possibility to define a read receipt when sending an email.
Its quite straightforward, just edit email.php, and add this at vars definitions:
var $readReceipt = null;
And then, at createHeader function add:
if (!empty($this->readReceipt)) {
$this->__header .= Disposition-Notification-To: . $this->__formatAddress($this>readReceipt) . $this->_newLine;
}
Question : 84 What are default session time and path?

267

Answer : 84 default session time in PHP is 1440 seconds or 24 minutes


Default session save path id temporary folder /tmp.
Question : 85 how to track user logged out or not? when user is idle ? Answer : 85 By
checking the session variable exist or not while loading th page. As the session will exist longer
as till browser closes. The default behaviour for sessions is to keep a session open indefinitely
and only to expire a session when the browser is closed. This behaviour can be changed in the
php.ini file by altering the line session.cookie_lifetime = 0 to a value in seconds. If you wanted
the session to finish in 5 minutes you would set this to session.cookie_lifetime = 300 and restart
your httpd server.
Question : 86 how to track no of user logged in ?
Answer : 86 whenever a user logs in track the IP, userID etc..and store it in a DB with a active
flag while log out or sesion expire make it inactive. At any time by counting the no: of active
records we can get the no: of visitors.
Question : 87 in PHP for pdf which library used?
Answer : 87 The PDF functions in PHP can create PDF files using the PDFlib library With
version 6, PDFlib offers an object-oriented API for PHP 5 in addition to the function-oriented
API for PHP 4. There is also the Panda module. FPDF is a PHP class which allows to
generate PDF files with pure PHP, that is to say without using the PDFlib library. F from FPDF
stands for Free: you may use it for any kind of usage and modify it to suit your needs. FPDF
requires no extension (except zlib to activate compression and GD for GIF support) and works
with PHP4 and PHP5.
Question : 88 for image work which library?
Answer : 88 we will need to compile PHP with the GD library of image functions for this to
work. GD and PHP may also require other libraries, depending on which image formats you
want to work with.
Question : 89 what is design pattern? singleton pattern?

268

Answer : 89 A design pattern is a general reusable solution to a commonly occurring problem


in software design. The Singleton design pattern allows many parts of a program to share a
single resource without having to work out the details of the sharing themselves.
Question : 90 what are magic methods?
Answer : 90 Magic methods are the members functions that is available to all the instance of
class Magic methods always starts with "__". Eg. __construct All magic methods needs to be
declared as public To use magic method they should be defined 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().
Question : 91 what is magic quotes?
Answer : 91 Magic Quotes is a process that automatically escapes incoming data to the PHP
script. Its preferred to code with magic quotes off and to instead escape the data at runtime, as
needed. This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0.
Relying on this feature is highly discouraged.
Question : 92 what is cross site scripting? SQL injection?
Answer : 92 Cross-site scripting (XSS) is a type of computer security vulnerability typically
found in web applications which allow code injection by malicious web users into the web
pages viewed by other users. Examples of 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 of an application. The vulnerability is present when user input is either
incorrectly filtered for string literal escape characters embedded in SQL statements or user input
is not strongly typed and thereby unexpectedly executed.
Question : 93 what is URL rewriting?
Answer : 93 Using URL rewriting we can convert dynamic URl to static URL Static URLs are
known to be better than Dynamic URLs because of a number of reasons 1. Static URLs
typically Rank better in Search Engines. 2. Search Engines are known to index the content of
dynamic pages a lot slower compared to static pages. 3. Static URLs are always more friendlier
looking to the End Users. along with this we can use URL rewriting in adding variables
[cookies] to the URL to handle the sessions.

269

Question : 94 what is the major php security hole? how to avoid?


Answer : 94 1. Never include, require, or otherwise open a file with a filename based on user
input, without thoroughly checking it first.
2. Be careful with eval() Placing user-inputted values into the eval() function can be extremely
dangerous. You essentially give the malicious user the ability to execute any command he or she
wishes!
3. Be careful when using register_globals = ON It was originally designed to make
programming in PHP easier (and that it did), but misuse of it often led to security holes
4. Never run unescaped queries
5. For protected areas, use sessions or validate the login every time.
6. If you dont want the file contents to be seen, give the file a .php extension.
Question : 95 whether PHP supports Microsoft SQL server ?
Answer : 95 The SQL Server Driver for PHP v1.0 is designed to enable reliable, scalable
integration with SQL Server for PHP applications deployed on the Windows platform. The
Driver for PHP is a PHP 5 extension that allows the reading and writing of SQL Server data
from within PHP scripts. using MSSQL or ODBC modules we can access Microsoft SQL
server.
Question : 96 what is MVC? why its been used?
Answer : 96 Model-view-controller (MVC) is an architectural pattern used in software
engineering. Successful use of the pattern isolates business logic from user interface
considerations, resulting in an application where it is easier to modify either the visual
appearance of the application or the underlying business rules without affecting the other. In
MVC, the model represents the information (the data) of the application; the view corresponds
to elements of the user interface such as text, checkbox items, and so forth; and the controller
manages the communication of data and the business rules used to manipulate the data to and
from the model. WHY ITS NEEDED IS 1 Modular separation of function 2 Easier to maintain
3 View-Controller separation means:
A Tweaking design (HTML) without altering code B Web design staff can modify UI without
understanding code.

270

Question : 97 what is framework? how it works? what is advantage? Answer : 97 In


general, a framework is a real or conceptual structure intended to serve as a support or guide for
the building of something that expands the structure into something useful. Advantages :
Consistent Programming Model Direct Support for Security Simplified Development Efforts
Easy Application Deployment and Maintenance.
Question : 98 what is CURL?
Answer : 98 CURL means Client URL Library
curl is a command line tool for transferring files with URL syntax, supporting FTP, FTPS,
HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS and FILE. curl supports
SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies,
cookies, user+password authentication (Basic, Digest, NTLM, Negotiate), file transfer resume,
proxy tunneling and a busload of other useful tricks. CURL allows you to connect and
communicate to many different types of servers with many different types of protocols. libcurl
currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also
supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading. HTTP form based
upload, proxies, cookies, and user+password authentication.
Question : 99 what is PDO ?
Answer : 99
The PDO ( PHP Data Objects ) extension defines a lightweight, consistent interface for
accessing databases in PHP. if you are using the PDO API, you could switch the database server
you used, from 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 of the advanced features that are available in the latest
versions of MySQL server. For example, PDO does not allow you to use MySQL's support for
Multiple Statements.
Just need to use below code for connect mysql using PDO
try {
$dbh = new PDO("mysql:host=$hostname;dbname=databasename", $username, $password);
$sql = "SELECT * FROM employee";
foreach ($dbh->query($sql) as $row)

271

{
print $row['employee_name'] .' - '. $row['employee_age'] ;
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
Question : 100 What is PHP's mysqli Extension?
Answer : 100
The mysqli extension, or as it is sometimes known, the MySQL improved extension, was
developed to take advantage of new features found 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 of benefits, the key enhancements over the mysql extension
being:
=>Object-oriented interface
=>Support for Prepared Statements
=>Support for Multiple Statements
=>Support for Transactions
=>Enhanced debugging capabilities

B.Praveen Kumar(Trainer in
PHP)
Sathya Technology,Ameerpet.
e-mailid:praveen.lamp@gmail.com

Anda mungkin juga menyukai