0% found this document useful (0 votes)
2K views

BCA - (WEB PROGRAMMING) (Total 5 Units PDF

The document contains the syllabus for a Web Programming lecture course covering HTML, JavaScript, PHP, and working with forms, cookies, and user sessions in PHP. The syllabus outlines 5 units: (1) basics of HTML and JavaScript, (2) introduction to PHP, (3) advanced PHP, (4) working with forms in PHP, and (5) working with cookies and user sessions. It provides an overview of the topics that will be covered in each unit, such as HTML tags, PHP arrays and objects, file handling in PHP, and using sessions in PHP.

Uploaded by

nsahithin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views

BCA - (WEB PROGRAMMING) (Total 5 Units PDF

The document contains the syllabus for a Web Programming lecture course covering HTML, JavaScript, PHP, and working with forms, cookies, and user sessions in PHP. The syllabus outlines 5 units: (1) basics of HTML and JavaScript, (2) introduction to PHP, (3) advanced PHP, (4) working with forms in PHP, and (5) working with cookies and user sessions. It provides an overview of the topics that will be covered in each unit, such as HTML tags, PHP arrays and objects, file handling in PHP, and using sessions in PHP.

Uploaded by

nsahithin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 153

LECTURE NOTES

WEB PROGRAMMING
2023-2024
II BCA IV Semester

ADITYA DEGREE COLLEGE


KAKINADA

Department of Computer Science


2

SYLLABUS

Unit-I: Basics of HTML & Java Scripts


Basics of HTML & Java Script: Basic structure of an HTML document, HTML Tags, Lists, Tables
and Frames, Forms and controls. Java Script: Introduction – Basic commands – Variables –
Operators – Control structures – Arrays - Window and document object – Forms and form
elements – String, math and dates – multiple windows.

Unit-II: Introduction to PHP


Basics of PHP: Introduction to PHP, Identifiers, Variables, Constants, Data Types, Operators,
Conditional Statements, PHP Loops. Working with Arrays: Arrays, Creating Arrays, some Array-
Related Functions. Working with Objects: Creating Objects, Object Instance. Working with
Strings, Dates and Time: Formatting Strings with PHP),Investigating Strings with PHP,
Manipulating Strings with PHP, Using Date and Time Functions in PHP.

Unit-III: Advanced PHP

Advanced PHP: Functions, Advantages of Using functions, Types of functions, creating and
invoking functions, returning values, recursive functions Object Oriented Concepts, File
handling and Data Storage: creating, open/close a file, file operations: read, write, append. File
truncate, file uploading, EOF in PHP.
Unit-IV: Working with Forms in PHP
Creating Forms, Accessing Form - Input with User defined Arrays, Combining HTML and PHP
code on a single Page, Using Hidden Fields to save state, Redirecting the user.
PHP with MySQL: Creating Database in MySQL, Connecting to MYSQL, Reading and Writing
form data from MYSQL
Unit-V: Working with Cookies and User Session

Working with Cookies and User Sessions: Introducing Cookies, Setting a Cookie with PHP,
Session Function Overview, Starting a Session, Working with session variables, passing session
IDs in the Query String, Destroying Sessions and Unsettling Variables, Using Sessions in an
Environment with Registered Users.
3

DEFINE HTML? EXPLAIN THE HISTORY OR HTML?

HTML Stands for Hyper Text Markup Lan guage

Hyp er text is simply a piece of text that works as a l ink.

Markup Language is a way of writing layout information within document.

HTML is the lang ua g e designed for crea ting web- page s. Html pro vides
a way for create web pages with text, i mages, or mul timedia content using
pr ed ef in ed tags saved as HTML f i le. The langua ge used to displa y web pages
is called HTML. Html is a syntax used to format a text document on the web
HTML is the langua g e in te rp re t ed by a b rowser. Such as 1 ) internet ex plorer
2 ) Netscape n avi gator 3 ) mozi lla Fire fox 4 ) opera

HTML separates “ content” from “ pres en tation ” here content are


words, images; audi o, video etc. Prese n tati on is definition of the type of
content and the i nstructi ons for how that type of content should be
di splayed. It is predefi n ed set of elements to identify contents types where
elements contai n one or more “ tags” that express content.

HISTORY OF HTML

In 1980, physicist Tim Berners- Lee, who was a contractor at CER N, proposed and
prototyped ENQUIRE, a system for CERN researchers to use and share documents. In
1989, Berners-Lee wrote a memo proposing an Internet-based hypertext system.
Berners-Lee specified HTML and wrote the browser and server software in late 1990. That
year, Berners-Lee and CERN data systems engineer Robert Cailliau collaborated on a joint
request for funding, but the project was not formally adopted by CERN. The first publicly
available description of HTML was a document called "HTML Tags", first mentioned on the
Internet by Berners-Lee in late 1991

HTML Versions
Since the early days of the web, there have been many versions of HTML:
Version Year

HTML 1991

HTML+ 1993
4

HTML 2.0 1995

HTML 3.2 1997

HTML 4.01 1999

XHTML 2000

HTML5 2012

EXPLAIN THE TYPES OF TAGS IN HTML?

Html is used to define document stru cture with the help of a single or a pair
of tags. A tag is a stri ng in the language su rrou nded by a less than ( <) and
a gr eat er than ( >) sign. An opening tag is spe cified as tag name and ending
tag is begin with slash (/), </ tag name)

They are two types of tags

1 ) Paired Tags 2 ) U np ai re d Tags

PAIRED TAGS : a tag is said to be a paired tag i f the text is placed betwe en
a tag and its compani on tag ( end tag). In paired tags, the f i rst tag is
referred to as opening tag and the second tag is referred to as closing tag.

Exampl e: <i> BCA i talic </ i>

<h 1 > ADCW </ h 1 >

UNPAIRED TAGS: An unpai red tag does not have a companion tag. Un
paired tags are also know as singular or stand- al one tags.

Exampl e: <br>

<hr>

EXPLAIN THE STRUCTURE OF HTML DOCUMENT WITH NEAT DIAGRAM?

Every HTML program has a rigid structure.


The entire web page is enclosed with in <HTML> </HTML>tags.
Withi n these tags two separate sections are created using the
<HEAD>…..</HEAD> tags and he <BODY>…..</BODY> tags. These tags are
5

1) Document Head Section


2) Document Body Section

DOCUMENT HEAD SECTION: Information placed in this section is essential to the inner
workings of the documents and has nothing to do with the content of the document. With
the exception of information contained within the <TITLE>…</TITLE> tags, all information
placed with in the <HEAD>…</HEAD>tags is not displayed in the browser.

DOCUMENT BODY SECTION: This area is used to display the content of the webpage with
required formats presented in the form of
sub tags inside the start and end of the
main body of textual information
<BODY>….</BODY>

<BODY> Tag contains the content of the


webpage.
6

EXPLAIN THE ATTRIBUTES (OR) PROPERTIES OF HTML?

Attributes allow to add extra instruction to selected tag. Because each tag has its
own unique attributes.

 HTML elements can have attributes


 Attributes provide additional information about an element
 Attributes are always specified in the start tag
 Attributes come in name/value pairs like: name="value"

They are common attributes of HTML

Title Spe cifies extra i nfo r m a tio n about an elem ent ( displ ay ed as a tool tip)

Id Speci fi es a uni que id for an element

Style Speci fi es an inli ne CSS style for an element

Specifies one or more class names for an element ( refers to a class in


Class
a styl e sheet)

WRITE STEPS TO CREATE A HTML DO CUMENT?

( OR)

WRITE THE PROCEDURE TO CREATE A HTML DO CUMENT?

To create a HTML document your need to use a text editor to create a


ASCII ( American Standard Code for Information Interchange) file with an extension of
.html or .htm
7

Steps to create a HTML DOCUMENT

1) open a text editor (notepad) or Start Run Notepad


2) Type the html code in a blank text file
3) Save the file by selecting the required drive and folder with .HTML or .HTM
extension
Every HTML document has two parts or sections the associated html tags are
<HEAD> with closing tag</HEAD> and <BODY> with closing tag </BODY>
respectively. They are also called

1) DOCUMENT HEAD SECTION

2) DOCUMENT BODY SECTION

Surrounding all the text in the entire file are the beginning and ending HTML tags <HTML>
AND </HTML>. These tags let the browser know that the file is indeed an HTML file.

A title tag <TITLE> is contained wit in te head of the document to provide a tile for
document with have end tag </title> we can include any HTML formatting with in the title
tag.
EXAMPLE:

<HTML>

<HEAD>

<TITLE> ASCS-KKD </TITLE>

</HEAD>

<BODY>

THIS IS BCA WEBPAGE

</BODY>

</HTML>

Save the file g.html Run the file in web browser.


8

EXPLAIN THE FEATURES OF THE HTML PROGRAM?

HTML, which stands for Hypertext Markup Language, is the predominant markup language
for web pages. With HTML you can create your own website. It is written in the form of
HTML elements consisting of “tags” surrounded by angle brackets with in the web page
content.

It allows images and objects to be embedded and can be used to create interactive
forms. It provides a means to create structured documents by denoting structural semantics
for text such as headings, paragraphs, lists, links, quotes and other items. It can embed
scripts in languages such as JavaScript which affect the behavior of HTML web pages

HTML can also be used to include Cascading Style Sheets (CSS) to define the
appearance and layout of text and other material. The W3C, maintainer of both HTML and
CSS standards, encourages the use of CSS over explicit presentational markup

EXPLAIN DOCUMENT BODY SECTION & IT’S ATTRIBUTES OF HTML?

(OR)

EXPLAIN DOCUMENT BODY IN DETAIL?

(OR)

EXPLAIN THE DOCUMENT BODY AND IT PROPERTIES WITH EXAMPLE?

The body tag is the second & main part of every html document. The tags
used to indicate the start and end of the main body of textual information. This is a paired
element it contains start and end tag <BODY>…. </BODY>

The data given in between these tag is displayed in the work area of the browser
window.
9

By default the background color of the body is displayed in white and the text color is
indicated with black. In order to change the default properties and formats the display
structure of the body tag & it’s attributes to change The attributes of the <body> are

1) BGCOLOR 2) BACKGROUND 3) TEXT

4) ALINK, VLINK, LINK 5) BGPROPERTIES 6) BOTTOM MARGIN

7) MARGIN HEIGHT/WIDTH 8) SCROLL 9) RIGHT/LEFT MARGIN

BGCOLOR: it changes the default background color to user defined color specified in the
tag. The user can specify the color name or hexadecimal number

Syntax: < BODY BGCOLOR= “NAME / HEXADECIMAL NUMBER”>

EX: BODY BGCOLOR= “RED” (OR) BODY BGCOLOR= “#45FF79”

<html>

<head>

<title> adcwbgcolor</title>

</head>

<body bgcolor="green">

</body>

</html>

BACKGROUND: it is used to change background according to user specified image file used
as the background of the document (i.e. GIF or jpeg file etc)

Syntax: <BODY BACKGROUND =” <drive,path,filename> (OR) File name>

Ex: BODY BACKGROUND =”C:\Users\Public\Pictures\um.jpg”

<html>

<head>
10

<title> adcwbgcolor</title>

</head>

<body background="C:\Users\Public\Pictures\mum.jpg">

</body>

</html>

TEXT : Changes the body text color from its default color to user defined color

SYNTAX: <TEXT = “COLORNAME OR HEXADECIMAL NUMBER”>

EX: TEXT =”RED” OR “#22FFCC”

<HTML>

<HEAD>

<TITLE>MSTCSIIIRD</TITLE>

</HEAD>

<BODY TEXT= RED>

<P> MSTCS GIRLS ARE GOOD</P>

</BODY>

</HTML>

ALINK, VLINK, and LINK: It specifies the color of Active link, Visited link and link which is
not visited.

Syntax: ALINK <COLORNAME> HLINK <COLORNAME> LINK <COLORNAME>

EXAMPLE: ALINK=YELLOW HLINK=GREEN LINK=BLACK

<HTML>

<HEAD>

<TITLE>MSTCW </TITLE> </HEAD>

<BODY ALINK=RED VLINK=YELLOW HLINK=BLACK>

<A HREF="file:///C:/Users /A.HTML” TITLE = "CLICK HERE">NEXT /A>


11

</BODY>

</HTML>

BGPROPERTIES: This property indicates horizontal scroll bar for the web pages i.e. values
(FIXED / SCROLL)

Syntax: BGPROPERTIES <SPECIFIES VALUE>

Example: BGPROPERTIES =”SCROLL” OR “FIXED”

<html>

<head>

<title>m</title>

</head>

<body bgproperties="scroll"

scroll="yes">

<img src="D:\WEB_GSK\IM.jpg">

</body>

</html>

MARGIN HEIGHT/WIDTH: Give the height and the width of the document towards right
left top bottom

Syntax: MARGINHEIGHT=<VALUE>

EXAMPLE: MARGINHEIGHT=50 (OR) MARGINWIDTH=50

RIGHT/LEFT MARGIN: It shows margin distance from the border of the webpage and text
and user want to give integer value

Syntax: RIGHTMARGIN=<VALUE>
12

EXAMPLE: RIGHTMARGIN=40 (OR) LEFTMARGIN=50

SCROLL: it shows vertical scroll bar and values (yes/no)

Syntax: Scroll < yes/no>

Example: Scroll = yes

<html>

<head>

<title>aditya </title>

</head>

<body BGPROPERTIES="SCROLL"

LEFTMARGIN=10

MARGINHEIGHT=10

MARGINWIDTH=10

RIGHTMARGIN=10

SCROLL="no">

<IMG SRC ="D:\DBMS_GSK\IM.jpg">

</BODY>

</HTML>

<!—PROGRAM TO ILLUSTRATE THE BODY TAG AND ITS ATTRIBUTES -- >

<html>

<head>

<title>aditya </title>
13

</head>

<body alink=yellow vlink=red link=WHITE

bgcolor="#010101"

text=white

bgproperties="scroll"

LEFTMARGIN=50

MARGINHEIGHT=30

MARGINWIDTH=20

RIGHTMARGIN=30

SCROLL="yes">

<CENTER>

<H1> WELCOME TO HTML PAGES </H1>

<IMG SRC ="D:\DBMS_GSK\IM.jpg">

<H2> <A HREF ="D:\DBMS_GSK\G1.HTML" TITLE="CLICK HERE"> NEXT </A> </H2>

</BODY>

</HTML>

EXPLAIN ABOUT TEXT FORMATTING TAGS?

(OR)

EXPLAIN ABOUT VARIOUS TEXT FORMATTING TAGS OF HTML WITH EXAMPLE AND
SYNTAX?

The text formatting tags are used to format the appearance of the text on your web
page. They are several formatting tags to change the appearance of the text according
specified tag given in it.
14

The formatting tags are

1) BOLD 2) ITALICS 3) UNDERLINE 4) PARAGRAPH


5.) LINE BREAKS 6) CENTER 7) STRONG 8) TYPEWRITER

9) STRIKE 10) SUBSCRIPT 11) SUPERSCRIPT 12) BLINK

13) HEADER TAGS 14) FONTSIZE, COLOR, FACE 15) BGSOUND

16) <BR> 17) <PRE>

BOLD: it displays the text in bold style.

Syntax: <B>….. </B>

Example <B> Gsk </B> GSK

ITALIC: it displays the text in italic style

Syntax: <I>….. </I>

Example <I> GS </I> GS

UNDERLINE: It displays the text as underline style

Syntax: <U>….. </U>

Example <U> GSK </U> GSK

PARAGRAPH: It provides a blank line and separates paragraphs in the textual. This
paragraph tag provides same functionality.

Syntax: <P>……</P>

Example: <P> html is a language is to design web pages </P>

LINEBREAK: it provides breaks between the text line if user want to start a text in new
line. i.e. it simply jumps to next line of the page. It doesn’t have no end tag

Syntax: <BR>… text


15

Example: <br> html is a language<br> is to design web pages <br>

CENTER: It is used to center everything in between them i.e. text, images, tables, etc.

Syntax: <CENTER>….. </CENTER>

Example: <CENTER> SRIKANTH </CENTER>

STRONG: it is also work as a bold tag, it displays the text in bold style only. But some of
the web browsers that cannot render the text as bold. So that purpose we want to use
strong tag.

Syntax: <STRONG>….</STRONG>

Example: <STRONG> SRIK </STRONG>

TYPEWRITER: The text appears to have been typed by a typewriter, in a fixed-width font.

Syntax: <TT>…..</TT>

Example: <TT> html is language</TT> html is language

STRIKE: Puts a line right through the centre of the text, crossing it out. Often used to show
that text is old and no longer relevant.

Syntax: <S>….</S>

Example: <S> srikanth</s> srikanth

SUBSCRIPT: it is used to generate a subscript function which displays the text in lower
position enclosed in <sub>…</sub>.

Syntax: text/number<sub>text/number

Example: H <SUB> 2 <SUB> O OUTPUT: H20

SUPERSCRIPT: it is used to generate a superscript function. It displays the text in raised


position of the text in <sup>….</sup>
16

Syntax: text/number <sup> text/number <sup>

Example: A<SUP>2+B<SUP>2+C=0 OUTPUT A2+B2+C=0

BLINK: it is used to display the flashing text. But it is browser dependent element.

Syntax: <BLINK>…..</BLINK>

Example: <BLINK>NAGA </BLINK>

HEADER TAGS: It supports six different levels of headings. In this the highest level header
tag is <H1> and lowest tag is <H6>. All styles appear in boldface and the size is depending
on tag used by the user.

Syntax: <H1>……</H1> .......... <H6>……</H6>

Example: <h1>gns</h1> GNS

<h2>naga </h2> naga

FONTFACE/COLOR/SIZE: It displays text in a particular font, use the font name such
"Helvetica" or "Arial" or "Courier". So that also color. Its display’s the color according to
specify in the tag same as the size also it display the size according to specify in the tag

Syntax: <font face="font name"> </font>

Example: <font face=”Arial”> THIS IS WEB </font>

Syntax: <font color="#hexadecimal / name"> </font>

Example: <font color=”red”> THIS IS WEB </font>

Syntax:<font size="?"> </font>

Example: <font size =”3”> THIS IS WEB </font>

NOTE: The font size is in between 1 to 7 only i.e. minimum value is 1 and maximum
value is 7 where are default value is 3
17

BR (BREAK) A br tag will insert a line break which means the text/image following the tag
will be moved to the next line when displayed in the browser.

Syntax: <BR> TEXT

Example: here the text display some thing <br>

<PRE>: This element display the text as it is given in the source code with all formats that
means spacing, tabulation etc.

Syntax: <PRE> TEXT </PRE> EX: <PRE>TEXT DISPLAY </PRE>

BGSOUND: its play a background sound when your webpage is opened. This tag must be
placed in <head> tag and the user must mention file extension of the audio

Syntax: <BGSOUND SRC = “FILENAME WITH EXTENSION”

Example: <BGSOUND SRC = “"audio/welcome.wav" />

WRITE A PROGRAM TO CREATE A WEBPAGE USING TEXT FORMATTING TAGS

<!..Program to display text formatting tags ..>

<HTML>

<HEAD>

<TITLE> TEXT FORMATTING TAG </TITLE>

<BODY BGCOLOR = “CORAL” TEXT= WHITE>

