PHP - Notes
PHP - Notes
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
<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
Target = -self
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
13
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:
17
18
// class selector
//.x{font-family:impact;}
p.x{font-size:20pt;color:black;}
</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
20
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
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.
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
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
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
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
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
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
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(),
)
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
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
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)
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
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";
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
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
63
<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;
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
67
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
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
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
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
90
91
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
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,
104
105
http://localhost/abc(folder name)/first.php
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
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:
4. Comparison operator:
==,!= ,===
5. Relational operator:
6. Logical 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
115
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
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
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
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 {
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
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)
137
138
139
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
143
144
145
?>
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
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
";
154
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
r+
w+
a+
x+
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
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
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
GET
POST
2.GET is insecure
POST is secure
up by using POST_MAX_SIZE
5.It is fast
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 '<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
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
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
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
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
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
177
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
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
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
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)
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
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
188
189
190
191
192
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
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
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
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
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
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
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
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
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
217
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
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
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
--------------------------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
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
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
242
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
PHP_Interview_questions
245
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
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()
249
250
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
254
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
GET/QueryString
POST
256
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
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
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
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
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
268
269
270
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