<H1>TEXT TAGS </H1>

<H2><B>TEXT IN HTML BOLD </B> </H2> <BR>

<H3><I> TEXT IN HTML ITLAIC </I> </H3> <BR>

<H4><U> TEXT IN HTML UNDERLINE </U> </H4> <BR>

<P> TEXT IN HTML PARAGRAPH </P> <BR>

<H5><CENTER> TEXT IN HTML CENTER </CENTER> </H5> <BR>


18

<H6><STRONG> TEXT IN HTML STRONG </STRONG> </H6> <BR>

<TT> TEXT IN HTML TYPEWRITER </TT> <BR>

<STRIKE> TEXT IN HTML STRIKE </STRIKE> <BR>

<H1> H<SUB>2</SUB>O </H1> <BR>

<H2> AX<SUP>2</SUP>+BX<SUP>2</SUP>+C=0 </H2> <BR>

<H3> <BLINK> WEBTECHNOLOGIES </BLINK> </H3> <BR>

<H4> <FONT FACE=Arial> THIS IS WEB TECH</FONT> </H4> <BR>

<FONT COLOR =RED> THIS IS WEBADC </FONT> <BR>

<FONT SIZE =7> THIS IS WEBADC </FONT> <BR>

</HEAD>

<HTML>

DEFINE HYPERLINK? AND EXPLAIN THE TYPES OF HYPERLINKS? (OR)

HOW MANY WAYS WE CAN CREATE HYPERLINKS? EXPLAIN?

A hyperlink is a special tag can contain links that takes directly to other pages and even
specific parts of a given page. These links are known as hyperlinks. Hyperlinks allow visitors
to navigate between websites by clicking on words, phrases, and images. Thus one can
create hyperlink by using data available in the webpage. We can create multiple pages with
the clickable hyperlinked text is considered as hyperlinks. In hyperlink tag consists start tag
and end tag (<a> </a>) is used to create a hyperlink

They are four types of hyperlinks are there

1) Text hyperlink
2) Image hyperlink
3) Mailto hyperlink
4) Intra Document hyperlink

TEXT HYPERLINKS: It is created to the selected text written between <a></a> tag is
considered as hyper text and by clicking on the text the page is connected dynamically.
19
1) In the text hyperlink, a page in the same folder
2) A page in the system i.e. by specifying the full path of the file.
3) A web page, by specifying the URL of the webpage

Syntax: < A HREF = “FILENAME / PATH ” > …. </A>

Example: < A HREF =”"http://www.yahoo.com"> CLICK HERE </A>

<!—PROGRAM TO IMPLEMENT TEXT HYPERLINK -->

<HTML>

<HEAD>

<TITLE> MSTCS </TITLE>

</HEAD>

<BODY BGCOLOR ="BLACK" ALINK=GREEN VLINK=RED LINK=BLACK>

<BR>

<H1><CENTER><AHREF="https://www.google.co.in">GOOGLE</A></H1></CENT
ER>

</BODY>

</HTML>
20

IMAGE HYPERLINKS:

The image hyperlink is same as the text hyperlink. For a image, one mouse click
returns an HTML document or any related image file or file. It is simply replace as text
hyperlink with an image hyperlink. The image is displayed with default border of blue color
and with a linkable cursor pointer.

Syntax: < A HREF = “PATH/FILE” >

<IMG SRC =” IMAGE FILE NAME“ WITH VALUES> </A>

Example: <A HREF="https://www.google.co.in">GOOGLE

< IMG SRC =”IMG SRC = "C:\Users\staff\Desktop\Tulips.jpg"

HEIGHT=150 WIDTH=100> </A>

<!-- PROGRAM TO IMPLEMENT IMAGE HYPERLINK -->

<HTML>

<HEAD>

<TITLE> MSTCS </TITLE>

</HEAD>

<BODY>

<A HREF="https://www.google.co.in">

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


21

<CENTER><IMG SRC = "C:\Users\staff\Desktop\Tulips.jpg" HEIGHT=150 WIDTH=100>

</CENTER>

</BODY>

</HTML>

MAILTO HYPERLINK: This tag provides you facility to specify an email address to send an
email. While anchor tag as an email tag then we sue mailto:emailaddress along with
properties of HREF. It is the common to add a mailto hyperlink to a webpage. It provides
you send email by opening a default mailbox with the id in sender URL

Syntax: < A HREF =”mailto: mail id” > text </A>

Example: <A HREF= "MAILTO:gantinagasrikanth@gmail.com">srikanth </A>

<!—PROGRAM TO IMPLEMENT MAIL TO HYPERLINK -->

<HTML>

<HEAD>

<TITLE> MSTCS </TITLE>

</HEAD>

<BODY>

<H1> <CENTER>

<A HREF= "MAILTO:gantinagasrikanth@gmail.com">srikanth </A>

</CENTER> </H1> </CENTER>

</BODY> </HTML>

INTRA DOCUMENT LINKING (OR) INTRA HYPERLINK

The tag give you create a hyperlink to any part of your document, rather than just
the beginning i.e., any portion of the document can automatically be displayed at the top of
the browser’s document area. This is particularly useful if you have a long webpage and
user would like to be able to jump to various section of it without scrolling.

The internal links will specified with # symbol followed by link attribute
22

<HTML>

<HEAD>

<TITLE> MSTCS </TITLE>

</HEAD>

<BODY>

<a href ="#MSTCS-I">CHAPTER1: HTML </a><br>

<a href="#MSCTS-II">CHAPTER2: dthml </a><br>

<a href ="#MSTCS-III">CHAPTER3: vbscript </a><br>

<a name= "CHAPTER1">

<h3> html </h3> HYPER TEXT MARKUPLANGUAGE

</a>

<a name= "CHAPTER2>

<h3> dhtml </h3>

Dynamic hypertext MARKUPLANGUAGE

</a>

<a name= "CHAPTER3">

<h3> vbscript </h3>

Visual basic

</a>

</BODY>

</HTML>

DEFINE ANCHOR TAG?

The <a> tag defines a hyperlink, which is used to link from one page to another is
know as Anchor tag. The most important attribute of the <a> element is the href attribute,
which indicates the link's destination. The term “anchor” is used because it indicates the
static positioning of a hyperlink.
23

Syntax: <a href =”document url” attr_name=”attr_value” />

Example: <a href="http://www.gnscollege.com">Visit </a>

Program: <html>

<head>

<title> mstcs </title> </head>

<body>

<a href="http://www.w3schools.com">Visit W3Schools.com! </a>

</body> </html>

WHAT IS MEANT BY PATH? EXPLAIN DIFFERENT PATHS IN HYPER LINKS?

(OR)

DEFINE PATH? DISCUSS THE DIFFERENCE BETWEEN RELATIVE PATHS &


ABSOLUTE PATHS IN HYPER LINKS?

PATHS: path is the location of the file which is linked to the text given between <a>….
</a> element. The location can be local or
external address can be specified using absolute /
relative reference.

Relative Path: This is used when a file is


located in the same folder where the documents are
stored i.e., HTML files.

Syntax: <A HREF = “FILENAME”>TEXT </A>

Example: < A HREF =”college.HTML”> CLICK </A>

Absolute Path: It is used if the file is located on the remote area that means outside of
the folder. In this path we will give complete location reference which includes Drive, Folder
name, Filename with extension.

Syntax: < A HREF =”Path/Filename”>text </A>


24

Example: <a href="d:\gns\college.html">Visit </a>

WHAT ARE LISTS? EXPLAIN DIFFERENT TYPES OF LISTS IN HTML?

(OR)

DEVELOP A HTML WEB PAGE THAT EXPLAINS LISTS?

List is the process of displaying the data in bullets / numbering format. It have 3
types of lists 1) Unordered list 2) Ordered list 3) Definition list

Here in the list <LI> tag is considered as the list item for all lists. In list tags the
closing tag is not compulsory for <LI>tag

UNORDERED LISTS: It is a collection of related items that have no order or sequence. This
list is created by using <UL>tag. Each item in the list is marked as a bullet.

The list types are DISC, SQUARE, and CIRCLE in this the default list is DISC Most of
the browsers will display disc. An unordered list starts with <UL>tag and end with </UL>

Syntax: <UL TYPE = [ATTRIBUTE NAME]>

Example: <UL TYPE=SQUARE>

<!—PROGRAM TO IMPLEMENT UNORDERED LISTS -->

<html>

<body>

<h4>An Unordered List:</h4>

<H3>GROUP</H4>

<ul>

<li>MSTCS</li>

<li>BBM</li>
25

<li>MPCS</li>

</ul>

</body>

</html>

ORDERED LIST: The content of an ordered list just like an unordered list, except that the
items are numbered instead of bullets. The number starts from one and incremented by one
presented in the <li> tag. The list is created by using <ol> tag.

They attributes are 1) Type 2) Start 3) Value

1) Type: in type we want to mention either Numbers, Alphabets and Roman


2) Start: it alters the sequence of numbering
3) Value: change the number sequence
Syntax: <OL TYPE = [ATTRIBUTE NAME]>

Example: <OL TYPE=I>

<!—PROGRAM TO IMPLEMENT ORDERED LIST -->

<html>

<body>

<h4>An Ordered List:</h4>

<H5>GROUP</H5>

<ol TYPE =I>

<li>MSTCS</li>

<li>BBM</li>

<li>MPCS</li>

</ol>
26

</body>

</html>

DEFINITION LIST: A definition list is a list of terms and corresponding definitions.


Definition lists are typically formatted with the term on the left with the definition following
on the right or on the next line. The definition text is typically indented with respect to the
term.

The list is works just like a entries find in a dictionary or encyclopedia, complete with
text and other elements. The elements used to create in Definition list

 <dl> it is the start tag in the list it contains end tag also </dl>
 <dt> it determines the Definition term
 <dd> it determines the Definition data
Syntax: <dl>

<dt> [text] </dt>

<dd>[text] </dd>

</dl>

Example: <dl>

<dt>Mstcs</dt>

<dd>- Maths, Stats,Computer </dd>

<dt>BBM</dt>

<dd>- Management, Accounts,Computer</dd>

</dl>

<!—PROGRAM TO IMPLEMENT THE DEFINITION LISTS -->

<html>

<body>
27

<h4>A Definition List:</h4>

<dl>

<dt>Mstcs</dt>

<dd>- Maths, Stats,Computer </dd>

<dt>BBM</dt>

<dd>- Management, Accounts,Computer</dd>

</dl>

</body>

</html>

NESTED LIST: It is method of combining more than one list in a selected list the list can
be nested to display the sub list details. It may contains ordered and unordered lists in a
nested list

Syntax:
<ul>
<Li>List item one</li>
<li>List item two with subitems :</li>
<ul>
<li>Subitem 1</li>
<li>Subitem 2</li>
</ul>
<li>Final list item</li>
</ul>
Example: <ul>

<li>GROUP</li>

<li>MSTCS

<ul>

<li>IST YEAR</li>

<li>IIND YEAR</li>
28

<li>IIIRD YEAR </li>

</ul>

</li>

<li>BBM</li>

</ul>

<!—PROGRAM TO IMPLEMENTED NESTED LIST-->

<html>

<body>

<h4>A nested List:</h4>

<ul>

<li>GROUP</li>

<li>MSTCS

<ul>

<li>IST YEAR</li>

<li>IIND YEAR</li>

<li>IIIRD YEAR </li>

</ul>

</li>

<li>BBM</li>

</ul>

</body>

</html>
29

<!—PROGRAM TO IMPLEMENT THE ORDERED LIST AND UNORDERED LIST>

<html>

<body BGCOLOR=ORANGE>

<H1>COURSES OFFERED </H1>

<H2>

<OL TYPE=I>

<LI>UG COURSES </H2>

<UL TYPE=SQUARE>

<LI>B.COM

<OL>

<LI>COMPUTERS

<LI>REGULAR

<LI>HONORS

</OL>

<BR><LI>B.SC

<UL TYPE=DISC>

<LI>MPCS

<LI>MSTCS

<LI>MECS

</UL><BR>

<LI>PROFESSIONAL COURSES

<UL TYPE=CIRCLE>

<LI>BCA

<LI>BBM

</UL><BR>

<LI>PG COURSES
30

<OL TYPE=A>

<LI>MCA

<LI>MBA

<LI>MSC (COMP, BIOCHEM, CHEM...)

</OL></OL>

</body>

</html>

EXPLAIN ABOUT TABLES IN HTML?

(OR)

EXPLAIN HOW TO CREATE TABLES IN HTML?

Tables in HTML pages allow you to organize information in a row and column format.
The HTML table model allows authors to arrange data text, preformatted text, images, links,
forms, form fields, other tables, etc. into rows and columns of cells. HTML table are used to
present any type of information for which you want a lot of control over the positioning of
the material

There are many ways to use tables to format information on the web. There is a
good chance it was produced using tables. They are some points to use in tables.

1) Present tabular information


2) Control layout
3) Express relationships

PRESENT TABULAR INFORMATION: If you have information or data that is naturally


divided into rows and columns, it can probably be easy and effectively formatted using
HTML

CONTROL LAYOUT: if you want to control the layout of text position a group of images, or
present an extensive menu, you may decide to use tables to achieve desired appearance

EXPRESS RELATIONSHIPS: If you need to display relationships between a group of


items, tables are usually a good mechanism to use.

CREATION OF TABLE

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


31

To construct tables in HTML, the basic element <table> is used to create the
structure of the table. Then the number of rows and columns are decided with TR and TD
elements.<TR> this element is used to create a table row where as <TD>&<TH> are used
to to insert the cells in the selected row

Table Row <TR>: The TR (table row) elements act as a container for a row of table cells.
Used to create table row, A horizontal structure is available to insert the data. A table can
contain an infinite number of table rows. Each table row of table element itself, with an
opening and closing tag <tr>….</tr>.where as columns are considered child elements of
Html tables. Where as table may contain an infinite number of table data cells (<td><tr>)

Table Cells: The TH and TD elements are used to define the cells in the selected row of the
table. TH is used to create a table header displayed with bold style and TD used to display
the table data in normal font

<!—PROGRAM TO CREATE A TABLE WITH 2 COLUMNS AND 4 ROWS -->

<html>

<head>

<title> mstcs table</title></head>

<table border=5 bgcolor=Teal cellpadding=5 cellspacing=5>

<tr> <th>SNO<th>NAME </tr>

<tr> <td>1<td>ABC</TR>

<tr> <td>2<td>GSK</TR>

<tr> <td>3<td>XYZ</TR>

</body>

</table></html>

COLSPAN This is used to merge the selected number of columns in the given row. The
horizontal cell are combined together to give a merging display

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


32

ROWSPAN: The rowspan works in the same way as colspan. It combines multiple vertical
cells and displays the content in horizontal format

ALIGN: it aligns of the caption with respect to the table. It has values i.e. BOTTOM, TOP,
CENTER

<!—PROGRAM TO CREATE ROWSPAN, COLSPAN, ALIGN -->

<html>

<head>

<title> mstcs table</title></head>

<body>

<table border=5 bgcolor=Silver cellpadding=5 cellspacing=5 align="center">

<tr><th colspan=4>MSTCS-IIIyear </th></tr>

<tr><th rowspan=4>MSTCS</th></tr>

<tr> <td>1<td>ABC<td>Ist </TR>

<tr> <td>2<td>GSK<td>IInd</TR>

<tr> <td>3<td>XYZ<td>IIIrd</TR>

</body>

</table>

</html>

WRITE A SHORT NOTE ON FRAMES?

(OR)

EXPLAIN ABOUT FRAMES IN HTML? AND DISCUSS ADVANTAGES AND


DISADVANTAGES OF FRAMES?

(OR)

DEVELOP A HTML PAGE USING FRAMES TAG IN HTML?

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


33

Frames are an HTML feature introduced by Netscape communications they allow your
to divide the browser window into several independent parts. Frames in an HTML document
can cause a web page to appear to be divided into scrollable regions. Each frame can be
assigned a name, a source document locater, dimensions, border alignments and style
sheets etc.

The frame is a similarity with window frame. A group of frames in a single browser
window is called a frameset. The frameset tag <FRAMESET> and corresponding ending tag
</FRAMESET> are used for creating a set of frames. The frameset tag in an HTML
document replaces the body tag.

They are three types of properties 1) <frame> 2) <frameset> 3) <noframes>

1) The initial frameset defines a set of frames to create a webpage

2) The frame defines a sub window i.e. frame in each part

3) The noframes defines no frame section for browsers that do not handle frames.

Once the browser window is partitioned, you need to tell the browser what to load
into the different frames. This is using the frame tag <FRAME>.no ending tag is necessary
to the frame tag. For example there are two frames in which the browsers window is
vertically divided into two equally parts

<html>

<head>

<title> two vertical frames </title>

</title> </head>

<frame name=sri>

<frameset cols="50%, 50 %">

<frame src="5.HTML"NAME=TOP>

<frame src="6.HTML"NAME=BOTTOM>

</frameset>

</html>

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


34

The <cols> attribute of the frameset tag is used to specify that for creating columns,
where a column is vertically oriented frame. The cols attribute can take values as a
percentage of the browser’s window or you can specify the column width using fixed pixel
amount. You can use the wildcard symbol “*” to assign left over amount of space, and to
divide the browser’s window in two proportions.

The <ROW> attribute of the frameset tag is work like <COL> tag. But it divided the
window horizontally using <ROW>attribute. The row attribute can take the value as a
percentage of the browser window or user specify pixel amount. We can also use wild card
symbol “*”to assign left over space The example shows the row section

<html>

<head>

<title> two vertical frames </title>

</title> </head>

<frame name=sri>

<frameset rows="50%, 50%">

<frame src="5.HTML"NAME=TOP>

<frame src="6.HTML"NAME=BOTTOM>

</frameset>

</html>

<NOFRAMES>: We can also include the Noframes tag it also have a corresponding tag that
means end tag <noframes>……</noframes>.The browsers which are capable of displaying
frames will ignore the NOFRAME tag. Browsers not capable of displaying frames render the
information appearing between NOFRAMES tag and its ending tag.

The attributes of frame are

 NAME: Assigns a name to a frame. It is used to load the content from one to
another frame.

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


35

 FRAME SRC: it locates of the frame contents

 SCROLLING: It sets the frame should scroll or not 1) auto 2) yes 3) no

 FRAME BORDER: It set the border to page the values are 1 and no border

 MARGINWIDTH: It specifies the margins in pixels i.e. left or right

 MARGINHEIGHT: It specifies the margins in pixels i.e. Top or bottom

 NORESIZE: It specifies the frame in non-resizable

EXPLAIN ABOUT FORMS IN HTML?

(OR)

WHAT IS ROLE OF HTML FORMS IN HTML?

Forms are a mechanism that allow you to type information into fields on a browser
screen and submit the information to a web server. They allow your to create interactive
web pages. That is you can fill out a form, submit it and then the information is uploaded to
the designated serer to handle a form. A program on the server processes the information
and then returns a new HTML DOCUMENT.

Forms have may functions. They can be used for gathering information about a user,
survey, order online etc. submitting a query to a search engine and so on. In each case,
when the user submits a form, values are uploaded to the receiving server. If user filled out
the form correctly, the HTML document may a message the user to redo the form and
resubmit it.

FORM TAGS: Forms provide an interface for collecting, displaying, and delivering
information and are used as a key component of HTML. Forms have different types of fields
such as text input fields, radio buttons, checkboxes, submit and reset button etc.

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


36

Form is created by using <FORM>tag. it is also a paired tag. i.e. it have end tag. i.e.
<FORM>…..</FORM>. The most important property in the form is action and method

Syntax: <form action=”drive: path” method=”post/get”>

….Form fields…

….Form fields…

</form>

Example: <form action="demo_sri" method="get">

Name: <input type="text" name="pname" />

Address: <input type="text" name="paddress" />

</form>

FORM METHODS:

The "method" attribute establishes how the form's data will be sent to the processing
agent. There are two possible values for this attribute (case-insensitive)

1) get: The form's data is added to the URI defined in the action attribute

Ex: <form action=http://www.server.com/program method=”get”>

<input type= user choice>

</form>

2) post: The form's data is added to the body of the form.

Ex: <FORM ACTION="http://www.w3.org/sample" METHOD="POST” >


<input type=user choice>
</form>

FORM INPUT TAGS

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


37

The primary element of html forms which helps user to create various controls using
its type attributes. It is an independent tag which means it does not have closing tags. It
supports 13 form controls with different structure.

Each input element with in the form is sent to the server as name/value pairs.

The input types are

1) Text 2) Password 3) Checkbox 4) Radio

5) Reset 6) Submit 7) Button 8) file

9) Image 10) select 11) Text Area

Submit & reset buttons are Action buttons

TEXT BOX: A rectangular shaped field in which a user can enter text is considered as text
box. A text box is the type of input tag with name, size max length and values. Example

<HTML>

<HEAD>

<TITLE>XYZ</TITLE>

</HEAD>

<body>

<font face="verdana" color="Red">

<FORM>

NAME <INPUT TYPE ="TEXT" NAME="NAME"SIZE=45><br><br>

FNAME &nbsp<INPUT TYPE ="TEXT" NAME="NAME"SIZE=45>

</font>

</body>

</FORM>

</HTML>

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


38

PASSWORD: The password input type creates a single line empty text box where the user
can enter text into it. It is similar to text fields. It display the text in the fields like stars (*)
and dot (.) that means it creates masked fields in passwords.

<html>

<body>

<form action="">

Username: <input type="text" name="user"><br>

Password: <input type="password" name="password">

</form>

</body>

</html>

CHECKBOXES: A checkbox is represented by square icon. This is used for multiple


selections. The user can select or deselect by clicking on it. A selected check box is usually
show in dark grey, and unselected check box is shown in light grey. It often used in series.

<html>

<body>

<form action="">

<H3> COURSES OFFERED </H3>

<input type="checkbox" name="vehicle" value="Bike">BSC<br>

<input type="checkbox" name="vehicle" value="Car">BCOM<br>

<input type="checkbox" name="vehicle" value="Bike">BBM<br>

<input type="checkbox" name="vehicle" value="Car">BCA

</form>

</body>

</html>

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


39

RADIO BUTTONS: Radio buttons are a group of buttons from which only one can be
selected at a time.

Ex: <html>

<body>

<form action="">

<H4>GENDER</H4>

<input type="radio" name="sex" value="male">Male<br>

<input type="radio" name="sex" value="female">Female

</form>

</body>

</html>

ACTION BUTTONS: - They are two types actions buttons they are submit and reset. Where
the user clicks on the submit button, the values that have been entered into the form are
sent the program that process the form. where as reset button is to allow to clear all of the
input entered in the form and starts from the first.

Submit: <input type=”submit” value=”submit”>

Reset: <input type=”reset” value=”clear”>

Ex: <html>

<body>

<form action="demo_form.asp" method="get">

Name: <input type="text" name="name"><br>

Sname: <input type="text" name="sname"><br>

<button type="submit" value="Submit">Submit</button>

<button type="reset" value="Reset">Reset</button>

</form>

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


40

</body>

</html>

FILE: The file type of input tag provides a file upload form box for HTML forms. It allows to
solicit (request) files from the readers such as images or videos.

Ex: <html>

<body>

<form action="demo_form.asp" method=”get”>

<input type="file" name="textbox"><br><br><br>

<input type="submit">

</form>

</body>

</html>

SELECT: The select tag allow to choose any subset of items from a group, the items given
in select tag are usually rendered in the style of a pop-up menu. The items are indicated by
using <option> tag. Here in <option>tag the end tag is optional

<html>

<body>

<select>

<option value="MSTCS">MSTCS</option>

<option value="B.COM">B.COM</option>

<option value="MPCS">MPCS</option>

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


41

<option value="BBM">BBM</option>

</select>

</body>

</html>

TEXT AREA: The <text area> tag defines a multi-line text input control. A text area can
hold an unlimited number of characters, and with fixed-width font (i.e. courier) the area can
be specified by the cols and rows attributes.

Ex: <html>

<body>

<textarea rows="10" cols="30">

The Best way to predict your Future is to create it.

The good teacher explains. The superior teacher demonstrates. The great teacher
inspires.

</textarea>

</body>

</html>

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


42

\\ PROGRAM TO CREATE BIODATA USING FORM TAG

<html>

<body BGCOLOR="OLIVE">

<h1><CENTER> <FONT FACE=ARIAL COLOR=WHITE> BIO DATA </H1> </CENTER>

<form tag="Create Logon">

<fieldset>

<legend>Personal information:</legend>

Username : <input type="username" name="username" /><BR><BR>

Surname : <input type="surname" name="surname" /><BR><BR>

Date of Birth : <input type="date of birth" name="dob" /><BR><BR>

Password : <input type="password" name="pwd" /><BR><BR>

Gender &nbsp&nbsp<input type="radio" name="sex" value="male">Male

<input type="radio" name="sex" value="female">Female<br><BR>

Email : <input type="email" name="email" /><BR><BR>

Telephone: <input type="telephone" name="tel" /><BR><BR>

Food Items <input type="checkbox" name="op1" value="MILK"> Milk &nbsp

<input type="checkbox" name="op2" value="BUTTER"> Butter &nbsp

<input type="checkbox" name="op2" value="CHEESE"> Cheese<br><br>

Places<Select>

<option value="KKD">Kakinada</option>

<option value="HYD">Hyderabad</option>

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


43

<option value="TPTY">Tirupati </option>

<option value="CH">Chennai</option>
</select><br><br>

Comment<textarea name="comments" rows="7"


cols="30"></textarea><br>

Address : <input type="address" name="add"


/><BR><BR>

Post Code : <input type="postcode" name="ptc"


/><BR><BR>

<input type="submit" value="Submit" />

<input type="reset" value="Reset" />

</fieldset>

</form></body></html>

EXPLAIN THE HTML DOCUMENT HEADER IN DETIAL?

(OR)

WHAT SORT OF META INFORMATION CAN BE PLACED IN THE HEAD DOCUMENT


EXPLAIN?

The head is first section of any HTML page, it contains lots of control information that
is needed by browsers and servers. Many people do write the <title> tag in head section.
Information placed in this section is essential to the inner workings of the document the
information placed with in the <head>….</head> expect <title> tag is not displayed by the
browser.

They are several tags in html they are

 <BASE>: This tag is used to enforce relative links. Between pages and documents.
o Ex: <BASE HREF=”URL”>
 <BASEFONT>: This tag defines the font size to be used in the html document. The
attributes of this tag is (size, color, face)
o Ex: <BASEFONT SIZE=”4” COLOR=”BLUE” FACE=”ARIAL”>

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


44

 <BGSOUND>: This tag is used to play a sound track in the background. This tag is
for internet explorer document only.
o Ex: <BGSOUND SRC=”SRI.WAV”> </BGSOUND>
 <ISINDEX>: This tag is used for take simple and single line of text input.
 <LINK>: This tag is used to allow other documents to be linked to, or included in, in
the document
o Ex: <LINK REL=”TYPE” HREF=”URL” TYPE=”STRING” MEDIA=”STRING”>
 <META>: This tag is used to describes the whole document should be included
using one of alternatives
o Ex: <META NAME=”STRING” CONTENT=”STRING”>

 <NOSCRIPT>: This tag is used to hold text that only appears if the browser does
not support the script tag.

 <SCRIPT>: This tag is used to holds programming scripts statements like Java
script, VBscript.

 TITLE> The webpage title which appear in the title bar of the web browser

JAVA SCRIPT
EXPLAIN ABOUT SCRIPTING?
Script is the abbreviation for “SCOTTISH CENTRE FOR RESEARCH IN INTELLECTUAL
PROPERTY TECHNOLOGIES.
Any program run by web server in response to the user’s request is termed as script.
Scripting languages are the basis o the CGI-BIN( common gate way programming.
Webpages are two types 1) server side script 2) client side script
languages. In that the most popular is client side script i.e. JavaScript

WHAT IS JAVA SCRIPT? AND EXPLAIN THE BENEFITS OF JAVASCRIPT?


The original name for java script is live script. Java script was originally created by
NETSCAPE. Microsoft version of the JavaScript is called Jscript by the (ECMA European
Computer Manufacturers Association). After that Microsoft and Netscape have been involved

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


45

in the standardization of JavaScript to (ISO). INTERNATIONAL ORGANIZATION FOR


STANDARDS.
JavaScript is an lightweight, interpreted programming language with object oriented
capabilities.
It is designed for creating network based applications
It is open and cross-platforms
It is directly embedded directly into HTML pages

BENEFITS OF JAVASCRIPT:
1) It is widely supported by web browsers
2) It gives easy access to the document objects and can manipulate most of them.
3) We can create animations with out the long downloading
4) It is relatively secure, JavaScript can neither read from your local hard drive nor write
to it,
5) It can’t get a infected by virus directly to JavaScript.
6) It allow page effects to create
1) User’s time on page 2) Popups and tool tips 3) page timeout
4) Color changes 5) font sizing 6) embedded audio
7) Scrolling banners 8) Toggle buttons 9) Image transitions
10) Automated popup

7) JavaScript will add user interactivity, because we add special effects to the webpage so
that it will make more interactive.

8) JavaScript will provide seamless integration with user plug-ins (JavaScript not only
provides access to HTML objects, it also gives access to browser and platform-specific
objects like browser plug-ins (e.g. Adobe Acrobat, Media Player).

9) JavaScript will allow client-side user form validation (to check for simple errors such as
missing information)

10) JavaScript will allow access to some system information

EXPLAIN THE ADVANTAGES OF JAVASCRIPT?

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


46

 An interpreted language: it is an interpreted language, which requires no


compilation steps. The syntax is completely interpreted by the browser

 Embedded within html: it does not require any special editor for written programs,

just it required text editor like notepad and saved as filename.html

 JavaScript give HTML designers a programming tool: The HTML programmers

are normally not programmers, but the script is very simple syntax any one write

code into their HTML pages

 JavaScript can react to events: It can be set to execute, when things happens,

like user clicks, loading finished etc on an html element

 JavaScript can read and write HTML elements: it can read and change the

content of html elements

 JavaScript Can be used to Validate Data: it can be used to validate from data

before it is submitted to a server. It saves extra time for processing.

 JavaScript can be used to create cookies: JavaScript can be used to store and

retrieve information on the visitors computers

EXPLAIN THE STRUCTURE OF A JAVASCRIPT PROGRAM? & EXPLAIN HOW IT IS


INCLUDE IN HTML DOCUMENT?

The general structure of JavaScript is

<script language=”JavaScript”>

…..// JavaScript code

</script>

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


47

JavaScript is traditionally embedded into a standard html program. It embedded between


<SCRIPT>…..</SCRIPT>. These tags are embedded in <body>…</body> or
<head>…</head> tags

The script attributes are

Language: scripting language name

Type: Internet content for a scripting language

Src: Url for an external linked script

Rules: The key points are to follow when a writing a scripts programs

1) Each line of code is terminated by a semicolon (;).


2) Blocks of code must be surrounded by a pair of curly braces {…}.
3) A block of code is set of instructions that are to be executed together as a unit.
4) JavaScript is case sensitive
5) Variables are declared by using the Keyword var.
6) Functions have parameters, which are passed inside parenthesis.
7) Scripts require neither a main function nor an exit condition
8) Execution of a script starts from the first line of code and runs to till end.
9) JavaScript has two form of comments i.e. (//) , ( “/*………*/”)
10) // : for single line comment ex: //gsk
/*…*/ : for multiple line of comment ex: /* gsk

Sk */

Including java script: After writing the script we need to include in an html page.
Script can be executed with an interpreter it is part of a browser. The browser also
debug the script and display errors if any.

We can include the java script into two ways.

1) Directly include in <HTML> tags. If script is minimal


Ex: <html>

<head>

<script language=”java script”>

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


48

Code to JavaScript </script> </head>

<body> ..................... </body> </html>

2) External i.e. we can create the script in separate file & save it (filename.js) and
then create HTML file and include in the file by using “src” element i.e. <script
language=”JavaScript” src=”filename.js”>
Ex: <html>

<head>

<script language=”JavaScript” src=”gsk.js”> </head>

<body>

……</body></html>

WHERE U CAN PLACE THE JAVA SCRIPT IN HTML?

1) IN HEAD SECTON
2) IN BODY SECTION
3) IN BOTH HEAD AND BODY SECTION
4) IN EXTERNAL FILE

WHAT DATA TYPES ARE USED IN JAVASCRIPT? EXPLAIN?

(OR)

GENERAL PROGRAMMING LANGUAGES SUPPORTS THE FOLLOWING DATA


TYPES, CHARACTERS, INTEGERS, BOOLEAN, STRINGS, AND NULL?

JavaScript uses four data types

1) NUMBERS 2) STRINGS 3) BOOLEAN 4) NULL

NUMBER (OR) NUMERIC DATATYPE: These are basic numbers. It is possible to


express both integers and floating point values.

Ex: var g1= 30;

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


49

var gsk=14.25;

STRINGS: These are collections of characters. Generally string is enclosed with in


double quotes. The value of a string can contain spaces & can be totalled made by
digits.

Ex: “gsk”, “srikanth”

BOOLEAN: it holds the values of “TRUE/ FALSE”. These are used to hold the results of
conditional tests.

Ex: var g=T/F

NULL: In JavaScript the null represents nothing the null value in JavaScript term as null.
It doesn’t mean NIL or ZERO

Ex: var emp_no=null;

Var age=null;

DEFINE VARIABLE? EXPLAIN IT SCOPE?

A variable is a data item that can be manipulated at any time. In javascript the
variable are same as the other programming languages. Variables are used to hold data
in memory.

Variables are declared by using “var” keyword followed by variable name

 Variables are divided into two types


1) Global variable 2) Local variables
Global variable: it is defined every where in you JavaScript code.
Local variable: It can be defined only with in function where it is defined. Function
parameters are always local to that function.

Declaring a variable name:


1) JavaScript variable must start with a letter or underscore(_) but not numerals.
2) Spaces can’t be used in variable names.
3) A underscore can be used as separator in case of multiple words
4) JavaScript variable are case sensitive.

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


50

5) Reserved words are not used as variable name.

WRITE A SAMPLE PROGRAM TO CREATE JAVA SCRIPT.


<html>
<head>
<title>Javascript</title>
</head>
<body>
<script type="text/javascript">
document.write("Hello gsk!");
</script>
</body>
</html>

WHAT ARE THE OPERATORS IN JAVA SCRIPT? GIVE EXAMPLES


(OR)
EXPLIAN THE OPERATORS AVAILABLE IN JAVA SCRIPT?

The javascript operators are


1) Arithmetic operators 2) Comparison operators
3) Logical operators 4) Assignment operators
5) Conditional operators 6) The + operator used on Strings

Arithmetic Operators: These operators takes numerical values as their operands and
return a value. The operators are
OPERATOR DESCRIPTION EXAMPLE
+ Addition (add two operands) A+b=c; 10+20=30
- Subtraction (subtract second operand from the first a-b=c 10-20=-10
* Multiplication (multiply both operands) a*b=c 5*2=20
/ Division (divide the first number by the number b/a=c 4/2=2
% Remainder ( divides left by right and leave remainder b%a=c 3%2=1
++ Increment operator ( increases the integer value) A++ 10++=11
-- Decrement operator (decreases the integer value) A—10--=9
COMPARISON OPERATORS: A comparison operator compares the operands and returns the
value based on the condition whether it is true or not .
EXAMP
OPERATOR DESCRIPTION
LE
== Returns true if the operands are equal (A==b)
!= Returns true if the two operands are not equal (a!=b)
> Greater than ( returns true if the left operand is greater than the right (a>b)

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


51

>= Returns true if the left operand is greater than or equal to the right one (a>=b)
< Returns true if the left operand is less than right (a<b)
<= Returns true if the left operand is less than or equal to the right one (a<=b)

LOGICAL OPERATORS
These operators used with Boolean values. They return a Boolean value.
OPERATOR DESCRIPTION EXAMPLE
&& AND operator. if both operands are non zero then become true (a&&b)
|| OR operator. If any of the two operands are non zero it become true (a||b)
! Logical Not returns false if operand value evaluates true !(a&&b)
ASSIGNMENT OPERATORS:
These operators are to assign a value to a variable or constant or expression assigned for
given variable.
OPERATOR DESCRIPTION EXAMPLE
= Assigns the value of the right operand to the left operand c=a+b
+= Adds together the operands and assigns the result to the left c+=a /c=c+a
Subtract the right from the left operand and assigns the result to
-= c-=a / c=c-a
the left
*= Multiplies the operands and assigns the result to the left C*=a / c=c*a
/= Divides the left by the right operand and assigns the result to left c/=a / c=c/a
Divides the left by the right operand and assigns the remainder to
%= C%=a / c=c%a
left

CONDITIONAL OPERATOR (? :)
It used for comparing two expressions also contains a conditional operator that
assigns a value to a variable based on some condition

Operator Description Example

?: Conditional Expression If Condition is true ? Then value X : Otherwise value Y

THE + OPERATOR USED ON STRINGS: The + operator can also be used to add string
variable or text values together. To add two or more string variables together, use the
operator.
SYNTAX: TXT1=”WHAT A VERY”; TXT2=”NICEDAY”;;

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


52

EXAMPLE: TXT3=TXT1+TXT2;

WHAT ARE THE CONTROL STATEMENTS IN JAVASCRIPT? EXPLAIN WITH EXAMPLE?


JavaScript supports conditional statements which are used to perform different actions
based on different conditions

CONDITIONAL STATEMENTS:

JavaScript supports following forms of statement:

1) if statement 2) if...else if... statement


2) if...else statement 4) Switch statement

IF STATEMENT: The if statement is the fundamental control statement that allows


JavaScript to make decisions and execute statements conditionally.

Syntax: if (expression) {
Statement(s) to be executed if expression is true

EXAMPLE <script type="text/javascript">


var age = 20;
if( age > 18 ){
document.write("<b>ALL THE BEST</b>");
}
</script> }

Here JavaScript expression is evaluated. If the resulting value is true, given statement(s)
are executed. If expression is false then no statement would be not executed.

IF...ELSE STATEMENT: The if...else statement is the next form of control statement that
allows JavaScript to execute statements in more controlled way.

Syntax: if (expression){
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


53

Here JavaScript expression is evaluated. If the resulting value is true, given statement(s) in
the if block, are executed. If expression is false then given statement(s) in the else block,
are executed.

EXAMPLE: <script type="text/javascript">


var age = 15;
if( age > 18 ){
document.write("<b>Qualifies for EXAM</b>");
}else{
document.write("<b>Does not qualify for EXAM</b>");
} </script>

IF...ELSE IF... STATEMENT:

The if...else if... statement is the one level advance form of control statement that allows
JavaScript to make correct decision out of several conditions.

Syntax: if (expression 1){


Statement(s) to be executed if expression 1 is true
}else if (expression 2){
Statement(s) to be executed if expression 2 is true
}else if (expression 3){
Statement(s) to be executed if expression 3 is true
}else{
Statement(s) to be executed if no expression is true
}

It is just a series of if statements, where each if is part of the else clause of the previous
statement. Statement(s) are executed based on the true condition, if non of the condition is
true then else block is executed.

EXAMPLE:
<script type="text/javascript">
var book = "COMPUTERS";
if( book == "MATHS" ){
document.write("<b>MATHS Book</b>");
}else if( book == "COMPUTERS" ){
document.write("<b>COMPUTERS Book</b>");
}else if( book == "economics" ){
document.write("<b>STATISTICS Book</b>");
}else{

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


54

document.write("<b>Unknown Book</b>");
}
</script>
SWITCH STATEMENT: switch statement is to give an expression to evaluate and several
different statements to execute based on the value of the expression. The interpreter
checks each case against the value of the expression until a match is found. If nothing
matches, a default condition will be used.

SYNTAX
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
The break statements indicate to the interpreter the end of that particular case. If they were
omitted, the interpreter would continue executing each statement in each of the following
cases.

EXAMPLE

<script type="text/javascript">
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
case 'A': document.write("A+GRADE<br />");
break;
case 'B': document.write("A GRADE<br />");
break;
case 'C': document.write("B GRADE<br />");
break;
case 'D': document.write("C GRADE<br />");
break;
case 'F': document.write("D GRADE<br />");

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


55

break;
default: document.write("FAIL<br />")
}
document.write("Exiting switch block");
</script>
LOOPING STATEMENTS:
Loops execute a block of code, a specified number of times, or while a specified
condition is true.
In java script, there are three different kind of loop
1) for 2) while 3) do while

FOR LOOP:
For loop is the most compact form of looping and includes the following three important
parts:
1) The loop initialization
2) The test statement which will test if the given condition is true or not
3) The iteration statement where you can increase or decrease your counter
Syntax:

for (initialization; test condition; iteration statement)

Statement(s) to be executed if test condition is true

EXAMPLE:

<script type="text/javascript">

var I;

document.write("Starting Loop" + "<br />");

for(I= 0; I < 10; I++)

document.write("Current Count : " + I);

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


56

document.write("<br />");

document.write("Loop stopped!");

</script>

WHILE LOOP: The most basic loop in JavaScript is the while loop.

Syntax:

while (expression)

Statement(s) to be executed if expression is true

The purpose of a while loop is to execute a statement or code block repeatedly as long as
expression is true. Once expression becomes false, the loop will be exited.

EXAMPLE:

<script type="text/javascript">

var SRIK= 0;

document.write("Starting Loop" + "<br />");

while (SRIK< 10) {

document.write("Current Count : " + SRIK+ "<br />");

SRIK++;

document.write("Loop stopped!");

</script>

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


57

DO...WHILE LOOP:

The do...while loop is similar to the while loop except that the condition check happens at
the end of the loop. This means that the loop will always be executed at least once, even if
the condition is false.

Syntax:

do{

Statement(s) to be executed;

while (expression);

Example:

<script type="text/javascript">

var GSK = 0;

document.write("Starting Loop" + "<br />");

do{

document.write("Current Count : " + GSK + "<br />");

GSK++;

}while (GSK < 0);

document.write("Loop stopped!");

</script>

BREAK STATEMENT:

The break statement will break the loop and continue executing the code that follows
after the loop if any.

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


58

Example

<script type="text/javascript">

var gn= 1;

document.write("Entering the loop<br /> ");

while (gn < 20)

if (gn == 5){

break; // breaks out of loop completely

gn = gn+ 1;

document.write( gn+ "<br />");

document.write("Exiting the loop!<br /> ");

</script>

CONTINUE STATEMENT:

The continue statement tells the interpreter to immediately start the next iteration of the
loop and skip remaining code block.

When a continue statement is encountered, program flow will move to the loop check
expression immediately and if condition remain true then it start next iteration otherwise
control comes out of the loop.

EXAMPLE:

<script type="text/javascript">

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


59

var GS = 1;

document.write("Entering the loop<br /> ");

while (GS < 10)

GS =GS + 1;

if (GS == 5){

continue; // skill rest of the loop body

document.write( GS + "<br />");

document.write("Exiting the loop!<br /> ");

</script>

WRITE A PROGRAM TO PRINT NATURAL NUMBER UPTO GIVEN NUMBER IN


JAVASCRIPT?

<html

<body>

<script type="text/javascript">

var i;

for(i=0; i<100; i++)

document.write(+i);

document.write("<br>");

</script>

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


60

</body>

</html>

WRITE A PROGRAM TO PRINT FACTORIAL OF GIVEN NUMBER IN JAVA SCRIPT?

<html>

<body>

<script type = "text/javascript">

var n = parseInt(window.prompt("Enter the Number:"));

var result = fact(n);

function fact(n)

if(n == 0)

return 1;

else

return (n*fact(n-1));

document.write("Factorial of the given number " + result);

</script>

</body>

</html>

WRITE A PROGRAM TO PRINT FIBONACCI SERIES IN JAVASCRIPT?

<html>

<body>

<script type="text/javascript">

var a=0,b=1,c;

document.write("Fibonacci");

while (b<=13)

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


61

document.write(c);

document.write("<br/>");

c=a+b;

a=b;

b=c;

</script>

</body>

</html>

ARRAYS

WHAT IS AN ARRAY? EXPLAIN HOW TO CREATE AN ARRAY AND HOW TO ADD AN


ACCESS ELEMENT?

(OR)

HOW DO I CREATE AN ARRAY IN JAVASCRIPT AND EXPLAIN ITS FUNCTIONS?

(OR)

DEFINE ARRAY? EXPLAIN THE BASIC FUNCTIONS OF ARRAY?

JavaScript arrays are used to store multiple values in a single variable.

Creating Arrays: Array can be constructed three ways.

1) The first way to declare array is to declare a variable and pass it some elements.

Ex: var days= [“Monday”, “Tuesday”, “Wednesday”];

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


62

It creates an array three elements, each holding a text string. In this type of array
the elements will surrounded by square brackets.

2) The second way to declare an array is to create array object using the keyword “new”
and a set of elements

Ex: var days= new Array(“Monday”,”Tuesday”,”Wednesday”);

Using this construct, the contents of the array is surrounded by small braces.
Because they are parameters to the constructor of the array object

3) The Third way to declare an empty array object which has space for a number of
elements can be created.
Ex: var days = new Array(4);

ADDING ELEMENTS TO AN ARRAY: Array elements are accessed by their index. The
index is denotes the position of the element in the array and, as in for loops. These are
starting from “0”

Ex: var days[3]=”Monday”;

We can’t new item now because it is already full many languages faced this problem
can’t solve it. But JavaScript has a good option because the interpreter simply extends
the array and inserts the new item.

1. var data = [“Monday”,”Tuesday”, 85, 01, 00, 12, 12, “gsk”];


2. data[5] = “mstcshai”;
3. data[23] = 48;

ACCESSING ARRAY MEMBERS: The elements in the array are accessed through their
index the same access method is used to find elements and to change their value.

HOW TO REMOVE THE ELEMENTS FROM THE ARRAY?

(OR)

HOW TO REMOVING ARRAY MEMBERS

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


63

REMOVING ARRAY MEMBERS: Removing elements from an array is direct method.


JavaScript doesn’t provide a built-in function to do this for you.

 Read each element in the array.


 If the element is not the one you want to delete, copy it into a temporary array.
 If you want to delete the element then do nothing
 Increment the loop counter.
 Repeat the process

EXPLAIN THE OBJECT BASED ARRAYS FUNCTIONS IN JAVASCRIPT?

The object based arrays functions are

CONCAT: The concat() method is used to join two or more arrays.This method does not
change the existing arrays, but returns a new array, containing the values of the joined
arrays.

SYNTAX: array1.concat(array2, array3,..., arrayX)

EXAMPLE: var h = ["s", "r"]; var s = ["i", "k", "a"]; var n = h.concat(s);

document.write(n);

WRITE A PROGRAM TO DISPLAY THE OBJECT BASED CONCAT FUNCTION IN


JAVASCRIPT?

<!DOCTYPE html>

<html>

<body><script>

var h = ["s", "r"];

var s = ["i", "k", "a"]; OUTPUT: s,r,i,k,a

var n = h.concat(s);

document.write(n);

</script></body></html>

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


64

JOIN (STRING): The join() method joins the elements of an array into a string, and
returns the string. The elements will be separated by a specified separator. The default
separator is comma (,).

SYNTAX: array.join(separator);

EXAMPLE: var fruits = ["Banana", "Orange", "Apple", "Mango"];

var energy = fruits.join(" and ");

POP(): The pop() method removes the last element of an array, and returns that element.

SYNTAX: array.pop()

EXAMPLE: var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.pop();

PUSH(): The push() method adds new items to the end of an array, and returns the new
length. The new item(s) will be added at the end of the array.

SYNTAX: array.push(item1, item2, ..., itemX)

EXAMPLE: var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.push("Kiwi");

REVERSE():The reverse() method reverses the order of the elements in an array.

SYNTAX: array.reverse()

EXAMPLE: var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.reverse();

SHIFT():The shift() method removes the first item of an array, and returns that item.This
method changes the length of an array.

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


65

SYNTAX: array.shift();

EXAMPLE: var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.shift();

SLICE(): The slice() method returns the selected elements in an array, as a new array
object. The slice() method selects the elements starting at the given start argument, and
ends at, but does not include, the given end argument.

SYNTAX: array.slice(start,end);

EXAMPLE: var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];

var citrus = fruits.slice(1, 3);

SORT():The sort() method sorts the items of an array.The sort order can be either
alphabetic or numeric, and either ascending or descending.

SYNTAX: array.sort(sortfunction);

EXAMPLE: var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.sort();

UNSHIFT(): The unshift() method adds new items to the beginning of an array, and
returns the new length.

SYNTAX: array.unshift(item1,item2, ..., itemX);

EXAMPLE: var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.unshift("Lemon","Pineapple");

WRITE A PROGRAM TO PRINT POP() METHOD IN JAVASCRITPT?

<html>

<head>

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


66

<title>JavaScript Array pop Method</title>

</head>

<body>

<script type="text/javascript">

var numbers = [1, 4, 9];

var element = numbers.pop();

document.write("element is : " + element );

var element = numbers.pop();

document.write("<br />element is : " + element );

</script>

</body>

</html>

EXPLIAN DIALOG BOXES OR (POPUP BOXES) (WINDOW OBJECTS)?

JavaScript supports three important types of dialog boxes. These dialog boxes can be
used to raise and alert, or to get confirmation on any input or to have a kind of input from
the users.
1) Alert box 2) Confirm box 3) Prompt box
ALERT BOX: An alert dialog box is mostly used to give a warning message to the users.
Like if one input field requires to enter some text but user does not enter that field then as
a part of validation you can use alert box to give warning message
Syntax: alert(“textmessage”);
Example: alert(“Welcome to Mstcs”);

WRITE A PROGRAM TO DISPLAY ALERT BOX IN JAVASCRIPT?

<HTML>
<head>
<script type="text/javascript">
alert("Warning Message");

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


67

</script>
</head>
</HTML>

CONFIRM B0XA confirm box is often used if you want the user to verify or accept
something. When a confirm box pops up, the user will have to click either "OK" or "Cancel"
to proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns
false.
Syntax: confirm(“TEXT MESSAGE);
Ex: confirm (“har”);
WRITE A PROGRAM TO DISPLAY PROMPT BOX IN JAVASCRIPT
<!DOCTYPE html>
<html>
<body>
<script language="javascript">
var x=confirm ("if u work hard");
if(x)
alert("u will get good marks");
else
alert("will get less marks");
</script>
</body> </html>
PROMPT BOX: A prompt box is often used if you want the user to input a value before
entering a page. When a prompt box pops up, the user will have to click either "OK" or
"Cancel" to proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the
box returns null.
Syntax: prompt (“text message”,default_value”);

Ex: prompt (“enter a name”, “gsk”);

WRITE A PROGRAM TO DISPLAY PROMPT BOX?

<HTML>

<body>

<script type="text/javascript">

var mstcs = prompt("Enter your name : ", "your name here");

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


68

alert("You have entered : " + mstcs );

</script>

</body>

</HTML>

WHAT ARE THE STRING MANIPULATION COMMANDS USED IN JAVA SCRIPT?

(OR)

WHAT IS STRING OBJECT? WRITE ALL METHODS OF STRING OBJECT?

(OR)

EXPLAIN “STRING” OBJECT METHODS IN DETAIL?

(OR)

EXPLAIN STRING MANIPULATION IN JAVASCRIPT?

JavaScript simply stores a series of characters. A string can be any text inside
quotes. You can use single or double quotes.

String manipulation can be done joining of strings, splitting of strings and search
through strings. In order to perform these manipulations functions JavaScript has used
following functions.

1) charAt(index) 2) concat() 3) indexOf() 4) lastIndexOf()

5) split() 6) substr() 7) Substring() 8)toLowerCase()

9) toUpperCase() 10) valueOf()

charAt(): This function returns the character at the specified index. Characters in a string
are indexed from left to right. First character is 0 last character in string called string name
-1 .

Syntax: string.charAt(index); Ex: var str = "HELLO WORLD";

var res = str.charAt(0)

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


69

WRITE A PROGRAM TO DISPLAY charAt() FUNCTION IN JAVASCRIPT?

<html>

<body>

<script language ="javascript">

var str = "HELLOWORLD";

document.writeln(str.charAt(5));

</script>

</body>

</html>

concat(): In JavaScript the concat function is used for combines the text of two strings
and returns a new string.

Syntax: string.concat(string1,string2,…stringx);

Ex: var str1 = "Hello ";

var str2 = "world!";

var res = str1.concat(str2);

WRITE A PROGRAM TO DISPLAY CONCAT() FUNCTION IN JAVASCRIPT?

<html>

<body>

<script language ="javascript">

var str = "HELLOWORLD";

var str1 = "gsk";

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


70

document.writeln(str.concat(str1));

</script>

</body>

</html>

INDEXOF(): Searches and (if found) returns the index number of the searched character or
substring within the string. If not found, -1 is returned. “Start” is an optional argument
specifying the position within string to begin the search. Default is 0.

Syntax: string.indexOf(searchvalue,start)

Example: var str = "Hello world, welcome to the universe.";

var n = str.indexOf("welcome");

LASTINDEXOF(): It returns the index within the calling string object of the first occurrence
of the specified value or -1 if not found.

SYNTAX: string.lastIndexOf(searchvalue,start)

Example: var myString = 'javascript rock';

document.write(myString.lastIndexOf('k'));

WRITE A PROGRAM TO DISPLAY lastIndexOf FUNCTION IN JAVASCRIPT?

<!DOCTYPE html>

<html>

<body>

<script language ="javascript">

var myString = 'javascript rock';

document.write(myString.lastIndexOf('k'));

</script>

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


71

</body>

</html>

SPLIT():The split() method is used to split a string object into an array of strings by
separating the string into substrings.

SYNTAX: string.split(separator,limit)

EXAMPLE: var str = "How are you doing today?";

var res = str.split(" ");

WRITE A PROGRAM TO DISPLAY split() FUNCTION IN JAVASCRIPT?

<!DOCTYPE html>

<html>

<body>

<script language ="javascript">

var str = "How are you doing today?";

var res = str.split(" ");

document.write(res);

</script>

</body>

</html>

SUBSTR(); :it returns the characters in a string beginning at the specified location through
the specified number of characters.

SYNTAX: string.substr(start,length)

EXAMPLE: var str = "HAI MSTCS!"; var res = str.substr(1, 4);

WRITE A PROGRAM TO DISPLAY SUBSTR() FUNCTION IN JAVASCRIPT?

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


72

<!DOCTYPE html>

<html>

<body>

<script language ="javascript">

var str = "HAI MSTCS!";

var res = str.substr(1, 4);

document.write(res);

</script> output : AIM

</body>

</html>

SUBSTRING():

The substring() method extracts the characters from a string, between two specified
indices, and returns the new sub string.

This method extracts the characters in a string between "start" and "end", not
including "end" itself.

SYNTAX: string.substring(start,end)

EXAMPLE: var str = "MSTCS world!";

var res = str.substring(1, 4);

WRITE A PROGRAM TO DISPLAY SUBSTRING() FUNCTION IN JAVASCRIPT?

<!DOCTYPE html>

<html>

<body>

<script language ="javascript">

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


73

var str = "MSTCS world!";

var res = str.substring(1, 4);

document.write(res);

</script>

</body>

</html>

TOLOWERCASE():The toLowerCase() method converts a string to lowercase letters.

SYNTAX: string.toLowerCase()

EXAMPLE: var str = "Hello MSTCS!";

var res = str.toLowerCase();

WRITE A PROGRAM TO DISPLAY TOLOWERCASE FUNCTION IN JAVASCRIPT?

<!DOCTYPE html>

<html>

<body>

<script language ="javascript">

var str = "Hello MSTCS!";

var res = str.toLowerCase();

document.write(res);

</script>

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


74

</body>

</html>

TO UPPERCASE():The toUpperCase() method converts a string to uppercase letters.

SYNTAX: string.toUpperCase()

EXAMPLE: var str = "Hello MSTCS!"; var res = str.toUpperCase();

WRITE A PROGRAM TO DISPLAY TOUPPERCASE FUNCTION IN JAVASCRIPT?

<!DOCTYPE html>

<html>

<body>

<script language ="javascript">

var str = "Hello MSTCS!";

var res = str.toUpperCase();

document.write(res);

</script>

</body>

</html>

VALUEOF():The valueOf() method returns the primitive value of a boolean.

SYNTAX: boolean.valueOf()

EXAMPLE: var bool = false; var x = bool.valueOf()

WRITE A PROGRAM TO DISPLAY BOOLEAN FUNCTION IN JAVASCRIPT?

<!DOCTYPE html>
<html> <body>

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


75

<script language ="javascript">


{
var bool = false;
var x = bool.valueOf()
document.write(x);
} </script>
</body>
</html>

EXPLAIN MATHEMATICAL FUNCTION IN JAVA SCRIPT?


(OR)
DISCUSS MATH LIBRARY IN JAVASCRIPT?

The math object provides properties and methods for mathematical constants and functions.
Unlike the global objects. math is not a constructor. Mathematical functions and values are
part of built in JavaScript object called Math. All functions and attributes used in
mathematics must be accessed through this object only as

Math.function name () or Math.attribute where “M” should be capital letter

SYNTAX: Var x = Math.PI; // Returns PI (approx. 3.14)


var y = Math.sqrt(16); // Returns the square root of 16

MATH METHODS
1) abs(value): Returns the absolute value of a number.
2) acos(value): Returns the arccosine (in radians) of a number.
3) asin(value): Retuns the arctangent ( in radians) of a number.
4) atan(value): Returns the arctangent (in radians) of a number.
5) Atan2(value1,value2): Returns the arctangent of the quotient of its
arguments.
6) ceil(value): Returns the smallest integer greater than or equal to a number.
7) cos(value):returns the cosine of a number.
8) sin(value) :Returns the sine of a number.
9) Tan(value): Returns the tangent of a number.
10) Log(value): Returns the natural logarithm of a number.
11) Max(val1,val2): Returns the biggest of the two values passed in
12) Min(val1,va2):Returns the smallest of zero or more numbers.
13) Pow(value power): Returns base to the exponent power, that is, base
exponent.

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


76

14) Random(value): Returns a pseudo-random number between 9 and 1.


15) Round(value): returns the value of a number rounded to the nearest
integer.
16) Sqrt(value): returns the square root of the value.

WRITE A PROGRAM TO PERFORM MATH METHODS IN JAVASCRIPT?


<!DOCTYPE html>
<html>
<head>
<title>math</title>
</head>
<body>
<h3 align=center> math objects </h3>
<script language ="javascript">
{
var value = Math.abs(-8.598);
document.write("<br>first value:"+value);

var value = Math.acos(0.1);


document.write("<br> second
value:"+value);

var value =Math.ceil(45.20);


document.write("<br> third value:"+value);

var value=Math.floor(10.23);
document.write("<br> fouth value:"+value);

var value=Math.round(0.5);
document.write("<br> fifth value:"+value);

var value=Math.acos(-1);
document.write("<br> sixth value:"+value);

var value=Math.asin(-1);
document.write("<br> seventh value:"+value);

var value=Math.log(3);
document.write("<br> eight value:"+value);

var value=Math.max(1,5);
document.write("<br> ninth value:"+value);

var value=Math.min(1,9);
document.write("<br> tenth value:"+value);

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


77

var value=Math.sqrt(2);
document.write("<br> elevnth value:"+value);

var value=Math.exp(3)
document.write("<br> twelth value:"+value);

}
</script>
</body>
</html>

EXPLAIN ABOUT VARIOUS BULIT IN OBJECTS IN JAVASCRIPT? (1/10/14)

Most of the objects that you will use in your scripting will be pre built ones that came
with the browser.

1) The document object 2) The Window object

3) The form Object 4) The Browser object

5) The date Object

The document object: A document is a webpage that is being either displayed or created
the document has a number of properties that can be accessed by JavaScript programs and
used to manipulate the content of the page.

JavaScript document object provides the access of the entire webpage. That includes the
<head>section and <body>definition and various objects with in the page, such as links
and forms and anchors.

Syntax: document. propertyName (or) document.methodName(parameters)

These are the properties and methods of document objects

. write(“string”) . writeln(“string”) . bgcolor


. fgcolor . anchors . links

. layers . close()

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


78

The Window object: The browser window is a mutable(changeable) object that can be
addressed by javascript code. Some of the properties and methods that are available from
window objects.

. open (“url , name”) . close() . toolbar=[1/0]

. location = [1/0] . directories=[1/0] . status=[1/0]

. menubar=[1/0] . scrollbars=[1/0] . resizable=[1/0]

. width=pixels . height=pixels

The Form object: Two aspects of the form can be manipulated through javascript. First the
data is entered onto your form can be checked at submission. Second you an actually build
forms through javascript

. onclick = “method”

. onSubmit = “method”

. onReset = “method”

The browser object: The browser is a JavaScript object can be queried from within your
code. For historical reasons the browser object is actually called the navigator object. The
following are the properties

. navigator .appCodeName . navigator .appName

. navigator .appVersion . navigator .appuserAgent

. navigator .appplugins . navigator .appmimetypes

The Date object: JavaScript includes a well developed date class which provides functions
to perform many different date manipulations. In java script data and time represent the
number of milliseconds since 1 st January 1970 UTC. It has two separate notions i.e. UTC
and LOCAL

UTC: UNIVERSAL TIME also know as Greenwich Mean Time which is the standard time
throughout the world

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


79

LOCAL: it is the time on the machine which is executing the script

. Date() . Date(milliseconds)

. Date(string) . Date(year,month,day[,hour,minute,second])

. Parse(string)

EXPLAIN ABOUT DOCUMENT OBJECT WITH PROPERTIES AND METHODS WITH AN


EXAMPLE?

The document object: A document is a webpage that is being either displayed or


created the document has a number of properties that can be accessed by JavaScript
programs and used to manipulate the content of the page.

JavaScript document object provides the access of the entire webpage. That includes the
<head>section and <body>definition and various objects with in the page, such as links
and forms and anchors.

Syntax: document. propertyName (or) document.methodName(parameters)

These are the properties and methods of document objects

PROPERTY DESCRIPTION

bgcolor It is used to set / get the background color attribute of body tag

fgcolor It is used to set / get the foreground color attribute of body tag

forms It is used to get an array of all the form objects in the document page

links It is used to get an array of all the link objects in the document or webpage

url It us used to get the url string of current page or document

linkColor It is used to set / get value of link attribute of body tag

vlinkColor It is used to get/set the “visited link” color attribute of body tag

Title It is used to set / get the tile of the document using JavaScript

Cookie It is used to identify the value of a cookie

Image It is the object reference of an image object contained in the document

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


80

anchor It is the object reference of an anchor contained in the document

Methods: The methods are surrounding a parameter “[]” but the parameters are optional.

METHODS DESCRIPTION

close() Closes a document stream opened using document.open()

write(“string”) Writes to the document or document stream the “string” entered

writeln(“string”) Wrties to the document or document stream the “string” entered and
inserts a new line character at the end.

WRITE A PROGRAM TO DEMONSTRATE DOCUMENTS OBJECTS IN JAVASCRIPT?

<!DOCTYPE html>

<html>

<title>javascript</title>

<body>

<script>

document.bgColor = "green";

document.fgColor="yellow";

document.write("document.bgColor = "+document.bgColor+"<br>");

document.write("document.fgColor = "+document.fgColor+"<br>");

document.write("document.title = "+document.title+"<br>");

document.write("document.location = "+document.location+"<br>");

document.write("document.alinkColor = "+document.alinkColor+"<br>");

document.write("document.linkColor= " +document.linkColor+"<br>");

document.write("docuemnt.lastModified = "+document.lastModified+"<br>");

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


81

</script>

</body>

</html>

EXPLAIN ABOUT WINDOW OBJECT IN JAVASCRIPT?

(or)

EXPLAIN THE BUILT IN WINDOW TYPES PRESENTINH WITH AN EXAMPLE FOR


EACH ONE?

A window object is the top-level for each document, location and history object. The
browser window is a changeable object that can be addressed by JavaScript code.

Syntax: [windowVar=][window].open(“URL”,”windowName”,[“windowFeatures”])

windowVar is the name that you create for the new window.

URL is to open in the new window. It can be null(“ “)

WindowName portion respresents window name to use in the target attribute of <form> or
<A>tag.

WINDOW FEATURES

Option Explanation Value

width Used to set width of the browser window Integer

height Used to setl height of the browser window Integer

Location Used to display / hide the location bar in the new window [yes/no] or [1/0]

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


82

Status It is used to display / hide the status bar in the new window [yes/no] or [1/0]

WINDOW OBJECT PROPERTIES

Property Description

closed Returns a Boolean value indicating whether a window has been closed or not

defaultStatus Sets or returns the default text in the status bar of a window

document Returns the Document object for the window

frames Returns an array of all the frames (including iframes) in the current window

history Returns the History object for the window

length Returns the number of frames in a window

parent Returns the parent window of the current window

status Sets or returns the text in the statusbar of a window

top Returns the topmost browser window

WINDOW OBJECT FUNCTIONS (OR) METHODS

Method Description

alert() Displays an alert box with a message and an OK button

confirm() Displays a dialog box with a message and an OK and a Cancel button

prompt() Displays a dialog box that prompts the user for input

open() Opens a new browser window

close() Closes the current window

blur() Removes focus from the current window

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


83

focus() Sets focus to the current window

WRITE A PROGRAM TO DISPLAY WINDOW OBJECTS IN JAVASCRIPT?

<!DOCTYPE html>

<html>

<head>

<script>

var msg="hai this new window";

ob='toolbar=yes,location=yes,directories=no,status=no,menubar=yes,'

ob+='scrollbars=no,resizable=yes,width=500,height=300';

var x= window.open(" ","abc",ob);

x.document.write("<body bgcolor='pink' text='blue'>");

x.document.write("<H2><CENTER>"+msg+"</CENTER></H2>");

x.document.write("<FORM><CENTER>");

x. document.write("<INPUT type='button' value='click' onClick = 'self.close()'>");

x.document.write("</CENTER></FORM>");

</script>

</head>

<body>

<h1> window object </h1>

</body>

</html>

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


84

WRITE ABOUT FORM OBJECT IN JAVASCRIPT?

A form is object and can be manipulated in tow aspects through JavaScript. First the
data that is entered onto your form can be checked at submission. Second you can build
form through JavaScript. The <form> has number of attributes.

Property Description

.name The name of the form, which will be used when referencing objects with in the form

.method The method by which data is sent to the server

The URL of the CGI(common gateway interface) to which the data entered by the user
.action
will be sent

It is optional function to all or inline script to execute before the form data is submitted
.onsubmit
to server

Method Description

It is applied to all form elements. The event is triggered When the user clicks on that
onclick
element. It is not triggered to force events through the click() method

This event can only be triggered by the form itself and occurs when a form is
onsubmit
submitted

onReset This is a form only event and is triggered when a form is reset by the user

WRITE ABOUT BROWSER OBJECT IN JAVASCRIPT?

The browser is a JavaScript object and can be queried from within your code. The browser
object is actually called the navigator object

The following properties of browser object

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


85

Property Description

appCodeName It is used to get the code name of the browser

appName It is used to get the name of the browser

appVersion It is used to get the version of the browser

language It is used to get the language configured in browser preference

Plugins It is used to get an array of plugins installed in the browser

It is used to get an array of mime(multipurpose internet mail extensions) Types


mimeTypes
supported by the browser

WRITE A PROGRAM TO DISPLAY THE BROWSER OBJECT (OR) NAVIGATOR IN


JAVASCRIPT?

<html>

<body>

<script language = "javascript">

document.write("navigator.appName"+navigator.appName+"<br>");

document.write("navigator.appVersion"+navigator.appVersion+"<br>");

document.write("navigator.appCodeName"+navigator.appCodeName+"<br>");

document.write("navigator.userAgent"+navigator.userAgent+"<br>");

</script>

</body>

</html>

WRITE ABOUT DATA OBJECT IN JAVASCRIPT?

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


86

(OR)

EXPLAIN DATE OBJECT WITH ALL METHODS IN JAVASCRIPT?

JavaScript includes a well developed Date class which provides functions to perform
many different date manipulations. In JavaScript, date and time represent the number of
milliseconds since 1st January 1970 UTC. JavaScript like most programming systems, has
two separate notions of time UTC and local.

UTC is universal time, also know as Greenwich Mean Time, which is the standard
time throughout the world.

Local time is the time on the machine which is executing the script.

A JavaScript date object can represent dates from --100,000,000 to 100,000,000 days

Date(): Construct an empty date object.

Date (milliseconds) the new date object based upon the number of milliseconds which
have elapsed since 00:00:00 hours on 01/01/1970.

Date (string): The date object based upon the contents of a text string. The string must be
in the format which is created by the date. Parse() function

Parse(String): Returns the number of milliseconds since midnight on 01/01/1970 which


the string represents.

Method Description
date() Returns the current date and time
getDate() Returns the date, between the days of 1 and 31
getDay() Returns the day of the week, numbered 0 to 6
getMonth() Returns the month , numbered 0 to 11
getFullYear() Returns the year as a four digit number
getHours() Returns the current hour from 0 to 23
getMinutes() Returns the current minutes from 0 to 59
getSeconds() Returns the current seconds from 0 to 59
getMilliseconds() Returns the current milliseconds form 0 to 999
getTime() Returns the milliseconds since January 1, 1970
setDate() Specifies the day of the month 1-31
setMonth() Specifies the day of the month 0-11
setFullYear() Specifies the year in a Date object- four digits

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


87

setHours() Specifies the hour in a Date object 0-23


setMinutes() Specifies the minutes in a Date object 0-59
getUTCDate() Display the day of the month from a Date object specified by universal time from
1-31
setUTCDate() Specifies the day of the month in a Date object specified by universal time from 1-
31

WRITE A PROGRAM TO DEMONSTRATE DATE AND TIME FUNCTIONS?

<!DOCTYPE html>

<html>

<script>

var today=new Date();

document.write("Today:"+today);

document.write("<br>Day number is:"+ today.getDay());

document.write("<br>Month is:"+ today.getMonth());

document.write("<br>Year is:"+today.getYear());

document.write("<br>Hours is:"+today.getHours());

document.writeln("<br>UTC Hours is:"+today.getUTCHours());

</script>

<body></body>

</html>

WRIRE ABOUT EVENT HANDLING IN JAVASCRIPT

(OR)

WRITE ABOUT EVENT IN JAVASCRIPT

(OR)

WHAT ARE EVENTS? WHAT EVENTS CAN JAVASCRIPT HANDLE? EXPLAIN?

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


88

JavaScript is an event driven system. An event is any change that the user makes to the
state of the browser. For instance a word processor simply responds to you actions

JavaScript event handling can be quite a complex issue different manufactures have
implemented their own way of capturing and handling events. Internet explorer has a large
set of complicated, but useful, event routines which can be used t extend its functionality
beyond the web and onto the windows desktop the following are the event handler’s
properties.

The events handlers are not case-sensitive;

The syntax is <element attributes event=”handler”>

Attributes Description

onclick Refers to when an object is clicked

ondblclick Refers to when an object is double clicked

onblur Refer to an element losing the focus of the web browser

onfocus Refers to when an element is given focus

onerror Refers to when an error occurs

onkeypress Refers to when a keyboard key is pressed and /or held down

onsubmit Refers to when a submit button is clicked

onreset Refers to when a rest button is clicked

onload Refers to when a web page or image loads

onunload Refers to when a page is unloaded either by being closed or a link is clicked

onselect Refers to when an element is selected

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


89

onresize Refers to when a window is resized

onmouseup Refers to when the mouse button is released

onmousedown Refers to when the mouse button is pressed down

onkeyup Refers to when a keyboard key is released

WRITE A PROGRAM TO HANDLING EVENTS IN JAVASCRIPT?

<html>

<head>

<script type="text/javascript">

<!--

function over() {

alert("Mouse Over");

function out() {

alert("Mouse Out");

//-->

</script>

</head>

<body>

<form method="POST" action="https://in.yahoo.com/" onsubmit="return validate()">

<input type="submit" value="Submit" />

<p>Bring your mouse inside the division to see the result:</p>

<div onmouseover="over()" onmouseout="out()">

<h2> This is inside the division </h2>

</body>

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


90

</html>

EXPLAIN DATA VALIDATION IN DHTML?

(OR)

EXPLAIN HOW DATA VALIDATION CAN BE DONE IN DHTML USING JAVASCRIPT?

Validation is simply the process of ensuring that some data might be correct data for a
particular application. Data validation is the process of ensuring that users submit only the
set of characters which you require. It is not the process of ensuring that the data is any
way accurate.

If a program accepts data from a remote data looger and that input is always going
to be in a particular range, then the program knows that data outside the range is invalid
and should not be accepted..

WRITE A PROGRAM TO IMPLEMENT THE DATA VALIDATION?

<html>

<head>

<title> remembering patterns </title> </head>

<body>

<script language = javascript>

var st = new RegExp("{B|b}sc");

var st1= "Is this mstcs final year?";

var result = st.exec(st1);

if (result)

alert ("found"+result);

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


91

else

alert(" i didn't find it");

</script>

</body>

</html>

EXPLAIN MESSAGE PASSING IN DHTML?

(OR)

EXPLAIN MESSAGES AND CONFIRAMTIONS IN JAVASCRIPT?

(OR)

EXPLAIN VARIOUS BUILT IN WINDOW TYPES WITH SYNTAX AND EXAMPLES IN


JAVASCRIPT?

JavaScript provides three built-in window types that can be used from application
code. For instance you may need them to click a confirmation button before submitting
information to your database.

Three kinds of popup boxes created using javascript are

1) Alert box 2) Confirm box 3) Prompt box

ALERT BOX: the alert box is useful for alerting the users to something important. When a
javascript alert box is triggered. A small box will pop up and display the text that is
specified in the javascript code. The alert box pops up with an Ok button which the user has
to press to continue

Syntax: alert(“textmessage”); Ex: alert (“welcome to javascript”);

PROGRAM FOR DISPLAY THE ALERT BOX IN DHTML OR JAVASCRIPTS?

<html>

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


92

<head>

<script type="text/javascript">

<!--

function W() {

alert("hai mstcs final year");

//-->

</script>

</head>

<body>

<p>Click the following button to see the result: </p>

<form>

<input type="button" value="Click Me" onclick="W();" />

</form>

</body>

</html>

CONFIRM BOX: The confirm method shows a dialog box that contains a message and an
OK and Cancel button. If the user presses the OK button the confirm method returns true. It
the user presses cancel the method returns false

Syntax: confirm(“textmessage”); Ex: confirm(“do hardwork”);

<html>

<head>

<script type="text/javascript">

<!--

function getConfirmation(){

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


93

var retVal = confirm("Do you want to continue ?");

if( retVal == true ){

alert("User wants to continue!");

return true;

}else{

alert("User does not want to continue!");

return false;

//-->

</script>

</head>

<body>

<p>Click the following button to see the result: </p>

<form>

<input type="button" value="Click Me" onclick="getConfirmation();" />

</form>

</body>

</html>

PROMPT BOX: The prompt method


shows a dialog box with a message, a text
entry field, an OK button, and CANCEL
button. If the user presses OK the text in the
text entry field is returned as string. If the user
presses cancel the null value is returned by
the prompt method.

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


94

Syntax: prompt (“textmessage”,”value_default”);

Example: prompt (“input the user”,”srikanth”);

<html>

<head>

<script type="text/javascript">

<!--

function getValue(){

var gskVal = prompt("Enter your name : ", "your name here");

alert("You have entered : " + gskVal );

//-->

</script></head>

<body>

<p>Click the following button to see the result: </p>

<form>

<input type="button" value="Click Me" onclick="getValue();" />

</form>

</body></html>

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


95

UNIT-II: BASICS OF PHP

DEFINE PHP? EXPLAIN ABOUT ADVANTAGES OR BENEFITS OF PHP?


The PHP Hypertext Preprocessor (PHP) is a programming language that allows web
developers to create dynamic content that interacts with databases. PHP is basically used for
developing web based software applications.
PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
PHP is a server side scripting language that is embedded in HTML. It is used to manage dynamic
content, databases, (like MySQL, Oracle SQL Server) session tracking, even build entire e-
commerce sites.
Uses of PHP
 PHP performs system functions, i.e. from files on a system it can create, open, read,
write, and close them.
 PHP can handle forms, i.e. gather data from files, save data to a file, thru email you can
send data,return data to the user.
 You add, delete, modify elements within your database thru PHP.
 Access cookies variables and set cookies.
 Using PHP, you can restrict users to access some pages of your website.
 It can encrypt data.

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


96

CHARACTERSTICS OF PHP
 Five important characteristics make PHP's practical nature possible:
 Simplicity
 Efficiency
 Security
 Flexibility
 Familiarity

EXPLAIN IN HOW MANY WAYS THE PHP PROGRAM CAN WE CREATED?


In order to develop and run PHP Web pages, three vital components need to be installed on your
computer system

Web Server - PHP will work with virtually all Web Server software, including Microsoft's Internet
Information Server (IIS) but then most often used is freely available Apache Server. Download Apache
for free here: http://httpd.apache.org/download.cgi

Database - PHP will work with virtually all database software, including Oracle and Sybase but most
commonly used is freely available MySQL database. Download MySQL for free here:
http://www.mysql.com/downloads/index.html

PHP Parser - In order to process PHP script instructions, a parser must be installed to generate HTML
output that can be sent to the Web Browser. This tutorial will guide you how to install PHP parser on
your computer

We will create a very simple PHP script that displays the text "Hello, world!" in the browser
window. Ok, click on the WampServer icon somewhere on your Windows task bar and select
the "www directory". Alternatively you can access the "www" directory through
C:\wamp\www. Create a subdirectory in "project".
Now open up your code editor and create a new PHP file. Start with an

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


97

empty window and type the following code:


<?php
// Simple greeting message
echo "Hello, world!";
?>
Now save this file as "hello.php" in your project folder (located at
C:\wamp\project), and view the result in your browser through visiting this URL:
http://localhost/project/hello.php. Alternatively you can access the "hello.php" file through
selecting the local host option from the WampSever menu on the taskbar

EMBEDDING PHP WITHIN HTML


PHP files are plain text files with .php extension. Inside a PHP file you can write HTML like you
do in regular HTML pages as well as embed PHP codes for server side execution.
<html lang="en">
<head>
<title>A Simple PHP File</title>
</head> <body>
<h1><?php echo "Hello, world!"; ?></h1>
</body> </html>

DEFINE PHP VARIABLE? EXPLAIN IT TYPES?


A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
Rules for PHP variables:
A variable starts with the $ sign, followed by the name of the variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _)
Variable names are case-sensitive ($age and $AGE are two different variables).
In PHP, variables can be declared anywhere in the script.

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


98

The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
 local
 global
EXPLAIN ABOUT DATA TYPES IN PHP?
PHP supports total eight primitive data types: Integer, Floating point number or Float, String,
Booleans, Array, Object, resource and NULL. These data types can be broken into three
categories
1. Scalar Data types 2. Compound Data types 3. Special Data types

Scalar data types: Scalar data types are capable of containing a single item of information.
Several data types fall under this category including Boolean, Integer, Float and String

Boolean: A Boolean variable represents truth, supporting only two values TRUE or FALSE.

Alternatively we can use zero to represent FALSE & nonzero to represent TRUE

Integer: An integer is quite simply a whole number or that doesn’t contain fractional parts.

Decimal, Octal and hexadecimal numbers

Float: Float data type allows you to specify numbers that contain fractional parts

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


99

String: A string is a sequence of characters treated as a single unit; such units are typically

delimited by single or double quotes.

2. Compound data types: Compound data types allow us to aggregate multiple items of the

same type under a single name

Array: An array is a variable that can hold more than one value at a time. It is useful to

aggregate a series of related items together. An array is formally defined as an indexed

collection of data values

Ex: $state[1]= “Andhra Pradesh”;

Object: An object is a data type that not only allows storing data but also information on, how to

process that data. An object is a specific instance of a class which serves as templates for objects.

Objects are created based on this template via the new keyword. Every object has properties and

methods corresponding to those of its parent class.

3. SPECIAL DATA TYPES: Special data types encompass those types serving some sort of specific

purpose, which makes it impossible to group them in any other type category.

Resource: PHP is often used to interact with external data sources such as databases,

files &network streams. Typically this interaction takes place through "handles? EX: such

functions include fopen(), mysqli_connect()

Null: The special NULL value is used to represent empty variables in PHP. A variable of

type NULL is a variable without any data

EXPLAIN ABOUT OPERATORS IN PHP?

Operators: An operator is a symbol that specifies a particular action in an expression. The

following are the different classes of operators in PHP:

1. Arithmetic Operators 2. Assignment Operators

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


100

3. String Operators 4. Increment & Decrement Operators

5. Logical Operators 6. Equality Operators

7. Comparison Operators 8. Bit-wise Operators

Arithmetic Operators: The arithmetic operators perform various mathematical operations and

will probably be used frequently in many of your PHP programs

Assignment operators: - Used to assign a data value to a variable. The simplest form of assignment
operator justassigns some value

3. String Operators: PHP's string operators provide a convenient way in which to concatenate strings
together.

4. Increment & Decrement Operators: Providing shortened means by which you can add 1 to
or subtract 1 from the current value of a variable.
101

5. Logical Operators: Logical operators make it possible to direct the flow of a program, and are
used frequently with control structures, such as the if conditional and the while and for loops.

6. Equality Operators: Equality operators are used to compare two values, testing for
equivalence.

7. Comparison Operators: Comparison operators, like logical operators, provide a method by


which to direct program flow through examination of the comparative values of two or more
variables.

8. Bit-wise Operators: Bitwise operators examine and manipulate integer values on the level of
individual bits that make up the integer value.
102

EXPLAIN ABOUT PRINTS STATEMENTS IN PHP?


i) print(): The print() statement is responsible for providing feedback to user and it can capable
of displaying both raw strings and variables.
Example:
<?php
print ("<p> this is a statement</p>");
?>
ii) echo(): void echo (string arg1[,...,string arg n]);
The echo() statement operates similarly to print(), except for 2 differences:
• It cannot be used as part of complex expression (because it returns void).
• It is capable of outputting of multiple strings
EXPLAIN ABOUT CONTROL STATEMENTS / CONTROL STRUCTURES (OR) CONDITION
OPERATORS IN PHP?
Conditional statements are used to perform different actions based on different conditions.
When we write code, we want to perform different actions for different conditions

IF STATEMENT:
The if statement executes some code if the specified condition is true.
Syntax
103

if (condition) {
code to be executed if condition is true;
}

THE IF...ELSE STATEMENT


The if ...else statement executes some code if a condition is
true and another code if that condition is false.
Syntax
if (condition) {
code to be executed if condition is true;
} else { code to be executed if condition is false; }
The if .. elseif ... else Statement
The if....elseif .. else statement executes different codes for
more than two
conditions.
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
}

LOOPS STATEMENTS
When we write code, we want the same block of code to run over and over again in a row.
Instead of adding several almost equal code-lines in a script, we can use loops to perform a task
like this.
104

while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
for - loops through a block of code a specified number of time

While Loop
The while loop executes a block of code as long as the
specified condition is true.
Syntax
while (condition is true) {
code to be executed; }
Do...While Loop
The do...while loop will always execute the block of code once, it will then check the condition,
and repeat the loop while the specified condition is true.
Syntax
do {
code to be executed;
} while (condition is true);

For Loops
PHP for loops execute a block of code a specified number of times. The for loop is used when
we know in advance how many times the script should run.
Syntax
for (init counter; test counter; increment counter) {
code to be executed;
}
105

EXECUTION LOOPING STATEMENTS / UNCONDITIONAL STATEMENTS


CONTINUE STATEMENT
The continue statement is used within looping structures to skip the rest of
the current loop iteration and continue execution at the condition
evaluation and then the beginning of the next iteration

BREAK STAEMENT
The keyword break ends execution of the current for, for each, while,
do while or switch structure. When the keyword break executed inside a loop
the control automatically passes to the first statement outside the loop.
DEFINE ARRAY? EXPLAIN HOW TO CREATE AN ARRAY AND TYPES OF ARRAY
IN PHP?
An array is a data structure that stores one or more similar data type of values in a
single value.
Advantage of PHP Array:
 Less Code: We don't need to create multiple variables.
 Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
 Sorting: We can easily sort the elements of array.
CREATING ARRAYS
Arrays are complex variables that stores multiple or a group of values under a single variable
name.
<?php
$color1 = "Red";
$color2 = "Green";
$color3 = "Blue";
?>
Types of Arrays in PHP:
There are three types of arrays that you can create. These are:
• Indexed array - An array with a numeric key.

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


106

• Associative array - An array where each key has its own specific value.
• Multidimensional array - An array containing one or more arrays within itself.
Indexed Arrays:
A numeric array stores each element with a numeric ID key. That means the keys
have no real relation to the value other than the value?s position in the array. There are two
ways to create numerical arrays:
Syntax 1:
$colors=array("red", "green", "blue", "yellow", "black")
Syntax 2:
$colors[0]= "red"; $colors[1]= "green"; $colors[2]= "blue"; $colors[3]= "yellow"; $colors[4]=
"black";
Associative Arrays:
In an associative array, the keys assigned to values can be arbitrary and user defined strings. In
the following example the array uses keys instead of index numbers
Syntax:
$protocols = array ("TCP" => "Transmission Control Protocol", "IP" => "Internet
Protocol", "UDP" => "User Datagram Protocol", "FTP" => "File Transfer Protocol");
Multidimensional Arrays:
The multidimensional array is an array in which each element can also be an array and each
element in the sub-array can be an array or further contain array within itself and so on.

EXPLAIN ABOUT ARRAY FUNCTIONS IN PHP?


SNO FUNCTION DESCRIPTION
This function takes zero or more items as its input and returns an
1 array()
array consisting of these input elements.
It is used to make simultaneous variable assignments from values
2 list()
extracted from an array in just one operation.
It provides an easy way to quickly create and fill an array consisting of
3 range()
a range of low and high integer values.

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


107

This function determines whether variable is an array, returning TRUE


4 is_array()
if it is and FALSE otherwise.
This function takes as input any variable and sends its contents to
5 print_r()
standard output, returning TRUE on success and FALSE otherwise.
It adds variable onto the end of the given array, returning TRUE on
6 array_push()
success and FALSE otherwise.
7 array_pop() This function returns the last element from given array.
8 array_reverse() This function reverses the element order of the given array
9 count() It returns the total number of values found in the given array.
It sorts the given array, ordering elements from lowest to highest
10 sort()
value.
DESCRIBE ABOUT PHP STRING FUNCTIONS? (OR) EXPLAIN ABOUT STRING HANDLING
FUNCTIONS IN PHP?
108

WRITE ABOUT FORMATTING STRINGS WITH PHP?


(OR)
WRITE ABOUT FORMAT BUILT FUNCTION OF PHP?
The sprintf() is an in-built function of PHP which writes a formatted string to a variable. It
returns a formatted string. The sprintf() function is similar to the printf() function, but the only
difference between both of them is that sprint() saves the output into a string instead of displaying the
formatted message on browser like printf() function.
Syntax: sprintf (format, agr1, agr2, arg3...) : string
Here the arg1, arg2, arg3, etc. are the parameters of sprintf(). These parameters will be inserted
in the main string with percent (%) symbols. At each % sign, arguments will insert one-by-one.

Ganti.Naga Srikanth (Vice Principal & Lec in Comp Science)@Aditya,kkd EMAIL:gantinagasrikanth@gmail.com


109

EXPLAIN ABOUT STRING MANIPULATIONS COMMANDS IN PHP?

There are some functions in strings by using that commands we can manipulate the
strings according to that function.
1) Strlen() 2) strstr() 3) strpos() 4) substr() 5) strtok()

Strlen(): The strlen() is used to determine the length of a string. strlen() requires a string and returns an
integer representing the number of characters in the variable you have passed it.
if (strlen($membership) == 4) {
print "Thank you!";
} else {
print "Your 4 digits<P>";
}

strstr(): The strstr() is used to test whether a string exists embedded within another
string.strstr() requires two arguments: a source string and the substring you want to find within
it
$membership = "pAB7";
if (strstr($membership, "AB"))
{
print "Thank you. Don't forget soon!";
} else {
print "Thank you!";
}
substr(): The substr() function returns a portion of a string based on the start index and length
of the portion you are looking for. This function demands two arguments: a source string and
the starting index
$test = "mangofruit";
print substr($test,5); // prints "fruit"
print substr($test,5,2) // prints "fr"
110

strpos(): The strpos() function tells us both whether a string exists within a larger string and
where it is to be found. strpos() requires two arguments: the source string and the substring.
$membership = "message";
if (strpos($membership, "me") === 0) {
print "hello me";
}
strtok(): The strtok() function initially requires two arguments: the string to be tokenized and
the delimiters by which to split the string.
$test = "php.com"
$test .= "OP=dnquery.xp&ST=MS&DBS=2&QRY=developer+php";
$delims = "?&";
$word = strtok($test, $delims);
while (is_string($word)) {
if ($word) {
print "$word<br>";
}
$word = strtok($delims);
}
?>

EXPLAIN ABOUT DATE AND TIME FUNCTIONS IN PHP WITH AN EXAMPLE?


111
112

PROGRAM
<!DOCTYPE html>
<html>
<head>
<title>PHP Date Basic Syntax</title>
</head>
<body>
<?php
echo "Today is : " . date("Y/m/d") . "<br />";
echo "Today is : " . date("Y.m.d") . "<br />";
echo "Today is : " . date("Y-m-d") . "<br />";
echo "Today is : " . date("l") . "<br />";
echo "Today is : " . date("D") . "<br />";
echo "Today date is : " . date("d") . "<br />";
echo "This Month is : " . date("M") . "<br />";
echo "This year is : " . date("Y");
?>
</body>
</html>
Output :
Today is : 2022/04/07 Today is : 2022.04.07
Today is : 2022-04-07 Today is : Thursday
Today is : Thu Today date is : 07
This Month is : Apr This year is : 2022
113

UNIT – III
ADVANCED PHP

Advanced PHP: Functions, Advantages of Using functions, Types of functions, creating and
invoking functions, returning values, recursive functions Object Oriented Concepts, File
handling and Data Storage: creating, open/close a file, file operations: read, write, append. File
truncate, file uploading, EOF in PHP.

WHAT IS FUNCTION? EXPLAIN ADVANTAGES OF USING A FUNCTION?


A function is a self-contained block of code that can be called by your scripts. When called, the
function’s code is executed and performs a particular task. You can pass values to a function, which then
uses the values appropriately—storing them, transforming them, displaying them, whatever the
function is told to do. When finished, a function can also pass a value back to the original code that
called it into action.
TYPES OF FUNCTIONS: they are 4 types of advantages are there using a function in PHP
1. Code Reusability
2. Less Code
3. Easy to understand
4. Easy to maintain code

1. Code Reusability: PHP functions are defined once and can be invoked many times, like in other
programming languages.
2. Less Code: With function, logic is written only once, and it will be reused. so it reduces the need
of writing the same logic many time in the script.
3. Easy to understand: PHP functions separate the programming logic from the actual code. So it is
easier to understand the flow of the application because every logic is divided in the form of
functions.
4. Easy to maintain code: Function created once can be used many times, so any changes
made inside a function is automatically implemented at all the places without touching the
several files
114

DEFINE A FUNCTION? EXPLAIN TYPES OF FUNCTIONS IN PHP?


A function is a self-contained block of code that can be called by your scripts. When called, the
function’s code is executed and performs a particular task. You can pass values to a function, which then
uses the values appropriately—storing them, transforming them, displaying them, whatever the
function is told to do. When finished, a function can also pass a value back to the original code that
called it into action.
TYPES OF FUNCTIONS
They are two types of functions are available in PHP
1) Built-in functions 2) User Defined Functions

BUILT-IN FUNCTIONS: HP provides us with huge collection of built-in library functions. These
functions are already coded and stored in form of functions. To use those we just need to call
them as per our requirement like, var_dump, fopen(), print_r(), gettype() and so on.
USER DEFINED FUNCTIONS: Apart from the built-in functions, PHP allows us to create our own
customized functions called the user-defined functions.
Using this we can create our own packages of code and use it wherever necessary by simply
calling it.

HOW WE CAN CREATE FUNCTION & INVOKE A FUNCTION IN PHP?


While creating a user defined function we need to keep few things in mind:

1. Any name ending with an open and closed parenthesis is a function.


2. A function name always begins with the keyword function.
3. To call a function we just need to write its name followed by the parenthesis
4. A function name cannot start with a number. It can start with an alphabet or
underscore.
5. A function name is not case-sensitive.
6. Function must be single word if there are more than one word in a function name must
use underscore between them.
115

Syntax for function declaration without parameters.


function function_name ()
{
statement1;
statement2;
...
...
}
Example:
<?php
/* Defining a PHP Function */
function Sample_function()
{
echo "we are learning function creation";
}
Sample_function (); # function call
?>

EXPLAIN ABOUT PARAMETER PASSING METHODS IN FUNCTION?


(OR)
EXPLAIN ABOUT PARAMETER PASSING MECHANISM IN FUNCTION?

PHP allows us two ways in which an argument can be passed into a function
1) CALL BY VALUE (OR) PASS BY VALUE
2) CALL BY REFERENCE (OR) PASS BY REFERENCE

CALL BY VALUE: On passing arguments using pass by value, the value of the argument gets
changed within a function, but the original value outside the function remains unchanged. That
means a duplicate of the original value is passed as an argument.
116

<?php
function swap($arg1, $arg2){
echo "inside function before swapping: arg1=$arg1 arg2=$arg2\n";
$temp=$arg1;
$arg1=$arg2;
$arg2=$temp;
echo "inside function after swapping: arg1=$arg1 arg2=$arg2\n";
}
$arg1=10;
$arg2=20;
echo "before calling function : arg1=$arg1 arg2=$arg2\n";
swap($arg1, $arg2);
echo "after calling function : arg1=$arg1 arg2=$arg2\n";
?>
OUTPUT
before calling function : arg1=10 arg2=20
inside function before swapping: arg1=10 arg2=20
inside function after swapping: arg1=20 arg2=10
after calling function: arg1=10 arg2=20

CALL BY REFERENCE (OR) PASS BY REFERENCE


On passing arguments as pass by reference, the original value is passed. Therefore, the original
value gets altered. In pass by reference we actually pass the address of the value, where it is stored
using ampersand sign(&).
<?php
function swap(&$arg1, &$arg2){
echo "inside function before swapping: arg1=$arg1 arg2=$arg2\n";
$temp=$arg1;
$arg1=$arg2;
$arg2=$temp;
117

echo "inside function after swapping: arg1=$arg1 arg2=$arg2\n";


}
$arg1=10;
$arg2=20;
echo "before calling function : arg1=$arg1 arg2=$arg2\n";
swap($arg1, $arg2);
echo "after calling function : arg1=$arg1 arg2=$arg2\n";
?
OUTPUT
before calling function : arg1=10 arg2=20
inside function before swapping: arg1=10 arg2=20
inside function after swapping: arg1=20 arg2=10
after calling function : arg1=20 arg2=10

EXPLAIN ABOUT RECRUSIVE FUNCTION IN PHP?


Recursive function is a function which calls itself again and again until the termination condition arrive.
Recursive function calls can save undue space and redundancy in programs and aer useful for
performing repetitive operations.
<!DOCTYPE html>
<html>
<body>
<?php
function factorial($n)
{
if ($n < 0)
return -1;
if ($n == 0) return 1;
return ($n * factorial ($n -1));
}
echo factorial(10); ?> </body> </html>
118

DEFINE VARIABLE-LENGTH ARGUMENT LIST FUNCTION IN PHP?


PHP has support for variable-length argument lists in user-defined functions by using the ...
token.
Argument lists may include the ... token to denote that the function accepts a variable
number of arguments. The arguments will be passed into the given variable as an array.
NOTE: It is also possible to achieve variable-length arguments by using func_num_args
(), func_get_arg(), and func_get_args() functions. This technique is not recommended as it was
used prior to the introduction of the ... token.

EXAMPLE
<?php
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
?> OUTPUT IS : 10

WHAT IS OOP? EXPLAIN ABOUT ADVANTAGES OF OOP IN PHP?

OOP stands for Object-Oriented Programming.


Procedural programming is about writing procedures or functions that perform operations on
the data, while object-oriented programming is about creating objects that contain both data
and functions.
OOP PHP is a type of programming language construct added in php5 which helps in
building complex and reusable web application
119

ADVANTAGES OF OOP IN PHP


 OOP is faster and easier to execute
 OOP provides a clear structure for the programs
 OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes the code
easier to maintain, modify and debug
 OOP makes it possible to create full reusable applications with less code and shorter
development time

EXPLAIN ABOUT OBJECT ORIENTED CONCEPTS IN PHP?

Class Object Member Variable Member function


Inheritance Parent class Child Class Polymorphism
Overloading Data Abstraction Encapsulation Constructor
Destructor

Class − This is a programmer-defined (OR) USER DEFINED data type, which includes local
functions as well as local data. You can think of a class as a template for making many instances
of the same kind (or class) of object.

Object − An individual instance of the data structure defined by a class. You define a class once
and then make many objects that belong to it. Objects are also known as instance.

Member Variable − These are the variables defined inside a class. This data will be invisible to
the outside of the class and can be accessed via member functions. These variables are called
attribute of the object once an object is created.

Member function − These are the function defined inside a class and are used to access object
data.
120

Inheritance − When a class is defined by inheriting existing function of a parent class then it is
called inheritance. Here child class will inherit all or few member functions and variables of a
parent class.

Parent class − A class that is inherited from by another class. This is also called a base class or
super class.

Child Class − A class that inherits from another class. This is also called a subclass or derived
class.

Polymorphism − This is an object oriented concept where same function can be used for
different purposes. For example function name will remain same but it take different number of
arguments and can do different task.

Overloading − a type of polymorphism in which some or all of operators have different


implementations depending on the types of their arguments. Similarly functions can also be
overloaded with different implementation.

Data Abstraction − Any representation of data in which the implementation details are hidden
(abstracted).

Encapsulation − refers to a concept where we encapsulate all the data and member functions
together to form an object.

Constructor − refers to a special type of function which will be called automatically whenever
there is an object formation from a class.

Destructor − refers to a special type of function which will be called automatically whenever an
object is deleted or goes out of scope.
121

WHAT IS CLASS? HOW CAN WE CREATE A CLASS IN PHP?


A class is defined by using the class keyword, followed by the name of the class and a pair of
curly braces ({}). All its properties and methods go inside the braces:
 The special form class, followed by the name of the class that you want to define.
 A set of braces enclosing any number of variable declarations and function definitions.
 Variable declarations start with the special form var, which is followed by a conventional
$ variable name; they may also have an initial assignment to a constant value.
 Function definitions look much like standalone PHP functions but are local to the class
and will be used to set and access object data
SYNTAX:
<?php
class Fruit {
// code goes here...
}
?>
EXAMPLE:
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
} }
?>
122

DEFINE OBJECTS? HOW CAN WE CREATE A OBJECT WITH EXAMPLE?


An Object is an individual instance of the data structure defined by a class. We define a class
once and then make many objects that belong to it. Objects are also known as instances.
An object of a class is created using the new keyword.

<!DOCTYPE html>
<html>
<body>
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
} function get_name() {
return $this->name;
}}
$apple = new Fruit();
$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');

echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>
</body> </html> output : apple banana
123

WHAT IS A CONSTRUCTOR AND DESTRUCTOR FUNCTIONS IN PHP?


A constructor allows you to initialize an object's properties upon creation of the object. If you
create a construct() function, PHP will automatically call this function when you create an
object from a class.
DESTRUCTOR
A destructor is called when the object is destructed or the script is stopped or exited. If you
create a destruct() function, PHP will automatically call this function at the end of the script.
The construct and destructor functions starts with two underscores ( )!
EXAMPLE:
<!DOCTYPE html>
<html>
<body>
<?php
class Fruit {
// Properties
var $name;
var $color;
// Methods
function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
function __destruct() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}}
$apple = new Fruit("Apple", "red");
?>
</body>
</html> OUTPUT: The fruit is Apple and the color is red.
124

DEFINE ABOUT STATIC & FINAL KEYWORD IN PHP?


STATIC KEY WORD: Declaring class members or methods as static makes them accessible without
needing an instantiation of the class. A member declared as static cannot be accessed with an
instantiated class object
SYNTAX EXAMPLE

<?php <?php
class ClassName { class greeting {
public static function staticMethod() { public static function welcome() {
echo "Hello World!"; echo "Hello World!";
} }
} }
?> greeting::welcome(); ?>

FINAL KEY WORD: PHP 5 introduces the final keyword, which prevents child classes from overriding a
method by prefixing the definition with final. If the class itself is being defined final then it cannot be
extended.
Syntax: EXAMPLE
final function name_of_the_function() <?php
{ final class MyClass {
} final class Class_Name public $name = "GSK";
{ } }
class AnotherClass extends MyClass{};
?>

DEFINE ABOUT INHERITANCE? EXPLAIN ABOUT DIFFERENT TYPES OF INHERITANCE?


It is a concept of accessing the features of one class from another class. If we inherit the
class features into another class, we can access both class properties. We can extends the
features of a class by using 'extends' keyword.
They are 3 types of inheritance
1) Single level inheritance 2) multilevel inheritance 3) Hierarchical level inheritance
125

SINGLE LEVEL INHERITANCE: In single-level inheritance, we inherit one class into another class.
In this process, One is parent class and the other is child class. This type of inheritance also
known as simple inheritance.

MULTILEVEL INHERITANCE:
In this type of inheritance, there will be more than 2 classes involved. In Multilevel inheritance
Parent class will be inherited by a child and then further child class will be inherited by another
child class.

HIERARCHICAL INHERITANCE:
When more than one class inherit to a single class. This type of inheritance known as
Hierarchical Inheritance.
126

WHAT IS ABSTRACT CLASS? AND METHODS


Abstract classes and methods are when the parent class has a named method, but need its
child class(es) to fill out the tasks.
An abstract class is a class that contains at least one abstract method. An abstract method is a
method that is declared, but not implemented in the code.
An abstract class or method is defined with the abstract keyword:
RULES OF ABSTRACT CLASS
 The child class method must be defined with the same name and it redeclares the
parent abstract method
 The child class method must be defined with the same or a less restricted access
modifier
 The number of required arguments must be the same. However, the child class may
have optional arguments in addition
SYNTAX:
<?php
abstract class ParentClass {
abstract public function someMethod1();
abstract public function someMethod2($name, $color);
abstract public function someMethod3() : string;
} ?>
EXAMPLE
<?php
abstract class base {
abstract function printdata();
public function getdata() {
echo "GSK II BCA";
} }
class child extends base{
public function printdata(){
127

echo "GSK II BCA";


} }
$obj = new child();
$obj->getdata();
?>

DEFINE INTERFACE? WHAT ARE THE RULES OF INTERFACE?

An Interface allows the users to create programs, specifying the public methods that a class
must implement, without involving the complexities and details of how the particular methods are
implemented. It is generally referred to as the next level of abstraction. It resembles the abstract
methods, resembling the abstract classes. An Interface is defined just like a class is defined but with the
class keyword replaced by the interface keyword and just the function prototypes. The interface
contains no data variables. The interface is helpful in a way that it ensures to maintain a sort of
metadata for all the methods a programmer wishes to work on.

CHARACTERSITCS (OR) RULES OF INTERFACE


 An interface consists of methods that have no implementations, which means the
interface methods are abstract methods.
 All the methods in interfaces must have public visibility scope.
 Interfaces are different from classes as the class can inherit from one class only whereas
the class can implement one or more interfaces.
<?php
interface MyInterfaceName {
public function methodA();
public function methodB();
}
?>
128

WHAT ARE TRAITS IN PHP?


PHP only supports single inheritance: a child class can inherit only from one single parent.
Traits are used to declare methods that can be used in multiple classes. Traits can have
methods and abstract methods that can be used in multiple classes, and the methods can have
any access modifier (public, private, or protected).
Traits are declared with the trait keyword:
SYNTAX
<?php
class MyClass {
use TraitName;
} ?>
EXAMPLE
<?php
trait message1 {
public function msg1() {
echo "OOP is fun! ";
} }
class Welcome {
use message1;
}
$obj = new Welcome();
$obj->msg1();
?>

EXPLAIN ABOUT ENCAPSULATION WITH AN EXAMPLE?


 Encapsulation is a concept where we encapsulate all the data and member functions
together to form an object.
 Wrapping up data member and method together into a single unit is called
Encapsulation.
129

 Encapsulation also allows a class to change its internal implementation without hurting
the overall functioning of the system.
 Binding the data with the code that manipulates it.
 It keeps the data and the code safe from external interference.
EXAMPLE
<?php
class Job
{
public $Job_name;
public $Job_id;
function __construct($job_names, $job_ids)
{
$this->Job_name = $job_names;
$this->Job_id = $job_ids;
}
public function Job_details()
{
echo "Job name is: $this->Job_name Job id is: $this->Job_id";
}
}
$obj = new Job("Web Developer", "096847");
echo $obj->Job_details();
?>
OUTPUT
Job name is: Web Developer
Job id is: 096847
130

EXPLIAN ABOUT FILE HANDLING FUNCTIONS? AND WRITE IT MODES?


File handling is needed for any application. For some tasks to be done file needs to be
processed. File handling in PHP is similar as file handling is done by using any programming
language like C. PHP has many functions to work with normal files.
FUNCTIONS IN FILE
1) fopen() : PHP fopen() function is used to open a file. First parameter of fopen() contains
name of the file which is to be opened and second parameter tells about mode in which file
needs to be opened
<?php
$file = fopen(“demo.txt”,'w');
?>
2) fread() : After file is opened using fopen() the contents of data are read using fread(). It takes
two arguments. One is file pointer and another is file size in bytes
<?php
$filename = "demo.txt";
$file = fopen( $filename, 'r' );
$size = filesize( $filename );
$filedata = fread( $file, $size );
?>

3) fwrite() : New file can be created or text can be appended to an existing file using fwrite()
function. Arguments for fwrite() function are file pointer and text that is to written to file. It can
contain optional third argument where length of text to written is specified
<?php
$file = fopen("demo.txt", 'w');
$text = "Hello world\n";
fwrite($file, $text);
?>
4) fclose() : file is closed using fclose() function. Its argument is file which needs to be closed
131

<?php
$file = fopen("demo.txt", 'r');
//some code to be executed
fclose($file);
?>
MODES OF FILE (OR) FILE MODES
1) “w” – Opens a file for write only. If file not exist then new file is created and if file
already exists then contents of file is erased.
2) “r” – File is opened for read only.
3) “a” – File is opened for write only. File pointer points to end of file. Existing data in file is
preserved.
4) “w+” – Opens file for read and write. If file not exist then new file is created and if file
already exists then contents of file is erased.
5) “r+” – File is opened for read/write.
6) “a+” – File is opened for write/read. File pointer points to end of file. Existing data in file
is preserved. If file is not there then new file is created.
7) “x” – New file is created for write only.
132

UNIT – IV
WORKING WITH FORMS IN PHP
DEFINE FORM? EXPLAIN HOW TO CREATE A FORM IN PHP?
Form in PHP is similar to the forms that are built using HTML except the syntax used. In PHP,
forms use the GET and POST methods to print or retrieve the data entered by the user.
When the user enters all the details required in the form and submits the form using the
submit button the form is then further sent for processing and the action is performed on the
basis of whatever is mentioned in the action function. The form is then sent for further
processing using GET or POST methods whichever is mentioned while designing the form.

CREATION OF FORM
To create a form, you use the <form> element as follows:
<form action="form.php" method="post">
</form>
The <form> element has two important attributes:
action: specifies the URL that processes the form submission. In this example, the form.php
will process the form.
method: specifies the HTTP method for submitting the form. The most commonly used form
methods are POST and GET. In this example, the form method is post.
POST method
If a form uses the POST method, the web browser will include the form data in the HTTP
request’s body. After submitting the form, you can access the form data via the associative
array $_POST in PHP.
GET method
When you submit a form using the GET method, you can access the form data in PHP via the
associative array $_GET.
Unlike the POST method, the GET method appends the form data in the URL that
processes the form.
133

EXAMPLE
<!DOCTYPE HTML>
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form> </body> </html>

EXPLAIN THE FORM ELEMENTS AVAILABLE IN PHP?


(OR)
WHAT IS ROLE OF HTML FORM IN PHP? USING GET AND POST METHODS
Forms are a mechanism that allow you to type information into fields on a browser
screen and submit the information to a web server. They allow you to create interactive web
pages. That is you can fill out a form, submit it and then the information is uploaded to the
designated serer to handle a form. A program on the server processes the information and then
returns a new WEB DOCUMENT.

Forms provide an interface for collecting, displaying, and delivering information and are
used as a key component of HTML. Forms have different types of fields such as text input fields,
radio buttons, checkboxes, submit and reset button etc.

GET METHOD
 Get appends the form data to the end of URL, in the form of name=value pairs.
 Never use GET to send sensitive data, because the submitted form data is visible in the
URL.
 The length of a URL is limited to 2048 characters. So, user cannot send large data.
 Useful for form submissions where a user wants to bookmark the result.
 GET is good for non-secure data, like query strings.
134

POST METHOD
 POST appends the form data inside the body of the HTTP request. So, the submitted
form data is not visible to anyone.
 POST has no size limitations and can be used to send large amounts of data.
 Form submissions with POST cannot be bookmarked.
FORM ELEMENTS (OR) FROM INPUT TAGS
The primary element of forms which helps user to create various controls using its type
attributes. It is an independent tag which means it does not have closing tags. It supports 13
form controls with different structure.
Each input element with in the form is sent to the server as name/value pairs.

The input types are

1) Text 2) Password 3) Checkbox 4) Radio 5) Reset


6) Submit 7) Button 8) file 9) Image 10) select
11) Text Are a

TEXT BOX: A rectangular shaped field in which a user can enter text is considered as text box. A
text box is the type of input tag with name, size max length and values.

PASSWORD: The password input type creates a single line empty text box where the user can
enter text into it. It is similar to text fields. It display the text in the fields like stars (*) and dot (.)
that means it creates masked fields in passwords

CHECKBOXES: A checkbox is represented by square icon. This is used for multiple selections.
The user can select or deselect by clicking on it. A selected check box is usually show in dark
grey, and unselected check box is shown in light grey. It often used in series.

RADIO BUTTONS: Radio buttons are a group of buttons from which only one can be selected at
a time.
135

ACTION BUTTONS: - They are two types actions buttons they are submit and reset. Where the
user clicks on the submit button, the values that have been entered into the form are sent the
program that process the form. whereas reset button is to allow to clear all of the input
entered in the form and starts from the first.

SELECT: The select tag allow to choose any subset of items from a group, the items given in
select tag are usually rendered in the style of a pop-up menu. The items are indicated by using
<option> tag. Here in <option>tag the end tag is optional

TEXT AREA: The <text area> tag defines a multi-line text input control. A text area can hold an
unlimited number of characters, and with fixed-width font (i.e. courier) the area can be
specified by the cols and rows attributes.

PROGRAM
<html>
<form action = "sample.php" method = "post">
<b>Please tell us about Our website:</b><p>
<b>Name:</b><br>
<input type="text" name="name" size="15" maxlength="25" value=""><br>
<b>Email:</b><br>
<input type="text" name="email" size="15" maxlength="45" value=""><br>
<b>How frequently do you visit our site?:</b><br>
<select name="frequency">
<option value="">Site frequency:
<option value="0">My first Visit
<option value="1">1 time a month
<option value="2">Once in a month
<option value="3">Several times a week
<option value="4">Every day
</select><br>
<b>I frequently purchase the following products:</b><br>
136

<input type="checkbox" name="software" value="software">Softwares<br>


<input type="checkbox" name="hardware" value="hardware">Hardwares<br>
<input type="checkbox" name="stationary" value="stationary">Stationary<br>
<b>Our site's greatest asset is:</b><br>
<input type="radio" name="asset" value="products">Product selection<br>
<input type="radio" name="asset" value="design">Design<br>
<input type="radio" name="asset" value="service">Customer care<br>
<b>Comments:</b><br>
<textarea name="comments" rows="3" cols="40"></textarea><br>
<input type="submit" value="Submit!">
</form> </body> </html>

EXPLAIN HOW TO ACCESSING A FORMS IN PHP?


GET METHOD
To get form data, we need to use PHP super globals $_GET and $_POST. To retrieve data from
get request, we need to use $_GET, for post request $_POST.
 This is the built in PHP super global array variable that is used to get values submitted
via HTTP GET method.
 The array variable can be accessed from any script in the program; it has a global scope.
 This method displays the form values in the URL.
 It’s ideal for search engine forms as it allows the users to book mark the results.

<html><body>
<form action="welcome.php" method="get">
Name: <input type="text" name="name"/>
<input type="submit" value="visit"/>
</form>
</body></html>
welcome.php
137

<?php
$name=$_GET["name"]; //receiving name field value into $name variable
echo "Welcome, $name";
?>
In the above program, user enters his name and clicks on Visit button, then the form data is
added to URL and a request is sent to welcome.php program which is there in the webserver.
Upon receiving the request, program retrieves the user data from the URL and displays it on the
output.
Simple example to receive data from post request in PHP.
form.html
<form action="login.php" method="post">
<table>
<tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>
<tr><td>Email:</td><td> <input type="email" name="email"/></td></tr>
<tr><td colspan="2"><input type="submit" value="login"/> </td></tr>
</table>
</form>
login.php
<?php
$name=$_POST["name"];//receiving name field value into $name variable
$email=$_POST["email"];//receiving email field value into $email variable
echo "Welcome $name, your email address is: $email";
?>

EXPLAIN HOW TO COMBINING HTML AND PHP IN A SINGLE PAGE?


PHP code is normally mixed with HTML tags. PHP is an embedded language, meaning
that you can jump between raw HTML code and PHP without sacrificing readability. Such a
combination can be useful if you need to present the same form to the user more than once
138

PHP and HTML can be placed on the same page interchangeably by embedding PHP code. In
order to embed PHP code with HTML, the PHP must be set apart using PHP start and end tags.
The PHP tags tell the web server where the PHP code starts and ends. The PHP parser
recognizes three styles of start and end tags.

<?php
$num_to_guess = 42;
$message = "";
if ( ! isset( $guess ) )
$message = "Welcome to the guessing machine!";
elseif ( $guess > $num_to_guess )
$message = "$guess is too big! Try a smaller number";
elseif ( $guess < $num_to_guess )
$message = "$guess is too small! Try a larger number";
else // must be equivalent
$message = "Well done!";

?>
<html>
<head>
<title>Listing 9.9 A PHP number guessing script</title>
</head>
<body>
<h1>
<?php print $message ?>
</h1>
<form method="POST">
Type your guess here: <input type="text" name="guess">
</form> </body> </html>
139

DEFINE REDIRECTING THE USER FROM ONE PAGE TO ANOTHER IN PHP?


Redirection from one page to another in PHP is commonly achieved using the
Following two ways:
• Header Function in PHP
• JavaScript via PHP

Header Function in PHP:


The header function in PHP is used to redirect the user from current page to another page. It is
an in-built function that sends raw HTTP header to the client (user). You can simply use the PHP
header() function to redirect a user to a different page.
Syntax of header function
void header ( string $header [, bool $replace = TRUE [, int $http_response_code
]] )

JavaScript via PHP:


The windows.location object in JavaScript is used to get the current page address (URL) and to
redirect the browser to a new page. The window. Location object also contains the crucial
information about the page such as hostname, href, pathname, port etc.

DEFINE RDBMS?
RDBMS stands for Relational Database Management System. It is a program used to maintain a
relational database. It uses SQL (Structured Query Language) queries to access the data in the
database.
A relational database defines database relationships in the form of tables. The tables are
related to each other - based on data common to each.
Database is a collection of tables. Each table is a collection of related data entries,and it
consists of columns and rows. Column holds specific information about every record in the
table. Record (or row) is each individual entry that exists in a table
140

DEFINE SQL? EXPLAIN ABOUT COMMANDS IN SQL?


SQL is the standard language for dealing with Relational Databases. It is used to insert, search,
update, and delete database records. SQL is not a case sensitive language
 The data in a MySQL database are stored in tables which consists of columns and rows.
 MySQL is a database system that runs on a server.
 MySQL is ideal for both small and large applications.
 MySQL is very fast, reliable, and easy to use database system.It uses standard SQL
 MySQL compiles on a number of platforms.
COMMANDS IN SQL
o SELECT - extracts data from a database
o UPDATE - updates data in a database
o DELETE - deletes data from a database
o INSERT INTO - inserts new data into a database
o CREATE DATABASE - creates a new database
o ALTER DATABASE - modifies a database
o CREATE TABLE - creates a new table
o ALTER TABLE - modifies a table
o DROP TABLE - deletes a table
o CREATE INDEX - creates an index (search key)
o DROP INDEX - deletes an index

1) SELECT statement is used to select data from a database. The data returned is stored in a
result table, called the result-set.
Syntax: SELECT column1, column2, ... FROM table_name;
Here, column1, column2, are the field names of the table you want to select data from. If you
want to select all the fields available in the table,
Syntax: SELECT * FROM table_name;
141

2) UPDATE The statement is used to modify the existing records in a table.While updating
records in a table, WHERE clause is used in the UPDATE statement. The WHERE clause specifies
which record(s) that are to be updated
Syntax: UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;

3) DELETE The DELETE statement is used to delete existing records in a table. While deleting
records in a table, observe that WHERE clause is used in the DELETE statement. The WHERE
clause specifies which record(s) is to be deleted. If you omit the WHERE clause, all records in
the table will be deleted. Table schema remains in the database.
Syntax: DELETE FROM table_name WHERE condition;

4) INSERT INTO This statement is used to insert new records in a table. It is possible to write
the INSERT INTO statement in two ways:
1. Specify both the column names and the values to be inserted
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
2. If you are adding values for all the columns of the table, you do not need to specify the
column names in the SQL query.
INSERT INTO table_name VALUES (value1, value2, value3, ...);

5) CREATE DATABASE The CREATE DATABASE statement is used to create a new SQL database
Syntax: CREATE DATABASE database name;

6) ALTER DATABASE enables you to change the overall characteristics of a database.


Syntax: ALTER {DATABASE | SCHEMA} [db_name]
alter_specification ...
7) CREATE TABLE the statement is used to create a new table in a database. The column
parameters specify the names of the columns of the table. The datatype parameter specifies
the type of data the column can hold (e.g. varchar, integer, date, etc.).
Syntax: CREATE TABLE table_name ( column1 datatype, column2 datatype, );
142

8) ALTER TABLE statement is used to add, delete, or modify columns in an existing table. It is
also used to add and drop various constraints on an existing table.
ALTER TABLE - ADD Column
To add a new column in an existing table, use the following syntax:
ALTER TABLE table_name ADD column_name datatype;
ALTER TABLE - DROP COLUMN
ALTER TABLE table_name DROP COLUMN column_name;

9) DROP TABLE The statement is used to drop an existing table in a database.


Syntax: DROP TABLE table_name;

10) CREATE INDEX statement is used to create indexes in tables. Indexes are used to retrieve
data from the database more quickly than otherwise. The users cannot see the indexes, they
are just used to speed up searches/queries.
Syntax: CREATE INDEX index_name ON table_name (column1, column2, ...);

11) DROP INDEX the statement is used to delete an index in a table.


Syntax: ALTER TABLE table_name DROP INDEX index_name;

DEFINE HOW TO INSTALL MYSQL ON WINDOWS?

MySQL is one of the most popular relational database management software that is widely
used in today's industry. It provides multi-user access support with various storage engines.
 It allows us to implement database operations on tables, rows, columns, and indexes.
 It defines the database relationship in the form of tables (collection of rows and
columns), also known as relations.
 It provides the Referential Integrity between rows or columns of various tables.
 It allows us to updates the table indexes automatically.
143

Installing MySQL on Windows


Step 1: After downloading the setup, unzip it anywhere and double click the MSI installer .exe
file. It will give the following screen:
Step 2: In the next wizard, choose the Setup Type. There are several types available, and you
need to choose the appropriate option to install MySQL product and features. Here, we are
going to select the Full option and click on the Next button.
This option will install the following things: MySQL Server, MySQL Shell, MySQL Router, MySQL
Workbench, MySQL Connectors, documentation, samples and examples, and many more.
Step 3: Once we click on the Next button, it may give information about some features that
may fail to install on your system due to a lack of requirements. We can resolve them by
clicking on the Execute button that will install all requirements automatically or can skip them.
Now, click on the Next button.
Step 4: In the next wizard, we will see a dialog box that asks for our confirmation of a few
products not getting installed. Here, we have to click on the Yes button. After clicking on the
Yes button, we will see the list of the products which are going to be installed. So, if we need all
products, click on the Execute button.
Step 5: Once we click on the Execute button, it will download and install all the products. After
completing the installation, click on the Next button.
Step 6: In the next wizard, we need to configure the MySQL Server and Router. Here, I am not
going to configure the Router because there is no need to use it with MySQL. We are going to
show you how to configure the server only. Now, click on the Next button.
Step 7: As soon as you will click on the Next button, you can see the screen below. Here, we
have to configure the MySQL Server. Now, choose the Standalone MySQL Server/Classic MySQL
Replication option and click on Next. Here, you can also choose the InnoDB Cluster based on
your needs.
Step 8: In the next screen, the system will ask you to choose the Config Type and other
connectivity options. Here, we are going to select the Config Type as 'Development Machine'
and Connectivity as TCP/IP, and Port Number is 3306, then click on Next.
144

Step 9: Now, select the Authentication Method and click on Next. Here, I am going to select the
first option.
Step 10: The next screen will ask you to mention the MySQL Root Password. After filling the
password details, click on the Next button.
Step 11: The next screen will ask you to configure the Windows Service to start the server. Keep
the default setup and click on the Next button.
Step 12: In the next wizard, the system will ask you to apply the Server Configuration. If you
agree with this configuration, click on the Execute button.
Step 13: Once the configuration has completed, you will get the screen below. Now, click on the
Finish button to continue.
Step 14: In the next screen, you can see that the Product Configuration is completed. Keep the
default setting and click on the Next-> Finish button to complete the MySQL package
installation.
Step 15: In the next wizard, we can choose to configure the Router. So click on Next->Finish and
then click the Next button.
Step 16: In the next wizard, we will see the Connect to Server option. Here, we have to mention
the root password, which we had set in the previous steps. In this screen, it is also required to
check about the connection is successful or not by clicking on the Check button. If the
connection is successful, click on the Execute button. Now, the configuration is complete, click
on Next.
Step 17: In the next wizard, select the applied configurations and click on the Execute button.
Step 18: After completing the above step, we will get the following screen. Here, click on the
Finish button.
Step 19: Now, the MySQL installation is complete. Click on the Finish button.

EXPLAIN HOW TO CREATING DATABASE IN MYSQL


A database is used to store the collection of records in an organized form. It allows us to hold
the data into tables, rows, columns, and indexes to find the relevant information frequently.
We can access and manage the records through the database very easily.
145

MySQL implements a database as a directory that stores all files in the form of a table. It allows
us to create a database mainly in two ways:
1) MySQL Command Line Client
2) MySQL Workbench

MySQL Command Line Client


We can create a new database in MySQL by using the CREATE DATABASE statement
with the below syntax:
CREATE DATABASE [IF NOT EXISTS] database_name
[CHARACTER SET charset_name]
[COLLATE collation_name];
EXAMPLE : CREATE DATABASE testdb;
After that, use the SHOW CREATE DATABASE command to review the created database and
then MySQL returns the database name and the character set and collation of the database
EXAMPLE : SHOW CREATE DATABASE testdb;

MySQL Workbench
It is a visual database designing or GUI tool used to work with database architects,
developers, and Database Administrators. This visual tool supports SQL development, data
modeling, data migration, and comprehensive administration tools for server configuration,
user administration, backup, and many more. It allows us to create new physical data models,
E-R diagrams, and SQL development (run queries, etc.).

EXPLAIN HOW TO CONNECTION TO MY SQL? USING PHP SCRIPT?


The simplest way to connect with the MySQL database server using the PHP script is to use the
mysql_connect() function. This function needs five parameters and returns the MySQL link
identifier when the connection becomes successful. If the connection is failed, it returns FALSE.
Syntax
connection mysql_connect(server, user, passwordd, new_link, client_flag);
146

Server: It is the name of a host that runs the database server. By default, its value will be
lcalhost:3306.

User: It is the name of a user who accesses the database. If we will not specify this field, it
assumes the default value that will be the name of a user that owns the server process.

Password: It is the password of a user whose database you are going to access. If we will not
specify this field, it assumes the default value that will be an empty password.

New_link: If we make a second call with the same arguments in the mysql_connect() function,
MySQL does not establish a new connection. Instead, we will get the identifier of the already
opened database connection.

Client_flags: This parameter contains a combination of the below constants:


MYSQL_CLIENT_SSL: It uses SSL encryption.
MYSQL_CLIENT_COMPRESS: It uses a compression protocol.
MYSQL_CLIENT_IGNORE_SPACE: It provides space after function names.
MYSQL_CLIENT_INTERACTIVE: It provides a timeout before closing the connection.

If we want to disconnect from the MySQL database server, we can use another PHP
function named mysql_close(). It accepts only a single parameter that will be a connection
returned by the mysql_connect() function.

SYNTAX : bool mysql_close ( resource $link_identifier );


EXAMPLE
<html>
<head>
<title>MySQL Server Connection</title>
147

</head> <body>
<?php
$servername = 'localhost:3306';
$username = 'javatpoint';
$dbpass = 'jtp123';
$conn = mysql_connect($servername, $username, $password);
if(! $conn ) {
die('Connection failed: ' . mysql_error());
}
echo 'Connection is successful';
mysql_close($conn);
?>
</body>
</html>

EXPLAIN ABOUT WORKING WITH MYSQL DATA IN PHP?


To execute the basic SQL queries like Inserting, updating, deleting, and retrieving data, the
mysqli_query() function is used. For INSERT, UPDATE, and DELETE queries, no additional
scripting is required after the query has been executed because nothing is to be displayed as a
result (unless you want to). When using SELECT queries, you have a few options for displaying
the data retrieved by your query.
INSERTING DATA WITH PHP
The INSERT INTO statement is used to insert new rows in a database table.SQL query
using the INSERT INTO statement with appropriate values, after that we will execute this insert
query through passing it to the PHP mysqli_query() function to insert data in table.
Retrieving Data with PHP
PHP script can be written to retrieve that data from a database table. The SELECT statement is
used to select data from one or more tables. SELECT query is execute by mysqli_query()
function.
148

UNIT – V
WORKING WITH COOKIES AND USER SESSIONS

WHAT IS COOKIE? EXPLAIN THE USES OF COOKIES


A cookie is a small file with the maximum size of 4KB that the web server stores on the client
computer. Once a cookie has been set, all page requests that follow return the cookie name
and value.
A cookie can only be read from the domain that it has been issued from. For example, a cookie
set using the domain www.gsk.com cannot be read from the domain career.gsk.com.
Most of the websites on the internet display elements from other domains such as
advertising. The domains serving these elements can also set their own cookies. These are
known as third party cookies.
 A cookie created by a user can only
be visible to them. Other users
cannot see its value.
 Most web browsers have options for
disabling cookies, third party
cookies or both.
 If this is the case then PHP responds by passing the cookie token in the URL.
USES OF COOKES
 Http is a stateless protocol; cookies allow us to track the state of the application using
small files stored on the user’s computer. The path were the cookies are stored depends
on the browser.
 Internet Explorer usually stores them in Temporal Internet Files folder.
 Personalizing the user experience – this is achieved by allowing users to select their
preferences. The page requested that follow are personalized based on the set
preferences in the cookies.
 Tracking the pages visited by a user
149

EXPLAIN HOW TO CREATE A COOKIE WITH PHP


A cookie created by a user can only be visible to them. Other users cannot see its value
SYNTAX <?php
setcookie(cookie_name, cookie_value, [expiry_time], [cookie_path], [domain], [secure],
[httponly]);
?>
EXAMPLE <?php
setcookie("user_name", "Guru99", time()+ 60,'/'); // expires after 60 seconds
echo 'the cookie has been set for 60 seconds';
?>
 Php“setcookie” is the PHP function used to create the cookie.
 “cookie_name” is the name of the cookie that the server will use when retrieving its
value from the $_COOKIE array variable. It’s mandatory.
 “cookie_value” is the value of the cookie and its mandatory
 “[expiry_time]” is optional; it can be used to set the expiry time for the cookie such as 1
hour. The time is set using the PHP time() functions plus or minus a number of seconds
greater than 0 i.e. time() + 3600 for 1 hour.
 “[cookie_path]” is optional; it can be used to set the cookie path on the server. The
forward slash “/” means that the cookie will be made available on the entire domain.
Sub directories limit the cookie access to the subdomain.
 “[domain]” is optional, it can be used to define the cookie access hierarchy i.e.
www.cookiedomain.com means entire domain while www.sub.cookiedomain.com limits
the cookie access to www.sub.cookiedomain.com and its sub domains. Note it’s possible
to have a subdomain of a subdomain as long as the total characters do not exceed 253
characters.
 “[secure]” is optional, the default is false. It is used to determine whether the cookie is
sent via https if it is set to true or http if it is set to false.
 “[Httponly]” is optional. If it is set to true, then only client side scripting languages i.e.
JavaScript cannot access them.
150

EXPLAIN ABOUT RETRIEVING THE COOKIE AND MODIFY, DELETE A COOKIE?

$_COOKIE is a PHP built in superglobal variable. It is an array type and stores the names and
values of all the set cookies. The number of values that the $_COOKIE array can contain
depends on the memory size set in php.ini. The default value is 1GB.
EXAMPLE
<?php
print_r($_COOKIE); //output the contents of the cookie array variable
?>
Modify a Cookie Value
To modify a cookie, just set (again) the cookie using the setcookie() function.
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date to the past time. i.e.,
negative number.

WHAT IS A SESSION? AND USE OF SEESIONS IN PHP?

 A session is a global variable stored on the server.


 Each session is assigned a unique id which is used to retrieve stored values.
 Whenever a session is created, a cookie containing the unique session id is stored on the
user’s computer and returned with every request to the server. If the client browser
does not support cookies, the unique php session id is displayed in the URL
 Sessions have the capacity to store relatively large data compared to cookies.
 The session values are automatically deleted when the browser is closed. If you want to
store the values permanently, then you should store them in the database.
 Just like the $_COOKIE array variable, session variables are stored in the $_SESSION
array variable. Just like cookies, the session must be started before any HTML tags.
151

USE OF SESSIONS
 You want to store important information such as the user id more securely on the server
where malicious users cannot temper with them.
 You want to pass values from one page to another.
 You want the alternative to cookies on browsers that do not support cookies.
 You want to store global variables in an efficient and more secure way compared to
passing them in the URL
 You are developing an application such as a shopping cart that has to temporary store
information with a capacity larger than 4KB.

EXPLAIN HOW TO CREATING A SESSION, DESTROYING SESSION VARIBALE IN PHP?


A session begins by using the session_start function. Each session variable is stored and retrieved
from the global variable named _SESSION. Session variable are then created as follows:
SYNTAX : $_SESSION[identifier] = value;
EXAMPLE
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["name"] = "Educative";
$_SESSION["ID"] = "123";
?>
</body>
</html>
152

DESTROYING SESSION VARIABLE


A session can be using the session_unset and session_destroy functions in PHP.
The session_unset function removes all session variables.
The session_destroy function destroys the session.
EXAMPLE:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>

HOW WE ARE USING SESSIONS IN AN ENVIRONEMENT WITH REGISTERED USERS?


Working with Registered Users
Suppose that you've created an online community, or a portal, or some other type of
application that users can "join." The process usually involves a registration form, where the
user creates a username and password and completes an identification profile. From that point
forward, each time a registered user logs in to the system, you can grab the user's identification
information and store it in the user's session.

The items you decide to store in the user's session should be those items you can imagine using
quite a bit and that would be inefficient to continually extract from the database. For example,
153

suppose that you have created a portal in which users are assigned a certain level, such as
administrator, registered user, anonymous guest, and so forth. Within your display modules,
you would always want to check to verify that the user accessing the module has the proper
permissions to do so. Thus, "user level" would be an example of a value stored in the user's
session, so that the authentication script used in the display of the requested module only has
to check a session variable there would be no need to connect to, select, and query the
database.

Working with User Preferences


If you were feeling adventurous in the design phase of a user-based application, you might have
built a system in which registered users could set specific preferences that would affect the way
they viewed your site. For example, you may allow your users to select from a predetermined
color scheme, font type and size, and so forth. Or, you may allow users to turn "off" (or "on")
the visibility of certain content groupings.

Each of those functional elements could be stored in a session. When the user logs in, the
application would load all relevant values into the user's session and would react accordingly
for each subsequently requested page. Should the user decide to change her preferences, she
could do so while logged in you could even pre populate a "preferences" form based on the
items stored in the session rather than going back to the database to retrieve them. If the user
changes any preferences while she is logged in, simply replace the value stored in the
$_SESSION super global with the new selection no need to force the user to log out and then
log back in again.

You might also like