You are on page 1of 257

Internet Programming

Sept 2012
Jimma University

Table of Contents
Unit One: Introduction to Web Pages ............................................................................................. 6
1. Architecture of the Internet and WWW ..................................................................................... 6
1.1

The Internet ...................................................................................................................... 6

1.2

What is WWW and How Does it work?............................................................................ 8

1.3

Standardization ................................................................................................................ 9

2. Protocols ................................................................................................................................... 12
1.1

What is Internet Protocol? ............................................................................................. 12

1.2

HTTP ............................................................................................................................... 12

Unit Two: HTML Tags..................................................................................................................... 14


1. Basic HTML TAGS ....................................................................................................................... 14
1.1

HTML: Hypertext Markup Language .............................................................................. 14

1.2

HTML, HEAD, TITILE and BODY Tags ............................................................................... 15

1.3

Creating Links ................................................................................................................. 16

1.4

Working with Colors ....................................................................................................... 17

1.5

HTML Text Formatting Tags ............................................................................................ 17

1.6

Working with Graphics and Images................................................................................ 18

2. Tables and Lists ......................................................................................................................... 19


2.1 Creating Tables .................................................................................................................... 19
2.2 Using Ordered and Unordered List ..................................................................................... 21
3. Frames ....................................................................................................................................... 22
3.1 Working with Frames .......................................................................................................... 22
1. What is the advantage of using frames ............................................................................. 23
3.2 Nested Frames .................................................................................................................... 23
4. HTML Forms .............................................................................................................................. 24
1.7

Building HTML Forms ..................................................................................................... 24

1.8

Working with Text Fields and Passwords ....................................................................... 24

1.9

Using Buttons, Checkboxes and Selection Lists.............................................................. 25

1.10

Linking HTML Forms with PHP Scripts ........................................................................ 27

1.11

Automating Processing: Info Forms and Emails ......................................................... 27

Unit Three: Cascading Style Sheets............................................................................................... 28


2

1. CSS Basics .............................................................................................................................. 29


1.1 Introduction to CSS......................................................................................................... 29
1.2 CSS Syntax ..................................................................................................................... 30
1.3 Linking CSS to HTML ................................................................................................... 31
2. CSS Styling ............................................................................................................................. 32
2.1 Styling Backgrounds ....................................................................................................... 32
2.2 Styling Text ..................................................................................................................... 34
2.3 Styling Fonts ................................................................................................................... 38
2.4 Styling Links ................................................................................................................... 42
2.5 Styling Lists .................................................................................................................... 42
2.6 Styling Tables .................................................................................................................. 43
2.7 CSS Class and ID ............................................................................................................ 48
3. CSS Box Model ...................................................................................................................... 50
3.1 CSS Box Model ................................................................................................................ 50
3.2 CSS Border ....................................................................................................................... 51
3.3 CSS Margin ...................................................................................................................... 54
3.4 CSS Padding ..................................................................................................................... 55
Unit Four: JavaScript Programming .............................................................................................. 56
1. Introduction to JavaScript ..................................................................................................... 56
1.1 Introduction .................................................................................................................... 56
1.2 Running the JavaScript .................................................................................................... 56
1.3 Working with Variables and Data.................................................................................... 59
1.4 Operators and Expressions ............................................................................................. 62
1.5 Working with Conditional Statements ............................................................................ 67
2. Arrays, loops, and Functions ................................................................................................. 69
2.1 Using Arrays .................................................................................................................... 69
2.2 Working with Loops ........................................................................................................ 73
2.3 JavaScript Functions ........................................................................................................ 76
3. JavaScript Objects and Events ............................................................................................... 78
3.1 Working with JavaScript Objects..................................................................................... 78
3.2 Managing Events ............................................................................................................. 88
3.3 Form Processing and Validation ...................................................................................... 90
3

3.3.1 Accessing Form and Form Elements ............................................................................ 90


3.3.2 Form Validation ............................................................................................................ 93
Unit Five: Dynamicity in HTML: DHTML and DOM ....................................................................... 96
1. DOM ...................................................................................................................................... 96
1.1 Introduction to DOM....................................................................................................... 96
1.2 DOM Nodes and Node Tree ............................................................................................ 96
1.3 DOM Properties and Methods ........................................................................................ 98
1.4 DOM Node Access........................................................................................................... 99
1.5 DOM Events................................................................................................................... 101
2. Dynamic HTML(DHTML)...................................................................................................... 102
2.1 Introduction to DHTML ................................................................................................. 102
2.2 DHTML JavaScript.......................................................................................................... 102
2.3 DHTML DOM ................................................................................................................. 103
2.4 DHTML CSS .................................................................................................................... 104
Unit Six: Server Side Programming ............................................................................................. 106
1. Server Side Programming with CGI ................................................................................... 106
Static vs Dynamic Pages and Client side vs Server Side Scripting .................................... 106
What is CGI?....................................................................................................................... 107
The Hello world Test ........................................................................................................... 108
Getting Data and Other Information ................................................................................... 109
Processing Forms .................................................................................................................112
Data Parsing .........................................................................................................................114
Security ............................................................................................................................... 121
2. Server Side Programming with PHP .................................................................................... 122
1.1 Introduction to PHP ...................................................................................................... 122
1.2 Working with Variables ................................................................................................. 127
1.3 Using Operators ............................................................................................................ 130
1.4 Conditional Statements................................................................................................. 134
1.5 Using Loops ................................................................................................................... 137
1.6 Arrays ............................................................................................................................ 141
1.7 Functions in PHP ........................................................................................................... 153
4

3. Processing Data with PHP ................................................................................................... 156


2.1 Working with Forms ...................................................................................................... 156
2.2 Database Programming................................................................................................. 157
4. Advanced concepts in PHP .................................................................................................. 167
3.1 Classes in PHP ............................................................................................................... 167
3.2 Working with Files ......................................................................................................... 170
3.3 Cookies and Sessions .................................................................................................... 183
Unit Seven: Advanced Internet Programming ............................................................................ 189
7.1 Java Applets ...................................................................................................................... 189
7.2 The Extensible Markup Language(XML)......................................................................... 205
7.3 Java Server Page (JSP)...................................................................................................... 206
Predefined Variables ........................................................................................................... 245
Actions ................................................................................................................................ 246
Connecting to Database ...................................................................................................... 247

Unit One: Introduction to Web Pages


1. Architecture of the Internet and WWW
1.1 The Internet
What is the first thing that comes to your mind when you think of the Internet? When the term Internet
is considered one could considerer many things. But in a simple term, Internet is just a large number of
computers connected together in such a way that communication between them is both reliable and
fast. Phrased in this way, it is wholly unremarkable. But the Internet is also the people who use it, to
communicate and to share information, even to build relationships and communities. It's a culture that
has grown within a virtual space, and that has permeated many aspects of our everyday lives. The
Internet has become an industry in its own respect.
The Internet was the result of some visionary thinking by people in the early 1960s who saw great
potential value in allowing computers to share information on research and development in scientific
and military fields. J.C.R. Licklider of MIT (Massachusetts Institute of Technology), first proposed a global
network of computers in 1962, and moved over to the Defense Advanced Research Projects Agency
(DARPA) in late 1962 to head the work to develop it. Leonard Kleinrock of MIT and later UCLA
(University of California, Los Angeles) developed the theory of packet switching, which was to form the
basis of Internet connections. Lawrence Roberts of MIT connected a Massachusetts computer with a
California computer in 1965 over dial-up telephone lines. It showed the feasibility of wide area
networking, but also showed that the telephone line's circuit switching was inadequate. Kleinrock's
packet switching theory was confirmed. Roberts moved over to DARPA in 1966 and developed his plan
for ARPANET (Advanced Research Projects Agency Network). These visionaries and many more left
unnamed here are the real founders of the Internet.
Currently, the Internet, as a network of networks, consists of many computers, called servers or hosts,
which are linked by communication lines. These hosts are located in different part of the world and
connect millions of people as of now. The administrators of these hosts may make information or
software stored on them publically available, so that others can view, download or use the data. Figure
one can clearly depict the growth of the Internet in terms of growth in host/ server computers.
Another important thing that has contributed for growth of Internet is ownership. Who do you think
own the Internet? Until recently, nobody owns the Internet. The reason, although the Internet was
made in the U.S.A., its unique design transformed it into are source for innovation that anyone in the
world could use. Thought the Internet is not owned by anyone, its backbone: servers and Internet
Service Providers (ISP) are owned by private as well government organizations. This has fostered
democracy and elevates economic growth worldwide.

Figure 1.1 The growth of Internet


The Internet has, in a short space of time, become fundamental to the global economy. More than a
billion people worldwide use it, both at work and in their social lives. Over the past three decades it has
grown from an experimental research network and now underpins a range of new economic activities:
E-commerce, E-business as well as activities and infrastructures that support our economies. In addition,
Internet has revolutionized the entertainment, education, and other spheres of business.
Generally, the functionalities of the Internet in many business areas is manifested through its services
listed below:
World Wide Web (WWW),
Electronic mail,
File Transfer
Discussion Groups
Usenet (News Group),
Internet Chat,

Search Services

Practice 1.1
1. What are the major components of the Internet?
2. What are the major functionalities of the Internet in todays business environment?

1.2 What is WWW and How Does it work?


The Web consists of many millions of internet-connected computers, each with information on them
that their owner has decided to share. These documents can be formed of anything from plain text to
multimedia or even 3D objects. These computers, called servers, deliver this information over the
Internet to client computers (such as your PC at office or home) using a protocol. The protocol just
provides a mechanism that allows a client to request a document, and a server to send that document.
As the web has become more and more popular, its capabilities have increased to include such things as
graphics, animations, scripts and even complete computer programs, all embedded into the pages of the
documents. Essentially, the web is the easiest to use from the entire internet toolkit: this is partly why it
has become so popular. Various mechanisms allow the viewer to move around (navigate) the document
easily.
The web has become the most predominant of the new digital media, and has provided the mechanism
for many new forms of publishing. There are many reasons why this is so;

As the accessing of information stored on computers has become more widely accepted
and used, the number of methods, and hence the number of computer applications
needed, has multiplied.
The web provides a way of integrating these methods and applications, using a common
interface to allow easy access to any information stored on any computer
The language of the web, was specifically designed to be easy to learn, and was based
around the concept of marking text functionally, to ensure a wide authorship. As it has
grown, the web has moved away from this concept, becoming more complex and more
graphical than originally envisioned. Though, the core functions still lie beneath all the
complexity, and allow more or less anyone to write their own web pages quickly and easily,
with a minimal set of software tools.
One of the most powerful features of the web is the ability to link documents together
using hyperlinks. On clicking a hyperlink (usually underlined), the browser tries to access
the linked document, providing an almost instantaneous cross-referencing system. This
creates a non-linear orm of text, known as hypertext. Web pages can also contain
multimedia content that can also be hyperlinked, termed hypermedia.

The goal of a web server is to serve information to anyone who requests it; the web pages stored on the
server are made publically available. It's possible to restrict access to certain parts of the Internet, or to
those who have usernames and passwords, but it's not usual: most web sites are open for all to read
their contents. The use of the web as a public space to provoke discussion or to provide otherwise
difficult-to-publish information has been instrumental in its popularity. Examples of this range from the
subversive (political groups publishing propaganda), to the more mundane (businesses publishing timecritical data such as stock information or market prices).

With the rise of commerce on the Web, and the recognition of the market value that certain types of
information can command, parts of the Web have been locked away, hidden behind corporate intranets
and firewalls, sites with passwords, and subscription services.
A high proportion of this Deep or Invisible Web is hidden from view, whether from you and I, or from
search engines. Estimates of the size of this deep Web vary, but most agree that it is many times the size
of the Surface Web, i.e. the web that is open and accessible to the public.
The backbone of the web is the network of web servers across the world. These are really just
computers that have a particular type of software running on them: software: web browser, which
knows how to speak the protocol and knows which information stored on the computer, should be
made accessible through the web. It's possible to turn almost any computer into a web server by
downloading and installing server software (Example: Apache)
The web browser is also particularly clever in the way it displays what it retrieves. Web pages are
written in a certain language, and the browser knows how to display these correctly, whether you have
a huge flat screen or a tiny screen on a handheld device or phone. The language the page has been built
gives the browser hints on how to display things, and the browser decides the final layout itself.

Figure 1.2 How WWW works: retrieving a web page

Practice 1.2
1. What are the steps in which information is retrieved from a web?
2. What is the role of protocols in communication of information in the web?

1.3 Standardization
The nature of WWW, which is the connection of different type of computers around the world, would
have created chaos, if it is not for different standards that guild the web developers and owners what to

comply in their websites. The major standards in WWW are the language used to build the web pages:
HTML (Hypertext Markup Language) and the processes of giving address for web pages.

HTML
HTML is a standard language, which should mean that all web browsers interpret it in exactly the same
way. The standard is decided upon by a large body of volunteers and experts, who oversee its progress
and guide its development. This body is managed by the World Wide Web Consortium (the W3C,
http://www.w3.org/), and currently recommends the use of HTML4.01, its latest standard).
One of the reasons that the web is so widely used is that the standardization of HTML has allowed many
developers to produce browser software, for many types of computer. The original definition of HTML
was written in a language called SGML (Standard Generalized Markup Language), designed to allow
computers to read language definitions easily. This means that HTML is defined very precisely, which is
why you need to be equally precise when writing your web pages. If a web page is written in such a way
that it conforms to the SGML definition, then it should be readable by all browsers conforming to that
definition.
The next generation of HTML, called XHTML, is defined in a cut down version of SGML called XML
(eXtensible Markup Language). XHTML is stricter in its definition of tags (has strict syntax rules), but it is
much more flexible, in that it is much easier for computers to interpret. When a computer reads any
kind of document, it must follow a strict pattern or syntax, and the stricter this is, the easier the
computer finds the interpretation, even though we as humans may find it difficult to write so accurately.
Tools such as Dreamweaver and dedicated XML editors make writing this stricter form of HTML much
easier.

Web Page Address


Very similar to the postal address system, Internet addressing is a systematic way to identify people,
computer and the Internet resources. On the Internet, the term address is used loosely. Address can
mean many different things from an electronic mail address to a URL.
When a new site is put online it has a specific network address that looks something like
207.70.128.240. In order to make the site easier to remember, a unique name is correlated with the
number.
IP Address - An IP address is a unique number that identifies computer on the Internet; every computer
directly connected to the Internet has one. An IP address consists of four numbers separated by
periods. Each number must be between 0 and 255.

10

Domain Name - Most computers on the Internet have a domain name. A domain name is the text name
corresponding to the numeric IP address of a computer on the Internet. A domain name must be
unique. Internet users access your website using your domain name.
A domain name always contains two or more components separated by periods, called dots. Some
examples of domain names are: ibm.com, nasa.gov, aau.edu.telecom.net.et etc. Once a domain name
has been established, sub-domains can be created within the domain. For example, the domain name
for a large company could be vni.com and within this domain, sub-domains can be created for each of
the companys regional offices.
The portion of a domain name after the dot describes the type of organization holding that name. The
major categories are:

Com: commercial entities


Edu: educational institutions
Net: organizations directly involved in the Internet operations, such as network providers and
network information centers.
Org: miscellaneous organizations that do not fit any other category, such as non-profit groups
Gov: united states federal government entities
Mil: united states military
Country codes: a two-letter abbreviation for a particular country for example et for Ethiopia, uk
for united kingdom, or fr for France.

The domain names and IP address are what facilitate the information searching process. The key to
accessing all this information is the URI: Uniform Resource Identifier. Each web page has a unique
address, which is used by the URL: Uniform Resource Locator, which tells the client/browser how to
access the page.
For example: http://piglet.exeter.ac.uk/pallas/index.html, the parts of the URL could be decomposed as
follows.
The parts of a URL

http: the method of delivery (ftp, file, etc.). The :// is important to distinguish this from the
server name that follows
piglet.ex.ac.uk: the server computer the document is stored on. This could also be referred to by
its IP number, e.g. 144.173.116.100. Breaking this down further:
piglet the host: the name of the individual computer/ server. These are usually decided upon by
the organization concerned.
exeter: the organisation :exeter or ex (domain name = exeter.ac.uk)
ac: the organisation type: ac or edu for academic sites,
uk: the country code uk, fr, et, etc.

11

pallas: the directory/folder


index.html: the file itself

Practice 1.3

1. What is the difference between IP address and domain name?


2. Why do we need standardization?

2. Protocols
1.1 What is Internet Protocol?
The Internet protocols are the worlds most popular open-system (nonproprietary) protocol suite
because they can be used to communicate across any set of interconnected networks and are equally
well suited for LAN and WAN communications. The Internet protocols consist of a suite of
communication protocols, of which the two best known are the Transmission Control Protocol (TCP) and
the Internet Protocol (IP). The Internet protocol suite not only includes lower layer protocols (such as
TCP and IP), but it also specifies common applications such as electronic mail, terminal emulation, and
file transfer. In addition, it includes different application level protocols like Small Mail Transfer Protocol
(SMTP), Network News Transfer Protocol (NNTP), File Transfer Protocol (FTP), Dynamic Host
Configuration Protocol (DHCP) and Hypertext Transfer Protocol (HTTP)

1.2 HTTP
The Hypertext Transfer Protocol (HTTP) is an application level protocol for distributed, collaborative,
hypermedia information systems. HTTP has been in use by the World Wide Web global information
initiative since 1990. The first version of HTTP, referred to as HTTP/0.9, was a simple protocol for raw
data transfer across the Internet. HTTP/1.0, as defined by RFC (Request For Comments) 1945, improved
the protocol by allowing messages to be in the format of Multipurpose Internet Mail Extension (MIME)
like messages, containing meta-information about the data transferred and modifiers on the
request/response semantics. While HTTP/1.0 has provided with many capabilities it does not take in to
consideration the need for persistent connections, or virtual hosts. This has necessitated a protocol
version change. This specification defines the protocol referred to as HTTP/1.1. This protocol includes
more strict requirements than HTTP/1.0 in order to ensure reliable implementation of its features.
Practical information systems require more functionality than simple retrieval, including search, front
end update, and explanation. HTTP allows an open-ended set of methods and headers that indicate the
purpose of a request. It builds on the discipline of reference provided by the Uniform Resource Identifier
(URI), as a location (URL: Uniform Resource Locator) or name (URN: Uniform Resource Name) [20], for

12

indicating the resource to which a method is to be applied. HTTP is also used as a generic protocol for
communication between user agents and proxies/gateways to other Internet systems, including those
supported by the SMTP, NNTP, and FTP protocols. In this way, HTTP allows basic hypermedia access to
resources available from diverse applications.
The HTTP protocol is a request/response protocol. A client sends a request to the server in the form of a
request method, URI, and protocol version, followed by possible body content over a connection with a
server. The server responds with a status line, including the messages protocol version and a success or
error code, followed by a MIME like message containing server information, entity meta-information,
and possible entity body content. Most HTTP communication is initiated by a user agent and consists of
a request to be applied to a resource on some origin server. In the simplest case, this may be
accomplished via a single connection (v) between the user agent (UA) and the origin server (O).
Request chain ------------------------>
UA -------------------v------------------- O
<----------------------- response chain

Practice 1.4
1. What is the relationship between Internet Protocol suite and HTTP?
2. What is the general purpose of HTTP?

Generally, the HHTP request line includes HTTP version, request method and request URL while
the response line include HTTP version, status code: a three digit number and status description
which has textual explanation for the status code.
HTTP request line

HTTP response line

HTTP Version (eg. HTTP/1.1, HTTp/1.0)

HTTP Version (eg. HTTP/1.1, HTTp/1.0)

Request method (eg. GET, POST, DELETE, Status code (eg. 100, 200)
TRACE, PATCH)
Request URL

Status Description (eg. Ok and Success


(description for status code 100 and 200
respectively)

Table 1.1 Summer of the structure of HTTP

13

Unit Two: HTML Tags


1. Basic HTML TAGS
1.1 HTML: Hypertext Markup Language
HTML, which stands for Hypertext Markup Language, is the predominant markup language for web
pages. A markup language is a set of markup tags, and HTML uses markup tags to describe web pages.
HTML is written in the form of HTML elements consisting of HTML tags surrounded by angle brackets
(e.g. <html>) within the web page content. HTML tags normally come in pairs like <b> and </b>. The first
tag in a pair is the start tag, the second tag is the end tag; you can also refer to them as opening
tags and closing tags.
HTML elements form the building blocks of all websites. HTML 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
webpage. HTML can also be used to include Cascading Style Sheets (CSS) to define the appearance and
layout of text.
While a web developer, someone like you, uses the HTML tags to create the web page, software is
required to interpret tour code and display the information that you are trying to display: the software
could be any web browser software. The purpose of a web browser is to read HTML documents and
display them as web pages. The browser does not display the HTML tags, but uses the tags to interpret
the content of the page
HTML document is created using a simple text editor like Notepad or WordPad or any other text editor.
Notepad can edit HTML, and at the same time you are able to view what you edit, in a web browser.
Below, are step by step instructions on how to get Notepad to create an HTML document.
Step 1: The First step is to open up a new file using Notepad. To do this, open Notepad. If you can't find
notepad, click the Start menu, select Run and type in Notepad or click the Start menu, select All
programs/ Programs then you could find a Notepad in the Accessories subsection.
Step 2: The next step will be writing the HTML tags in the new Notepad file. After completing this task
save you file with a file extension of html or htm. For example, if you want to save your file with a file
name of exercise, you should write exercise.html.
Step 3: The third and final step is to set your computer up so that when you update the HTML document
in notepad, you can quickly see the changes you made to your page in your browser. To do this, first
open up the HTML file in Notepad. Then, double-click on the HTML file itself. You should now have two
windows open: one being Notepad, and the other your web browser. Now, when you type HTML in

14

Notepad, you can quickly view the results by going to the browser and hitting refresh.

1.2 HTML, HEAD, TITILE and BODY Tags


As you can remember from the previous section HTML code and page structure
HTML code can be written in plain text editor or by using any advance editor. Whatever the use of the
text editor the structure of an HTML code is similar. Let us first see how a plain html code looks like.
<html>
<head>
<title>Page title here </title>
</head>
<body>
Our body content here
</body>
</html>
The total code is divided into two parts and both the parts are kept inside <html> tags. Our page should
start with <html> and should end with </html>. The first part inside this html tags is head tag and it
starts with <head> and ends with </head>, after this the second part starts with <body> and ends with
</body> tag. Inside the body tag we keep all our content which we want to display to our web page
users. Whatever we place in this part of the page will be displayed by the browser to the web users. Lets
see both pars in detail.
<HEAD> </HEAD>
The web page should have only one starting head tag and one ending head tag. The head tag starts with
<head> and ends with </head>. The text or tags what goes inside the head tags will not be displayed in
the browser window. Inside this tag we keep all the meta keyword tags used for search engines. One of
the important tags is title: <titile>/</title> tag also kept inside this area. Title tags are displayed at the
top left side of the browser window. Title tags are also important for our search engine point of view.
We should keep most important keywords inside the title tag. If we are adding any JavaScript code here
then that will be loaded when the browser opens the page.
<BODY> </BODY>
This is where we will place our content for our visitors. What we place here will be displayed to our
visitors. So go on filling this place with your content to show to the web user. The style and other
formatting of the text and what you could do to fill the content of the web page will discuss in different
sections. Close our page with </HTML> tag.
HTML Attributes: Attributes provide additional information about HTML elements.

15

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"

Example: the background color of HTML document can be changed using bgcolor attribute of the
<body> tag.
<body bgcolor=green>, while bgcolor is the name of attrbuite, green is the value.

1.3 Creating Links


A hyperlink (or link) is a word, group of words, or image that you can click on to jump to a new document
or a new section within the current document. When you move the cursor over a link in a Web page, the
arrow will turn into a little hand.
Links are specified in HTML using the <a> tag. The <a> tag can be used in two ways:
1. To create a link to another document, by using the href attribute
2. To create a bookmark inside a document, by using the name attribute
HTML Links, the href Attribute: A link in HTML is always composed of two parts, the clickable part (the
link text) and the URL (Uniform Resource Locator, the destination site, page or resource). Here is an
example:

Clickable part (link text): Yahoo mail


URL: http://mail.yahoo.com

The HTML code for this link is: <a href= http://mail.yahoo.com> Yahoo mail</a>
HTML Links, the name Attribute: The name attribute specifies the name of an anchor. The name
attribute is used to create a bookmark inside an HTML document. Bookmarks are not displayed in any
special way. They are invisible to the reader.
Example:
A named anchor inside an HTML document: <a name="example">Sample Examples</a>
Create a link to the "Sample Examples" inside the same document: <a href="# example">Go to Sample

16

Example</a>

1.4 Working with Colors


In HTML colors can used to enhance the way your web page looks like. It can be used to change the
background of your webpage, the color of your text or the content of a table. While choosing the right
type of color is your responsibility, HTML provides you with many options to mingle with. HTML colors
are defined using a hexadecimal notation (HEX) for the combination of Red, Green, and Blue color values
(RGB). The lowest value that can be given to one of the light sources is 0 (in HEX: 00). The highest value is
255 (in HEX: FF). HEX values are specified as 3 pairs of two-digit numbers, starting with a # sign.
For example:
Red = #FF0000
Green = #00FF00
Blue = #0000FF
Cyan (blue and green) = #00FFFF
Magenta (red and blue) = #FF00FF
Yellow (red and green) = #FFFF00
Both <body bgcolor=red> and <body bgcolor=#FF0000> will change the background color in to red.

1.5 HTML Text Formatting Tags


There are options if one wants to create a text in HTML. Lets see some of the tags than can be used to
create text information.

HTML Headings
Headings are defined with the <h1> to <h6> tags. <h1> defines the largest heading. <h6> defines the
smallest heading.
Example:
<h1>This is a heading one </h1>
<h2>This is a heading two</h2>
<h3>This is a heading</h3>

HTML Paragraphs
Paragraphs are defined with the <p> tag.
Example:

17

<p>This is a paragraph</p>
<p>This is another paragraph</p>

Both of the above tags will enforce a new line whenever you write the tag. If you want additional new
line you can use the break tag (<br>: break tag does not have an end tag)
While the paragraph and heading tags are used to create texts, there are many other tags that you can
use to enhance and change the look of the text. The following are some examples.

The Tag

Meaning of Tag

<small>.. Define small text


<b>
.
Makes text bold
<em>........... Define emphasize text
<i>
.. .
Italicizes text
<big>. Define big text
<Strong>.. Define strong text
<sub>
.. Define subscripted text
<sup>
.. Define superscripted text

In addition to the above tags HTML has different facilities concerning the usage of special characters and
reserved words. Some of these tags are listed below.

Tag
<abbr>
<acronym>
<bdo>
<q>
<cite>
<dfn>
&#38; or &amp;
&apos; or &#39;
&gt; or &#62;
&cent; or &#162;
&copy; or &#169;

Description
Defines an abbreviation
Defines an acronym
Defines the text direction
Defines a short quotation
Defines a citation
Defines a definition term
Defines character &
Defines character
Defines character >
Defines character
Defines character

1.6 Working with Graphics and Images


In HTML, images are defined with the <img> tag. The <img> tag is empty, which means that it contains
attributes only, and has no closing tag. To display an image on a page, you need to use the src attribute.
Src stands for "source". The value of the src attribute is the URL of the image you want to display.

18

Syntax for defining an image: <img src="url" alt="Alternative Text"/>


The required alt attribute specifies an alternate text for an image, if the image cannot be displayed. The
value of the alt attribute is an author defined text. The alt attribute provides alternative information for
an image if a user for some reason cannot view it (because of slow connection, an error in the src
attribute)
Example: <img src="boat.gif" alt="Big Boat" />
To define the height and width of the image, rather than letting the browser compute the size, use
the height and width attributes.
Example: <img src=sunset.jpg height=50, width=100>
Note: Loading images take time, so my best advice is: Use images carefully.

2. Tables and Lists


2.1 Creating Tables
Tables are defined with the <table> tag. A table is divided into rows (with the <tr> tag), and each row is
divided into data cells (with the <td> tag). td stands for "table data," and holds the content of a data cell.
A <td> tag can contain text, links, images, lists, forms, other tables, etc. Header information in a table is
defined with the <th> tag. The text in a th element will be bold and centered.
Example:
<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
HTML code above looks in a browser:

19

Header 1

Header 2

row 1, cell 1 row 1, cell 2


row 2, cell 1 row 2, cell 2
Note: If you do not specify a border attribute, the table will be displayed without borders. Sometimes
this can be useful, but most of the time, we want the borders to show.

Attributes of table: the attributes of a table will be applied on the whole table element which include
one or more rows (<tr>), header cells (<th>) or data cells (<td>)
Attribute
align

bgcolor

border
cellpadding

Value
left
center
right
rgb(x,x,x)
#xxxxxx
colorname
pixels
pixels

cellspacing
width

pixels
pixels
%
Table 2.1 attributes of table

Description
Specifies the alignment of a table according to
surrounding text
Specifies the background color for a table

Specifies the width of the borders around a table


Specifies the space between the cell wall and the cell
content
Specifies the space between cells
Specifies the width of a table

Attributes of rows and cells: this attributes will be applicable only to the header cell or the data cell if
it is used with <th> or <td> tag while it will affect the whole content of the row if it is used by the <tr>
tag.
Attribute
align

bgcolor

colspan
height

Value
left
right
center
justify
char
rgb(x,x,x)
#xxxxxx
colorname
number
pixels

Description
Aligns the content in a cell

Specifies a background color for a cell

Specifies the number of columns a cell should span

20

nowrap
rowspan
width
valign

%
nowrap
number
pixels
%
top
middle
bottom

Sets the height of a cell


Specifies that the content inside a cell should not wrap
Sets the number of rows a cell should span
Deprecated. Use
styles
instead.
Specifies the width of a cell
Vertical aligns the content in a table row

Table 2.2 attributes of rows and cells


Practice 2.1
1. Create a table that displays an exam schedule for your department?

2.2 Using Ordered and Unordered List


An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.
The list items are marked with bullets (typically small black circles). The type attribute can be used to
specifies the style of the bullet points of the list items, its value includes disc, square and circle
Example:
<ul>
<li>Banana</li>
<li>Orange</li>
</ul>
How the HTML code above looks in a browser:
Banana
Orange
An ordered list starts with the <ol> tag. Each list item starts with the <li> tag. The list items are marked
with numbers.
Example:
<ol>
<li>Coffee</li>
<li>Milk</li>
</ol>

How the HTML code above looks in a browser:


1. Banana

21

2. Orange
Practice 2.2
1. Write a code that displays the courses that you are currently taking (use unordered list)?
2. Write a code that displays your favorite books in order?

3. Frames
3.1 Working with Frames
Frames can divide the screen into separate windows. Each of these windows can contain an HTML
document. A file that specifies how the screen is divided into frames is called a frameset. If you want to
make a homepage that uses frames you should:
Make an HTML document with the frameset
Make the normal HTML documents that should be loaded into each of these frames.
When a frameset page is loaded, the browser automatically loads each of the pages associated with the
frames. Each HTML document is called a frame, and each frame is independent of the others.
The disadvantages of using frames are:
The web developer must keep track of more HTML documents
It is difficult to print the entire page
The frameset element holds two or more frame elements. Each frame element holds a separate
document. The frameset element states only HOW MANY columns or rows there will be in the frameset
and it uses <frameset> tag. The <frame> tag defines one particular window (frame) within a frameset. In
the example below we have a frameset with two columns. The first column is set to 25% of the width of
the browser window. The second column is set to 75% of the width of the browser window. The
document "frame_a.htm" is put into the first column, and the document "frame_b.htm" is put into the
second column:
<frameset cols="25%,75%">
<frame src="frame_a.htm" />
<frame src="frame_b.htm" />
</frameset>
Note:
The frameset column size can also be set in pixels (cols="200,500"), and one of the columns can
be set to use the remaining space, with an asterisk (cols="25%,*").
You cannot use the body element together with the frameset element. However, if you add a
<noframes> tag containing some text for browsers that do not support frames, you will have to
enclose the text in a body element.

22

Attributes of frame
Attribute

Value

Description

frameborder

0 or 1

Specifies whether or not to display a border around a frame

marginheight

pixels

Specifies the top and bottom margins of a frame

marginwidth

pixels

Specifies the left and right margins of a frame

noresize

noresize

Specifies that a frame cannot be resized

scrolling

Yes, no
auto
URL

Specifies whether or not to display scrollbars in a frame

src

Specifies the URL of the document to show in a frame

Attributes of frameset
Attribute

Value

cols

Pixels, % or Specifies the number and size of columns in a frameset


*
Pixels, % or Specifies the number and size of rows in a frameset
*

rows

Description

Practice 2.3
1. What is the advantage of using frames
2. Create a web page that is divided in to three equal rows and the first row is divided in to two
columns.
3. Create a web page that is divided in to 3:2:1 proportion of columns.

3.2 Nested Frames


Framesets may be nested to any level. In the following example, the outer FRAMESET divides the
available space into three equal columns. The inner FRAMESET then divides the second area into two
rows of unequal height.
Example:
<FRAMESET cols="33%, 33%, 34%">
<frame src=one.html>
<FRAMESET rows="40%, 50%">
<frame src=two.html>
<frame src=three.html>
</FRAMESET>
<frame src=four.html>
</FRAMESET>

23

Note: the more frames are nested; it will make it complicated hence difficult manageable.

4. HTML Forms
1.7 Building HTML Forms
HTML forms are used to pass data to a server. An HTML form is a section of a document containing
normal content, markup, special elements called controls (checkboxes, radio buttons, menus, etc.), and
labels on those controls. Users generally "complete" a form by modifying its controls (entering text,
selecting menu items, etc.), before submitting the form for further processing (e.g., to a Web server, to a
mail server, etc.) Forms are a vital tool for the webmaster to receive information from the web surfer,
such as: their name, email address, credit card, etc. A form will take input from the viewer and
depending on your needs; you may store that data into a file, place an order, gather user statistics,
register the person to your web forum, or maybe subscribe them to your weekly newsletter.
The <form> tag is used to create an HTML form:
<form>
input elements
</form>
The most important form element is the input element. The input element is used to select user
information. An input element can vary in many ways, depending on the type attribute. An input
element can be of type text field, checkbox, password, radio button, submit button, and more. The most
used input types are described in the next subsections.

1.8 Working with Text Fields and Passwords


Text Field
<input type="text" /> defines a one-line input field that a user can enter text into:
<form>
First name: <input type="text" name="firstname" /><br />
Last name: <input type="text" name="lastname" />
</form>
How the HTML code above looks in a browser:
First name:
Last name:

Selam
Tibeb

24

Note: The form itself is not visible. Also note that the default width of a text field is 20 characters.
Practice 2.4
1. Create a web page that has a form for course registration; use your registration slip as a guide.
2. Create a web page that has a form for signing in to an email.

Password
<input type="password" /> defines a password field:
<form>
Password: <input type="password" name="pwd" />
</form>
How the HTML code above looks in a browser:
Password:

*********

Note: the characters entered in to the password field are masked.

1.9 Using Buttons, Checkboxes and Selection Lists


Radio Buttons
Radio buttons are a popular form of interaction. You may have seen them on quizzes, questionnaires,
and other web sites that give the user a multiple choice question. Below are a couple attributes you
should know that relate to the radio button.
Value: specifies what will be sent if the user chooses this radio button. Only one value will be sent for a
given group of radio buttons.
Name: defines which set of radio buttons that it is a part of.
<input type="radio" /> defines a radio button. Radio buttons let a user select ONLY ONE of a limited
number of choices:
<form>
<input type="radio" name="sex" value="male" /> Male<br />
<input type="radio" name="sex" value="female" /> Female
</form>

Practice 2.5

25

1. Create a web page that let students choose their department; use the list of department in your
faculty as a guideline.
2. Use a checkbox to create a web page that will enable students to select a subjects they enjoy
most (more than one selection is possible).

Checkboxes
Check boxes allow for multiple items to be selected for a certain group of choices. The check
box's name and value attributes behave the same as a radio button.
<input type="checkbox" /> defines a checkbox. Checkboxes let a user select ONE or MORE options of a
limited number of choices.
<form>
<input type="checkbox" name="vehicle" value="Bike" /> I have a bike<br />
<input type="checkbox" name="vehicle" value="Car" /> I have a car
</form>

Selection lists
Drop down menus are created with the <select> and <option> tags. <select> is the list itself and each
<option> is an available choice for the user.
<select name="degree">
<option>Choose One</option>
<option>Some High School</option>
<option>High School Degree</option>
<option>Some College</option>
<option>Bachelor's Degree</option>
<option>Doctorate</option>
<input type="submit" value="Email Yourself">
</select>

Attributes of select
Attribute

Value

Description

disabled

disabled

Specifies that a drop-down list should be disabled

multiple

multiple

Specifies that multiple options can be selected

name

name

Specifies the name of a drop-down list

size

number

Specifies the number of visible options in a drop-down list

26

Practice 2.6
1. Can you think of safe working condition and procedure as technician? Explain its importance?

1.10 Linking HTML Forms with PHP Scripts


To create a link between PHP scripts and HTML forms, we need to use the functionalities of buttons, and
the attribute of the <form tag>, specifically action and method.
Buttons:
Submit buttons: When activated, a submit button submits a form. A form may contain more than one
submit button.
Reset buttons: When activated, a reset button resets all controls to their initial values.
Action and method:
<input type="submit" /> defines a submit button.
A submit button is used to send form data to a server. The data is sent to the page specified in the form's
action attribute (how to write scripts will be discussed in the coming chapters). The file defined in the
action attribute usually does something with the received input:
<form name="input" action="action.php" method="get">
Username: <input type="text" name="user" />
<input type="submit" value="Submit" />

1.11 Automating Processing: Info Forms and Emails


If you would like to provide your web site visitors with a simple way to contact you from your web site,
but really don't want to display your email address, this HTML form code may be what you're looking for.
You can create a simple form, as displayed below, to enable your visitors to send you comments,
questions, product support requests, or whatever you'd like (remember you should change
dummy1@yahoo.com with your mail address).
<form action=mailto:dummy1@yahoo.com, method="POST", enctype="text/plain">
Your Name: <input type="text" size="20" name="VisitorName"><br><br>
Your Comment: <textarea name="VisitorComment" rows="4" cols="20">
</textarea><br><br>
<input type="submit" value="Email This Form">
</form>

27

Unit Three: Cascading Style Sheets

28

1. CSS Basics
1.1 Introduction to CSS
CSS stands for Cascading Style Sheet. A cascading style sheet file allows you to separate your web sites
HTML content from its style. As always you use your HTML file to arrange the content, but all of the
presentation/formatting (fonts, colors, background, borders, text formatting, link effects & so on...) are
accomplished within a CSS.
CSS is a web page layout method that has been added to HTML to give web developers more control
over their design and content layout. Using CSS allows a designer to create a standard set of commands
(either embedded inside the web page or from an external page) that controls the style of all
subsequent pages.
With CSS you can add style (fonts, colors, spacing, and size) to web documents. More advanced
techniques control the layout of the page without the use of tables or other cumbersome HTML.
CSS is that CSS separates the layout and the styles of a web page. This is often difficult to comprehend
for web designers that are used to compiling their creative and HTML coding in a single web page
document. Styles such as fonts, font sizes, margins, can be specified in one place, and then the Web
pages feed off this one master list, with the styles cascading throughout the page or an entire site.
Styles solve a common Problem. HTML tags were originally designed to define the content of a
document. They were supposed to say "This is a header", "This is a paragraph", "This is a table", by using
tags like <h1>, <p>, <table>, and so on. The layout of the document was supposed to be taken care of by
the browser, without using any formatting tags.
Styles sheets define HOW HTML elements are to be displayed, just like the font tag and the color
attribute in HTML. Styles are normally saved in external .css files. External style sheets enable you to
change the appearance and layout of all the pages in your Web, just by editing one single CSS
document!
CSS is a breakthrough in web design because it allows developers to control the style and layout of
multiple web pages all at once. As a web developer you can define a style for each HTML element and
apply it to as many web pages as you want. To make a global change, simply change the style, and all
elements in the Web are updated automatically.

CSS Versions
There are three levels/versions of CSS:
CSS1,
CSS2, and
CSS3

29

CSS 1
The first CSS specification to become an official W3C Recommendation is CSS level1
level1. It was published in
December 1996.
for:
Among itss capabilities are support for
Font properties such as typeface and emphasis
Color of text, backgrounds, and other elements
Text attributes such as spacing between words, letters, and lines of text
Alignment of text, images, tables and other elements
Margin,
gin, border, padding, and positioning for most elements
Unique identification and generic classification of groups of attributes
CSS 2
CSS level 2 specification was developed by the W3C and published as a Recommendation in May 1998. It
is a superset of CSS 1. It includes a number of new capabilities like absolute, relative, and fixed
positioning of elements and z-index,
index, the concept of media types, support for aural style sheets and
bidirectional text, and new font properties such as shadows.
CSS level 2 revision 1 or CSS 2.1 fixes errors in CSS 2. It removes poorly-supported
supported or not fully
interoperable features and adds already
already-implemented
implemented browser extensions to the specification.
CSS 3
CSS Level 3 builds on CSS Level 2 module by module, using the CSS2.1 specification as its core. Each
module adds functionality and/or replaces part of the CSS2.1 specification.
The CSS Working Group intends that the new CSS modules will not contr
contradict
adict the CSS2.1 specification:
only that they will add functionality and ref
refine definitions.

1.2 CSS Syntax


A CSS rule has two main parts: a selector, and one or more declarations. The selector is normally the
HTML element you want to style. Each declaration consists of a property and a value. The property is the
style attribute you want to change. Usually, it is the HTML tags to be styled. Each property has a value.

CSS declarations always ends with a semicolon, and declaration groups are surrounded by curly
brackets:

30

p {color:red; text-align:center;}
To make the CSS more readable, you can put one declaration on each line, like this:
p{
color:red;
text-align:center;
}
CSS Comments
Comments are used to explain your code, and may help you when you edit the source code at a later
date. CSS comments, like JavaScript comments, are ignored by browsers.
A CSS comment begins with /* and ends with */ like this:
/*This is a comment*/
p{
text-align:center;
/*This is another comment*/
font-family:arial;
}

1.3 Linking CSS to HTML


It is possible to link CSS with your html in three different ways: embedded style, inline style, and external
style.
Creating an Inline Style
Inline styles have the structure:
<tag style=property: value>
Creating Internal Styles
In the internal method, you simply place the CSS code within the <head></head> tags of each HTML file
you want to style with the CSS. The format for this is shown in the example below:
<head>
<title><title>
<style type="text/css">
CSS Content Goes Here
</style>
</head>
<body>

31

With this method each HTML file contains the CSS code needed to style the page. Meaning that any
changes you want to make to one page, will have to be made to all. This method can be good if you
need to style only one page, or if you want different pages to have varying styles.
Creating an External Style Sheet
An external CSS file can be created with any text or HTML editor such as "Notepad" or "Dreamweaver".
A CSS file contains no HTML, only CSS. You have to save the CSS file with the .css file extension. You can
link to the file externally by placing one of the following links in the head section of every HTML file you
want to style with the CSS file.
<link rel=stylesheet type=text/css href=filename.css/>
<style type=text/css>@import url(filename.css)</style>

Practice 3.1
1. Write an external CSS that formats paragraphs (<p> tags) and link to HTML page.
2. Write internal CSS to format your HTML page

2. CSS Styling
2.1 Styling Backgrounds
Background
You can style the background of an element in one declaration with the background property.
background: #ffffff url(path_to_image) top left no-repeat fixed;
Values:
attachment
color
image

position
repeat

Or you can set each property individually


Background Attachment
If you are using an image as a background. You can set whether the background scrolls with the page or
is fixed when the user scrolls down the page with the background-attachment property
background-attachment: value;
Values:
fixed
scroll
Background Color

32

You can specifically declare a color for the background of an element using the background-color
property.
background-color: value;
Values:
color name e.g. red, green, blue
hexadecimal number - e.g. #ff0000, #00ff00, #0000ff
RGB color code e.g. rgb(255, 0, 0), rgb(0, 255, 0), rgb(0, 0, 255)
transparent
e.g h1 { background-color: rgb(255, 255, 0); }
Background Image
You can set an image for the background of an HTML element (<p>, <h1>, <body>, <table>, etc) using
the background-image property.
background-image: url(path_to_image);
Values:
url
none
e.g. p { background-image: url("tulips.jpg"); }
Background Position
You can position an image used for the background of an element using the background-position
property.
background-position: value;
Values:

top left

top center

top right
center left

e.g. body { background-position: top right; }

center center
center right
bottom left
bottom center

bottom right
x-% y-%
x-pos y-pos

Background Repeat
You can set if an image set as a background of an element is to repeat (across=x and/or down=y) the
screen using the background-repeat property.
background-repeat: value;
Values:
repeat
repeat-x

33

repeat-y

2.2 Styling Text


Color
You can set the color of text with the following:
color: value;
Possible values are
color name example red, black
hexadecimal number example #ff0000, #000000
RGB color code example rgb(255, 0, 0), rgb(0, 0, 0)
Letter Spacing
You can adjust the space between letters in the following manner. Setting the value to 0, prevents the
text from justifying. You can use negative values. Negative values make the text to overlap each other.
letter-spacing: value;
Possible values are
normal
length
e.g. h2 { letter-spacing: 6; }

normal), -2, 6)
Fig. different letter spacing (0(normal
Word Spacing
You can adjust the space between words in the following m
manner.
anner. You can use negative values.
word-spacing: value;
Possible values are
normal
length
Line height
You can set the distance between lines in the following way:
line-height: value;
Possible values are
normal
number
length

34

percentage(%)

Text Align
You can align text with the following:
text-align: value;
Possible values are
left
right

center
justify

Examples:
This text is aligned left.
This text is aligned center.
This text is aligned right.
Text Decoration
You can decorate text with the following:
text-decoration: value;
Possible values are
none
underline
overline

line through
blink

Examples: h2 { text-decoration: line through; }


This text is underlined.
This text has a line through it.
This text is overlined.
Text Indent
You can indent the first line of text in an (X)HTML element with the following:
text-indent: value;
Possible values are
length
percentage(%)
Text Direction
You can sets the text direction
direction: value;

35

Possible values are


ltr
rtl
For the direction property to affect
ect reordering in inl
inline elements, the unicode-bidi propertys value must
be embed or override.
unicode-bidi
Possible value:
normal
embed
bidi-override
The meanings of the values are:
with
ith respect to the
normal: The element does not open an additional level of embedding w
bidirectional algorithm. For inline elements, implicit reordering works across element
boundaries.
embed: If the element is inline, this value opens an additional level of embedding with respect
to the bidirectional algorithm. Inside the element, reordering is done implicitly.
bidi-override: For inline elements this creates an override. For block container elements,
elements this
creates an override for inline
inline-level
level descendants not within another block container element.
This means that inside the
e element, reordering is strictly in sequence according to the direction
property; the implicit part of the bidirectional algorithm is ignored.
Example:
div {
direction: rtl;
unicode-bidi: bidi-override;
override;
}

<div> Hebrew and Arabic are written from rright to left. </div>
This is displayed as:

Text Transform
You can control the case of letters in an (X)HTML element with the following:
text-transform: value;
Possible values are

36

none
capitalize
e.g. h3 { text-transform: uppercase;}

lowercase
uppercase

White Space
You can control the whitespace in an (X)HTML element with the following:
white-space: value;
Possible values are
normal
pre
nowrap

pre-wrap
pre-line

This property declares how white space(tab, space, etc) and line break(carriage return, line feed, etc.)
inside the element is handled. Values have the following meanings:
normal: This value directs user agents to collapse sequences of white space, and break lines as
necessary to fill line boxes.
pre: This value prevents user agents from collapsing sequences of white space. Lines are only
broken at preserved newline characters.
nowrap: This value collapses white space as for normal, but suppresses line breaks within text.
pre-wrap: This value prevents user agents from collapsing sequences of white space. Lines are
broken at preserved newline characters, and as necessary to fill line boxes.
pre-line: This value directs user agents to collapse sequences of white space. Lines are broken at
preserved newline characters, and as necessary to fill line boxes.
The white-space processing model is as follows:
1. Each tab (U+0009), carriage return (U+000D), or space (U+0020) character surrounding a linefeed
(U+000A) character is removed if white-space is set to normal, nowrap, or pre-line.
2. If white-space is set to pre or pre-wrap, any sequence of spaces (U+0020) unbroken by an
element boundary is treated as a sequence of non-breaking spaces. However, for pre-wrap, a line
breaking opportunity exists at the end of the sequence.
3. If white-space is set to normal or nowrap, linefeed characters are transformed for rendering
purpose into one of the following characters: a space character, a zero width space character
(U+200B), or no character (i.e., not rendered), based on the content script.
4. If white-space is set to normal, nowrap, or pre-line, every tab (U+0009) is converted to a space
(U+0020) any space (U+0020) following another space (U+0020) is removed.

Practice 3.2
1. Write a CSS that uses background image and aligns paragraphs to right, with red text color.
2. Write internal CSS that gives extra spaces between letters and capitalize all <h1> tags in HTML
page

37

2.3 Styling Fonts


Font
The font property can set the style, weight, variant, size, line height and font:
font: [ [ font-style || font-variant || font-weight] || font-size [ /line-height] || font-family ];
Example:
font: italic bold normal small/1.4em Verdana, sans-serif;
The above would set the text of an element to an italic style a bold weight a normal variant a relative
size a line height of 1.4em and the font to Verdana or another sans-serif typeface.
Font -Family
You can set what font will be displayed in an element with the font-family property. There are 2 choices
for values:
family-name
generic family
If you set a family name it is best to also add the generic family at the end. As this is a prioritized list. So
if the user does not have the specified font name, it will use the same generic family.
font-family: Verdana, sans-serif;
Font Size
You can set the size of the text used in an element by using the font-size property.
font-size: value;
The value can be:
absolute size
relative size
length
percentage(%)
Absolute sizes are:
xx-small
x-small
small
medium

large
x-large
xx-large

The following table provides user agent guidelines for the absolute-size mapping to HTML heading and
absolute font-sizes
CSS absolute-size
xx-small
x-small
small
medium
large
x-large
xx-large
values
HTML font sizes
1
2
3
4
5
6
7

38

Relative sizes are:


larger
smaller
A relative-size is interpreted relative to the table of font sizes and the font size of the parent element.
For example, if the parent element has a font size of medium, a value of larger will make the font size of
the current element be large. If the parent elements size is not close to a table entry, the user agent is
free to interpolate between table entries or round off to the closest one.
Length Units in CSS
There are two types of length units: relative and absolute. Relative length units specify a length relative
to another length property. Style sheets that use relative units can more easily scale from one output
environment to another.
The absolute units consist of the physical units (in, cm, mm, pt, pc) and the px unit:
in: inches 1in is equal to 2.54cm.
cm: centimeters
mm: millimeters
pt: points the points used by CSS are equal to 1/72nd of 1in.
pc: picas 1pc is equal to 12pt.
px: pixel units 1px is equal to 0.75pt.
Example: all the following are possible
h1 { margin: 0.5in } /* inches */
h2 { line-height: 3cm } /* centimeters */
h3 { word-spacing: 4mm } /* millimeters */
h4 { font-size: 12pt } /* points */
h4 { font-size: 1pc } /* picas */
p { font-size: 12px } /* px */
Relative units are:
em: the current font-size of the relevant font
ex: the x-height of the relevant font
The em unit is equal to value of the font-size property of the element on which it is used. The exception
is when em occurs in the value of the font-size property itself, in which case it refers to the font size of
the parent element.
Example:
body

39

{
font-size: 12px;
text-indent:
indent: 3em; /* i.e., 36px - based on font-size*/
}
The ex means the x-height. The xx-height is so called because it is often equal to the height of the
lowercase x. However, an ex is defined even for fonts that do not contain an x.

Fig x-height
The x-height
height of a font can be found in different ways. Some fonts contain reliable metrics for the xheight. If reliable font metrics are not available, user agents may determine the x-height
height from the height
hei
of a lowercase glyph. In the cases where it is impossible or impractical to determine the x-height,
x
a value
of 0.5em should be used.
Example:
h1 { margin: 0.5em } /* em */
h1 { margin: 1ex
} /* ex */
Example:
h1 { line-height: 1.2em }
This means the line height of h1 elements will be 20% greater than the font size of the h1 elements.
On the other hand:
h1 { font-size: 1.2em }
This means that the font-size of h1 elements will be 20% greater than the font size inherited by h1
elements.
Font Style
You can set the style of text in an element with the font
font-style property:
font-style: value;
Possible values are
normal
itailc
oblique

40

Font Variant
You can set the variant of text within an element with the font-variant property:
font-variant: value;
Possible values are
normal
small-caps
Font Weight
You can control the weight of text in an element with the font-weight property:
font-weight: value;
Possible values are
lighter
normal
100
200
300

400
500
600
700
800

900
bold
bolder

The font-weight property selects the weight of the font. The values 100 to 900 form an ordered
sequence, where each number indicates a weight that is at least as dark as its predecessor. The keyword
normal is synonymous with 400, and bold is synonymous with 700. Keywords other than normal and
bold have been shown to be often confused with font names and a numerical scale was therefore
chosen for the 9-value list.
The bolder and lighter values select font weights that are relative to the weight inherited from the
parent. It is computed as follows:
inherited value
Bolder
Lighter
100

400

100

200

400

100

300

400

100

400

700

100

500

700

100

600

900

400

700

900

400

800

900

700

900

900

700

41

Example:
body { font-weight: 600;}
p { font-weight: bolder } /* this is based on 600 and it changes to 900*/

2.4 Styling Links


User agents commonly display unvisited links differently from previously visited ones. CSS provides the
pseudo-classes a:link and a:visited to distinguish them:
The a:link pseudo-class applies for links that have not yet been visited.
The a:visited pseudo-class applies once the link has been visited by the user.
The a:hover pseudo-class applies while the user designates an element with some pointing
device, but does not activate it. For example, a visual user agent could apply this pseudo-class
when the cursor (mouse pointer) hovers over a box generated by the element.
The a:active pseudo-class applies while an element is being activated by the user. For example,
between the times the user presses the mouse button and releases it.
The a:focus pseudo-class applies while an element has the focus (accepts keyboard events or
other forms of text input).
Below are the various ways you can use CSS to style links.
a:link {color: #009900;}
a:visited {color: #999999;}
a:hover {color: #333333;}
a:focus {color: #333333;}
a:active {color: #009900;}
Remark: You must declare the a:link and a:visited before you declare a:hover. Furthermore, you must
declare a:hover before you can declare a:active.
Using the above code will style all links on your web page, unless you declare a separate set of link styles
for a certain area of your webpage. Look at pseudo-classes sub-section for more.

2.5 Styling Lists


List Style
You can control the appearance of ordered and unordered lists in one declaration with the list-style
property
list-style: value value value;
Values:
image
position
type
Or you can control them individually

42

List Style Image


You can use an image for the bullet of unordered lists with the list-style property
list-style-image: url(path to image file);
If you use an image, it is a good idea to declare the list-style-type also in case the user has images turned
off.

List Style Position


You can control the position of ordered and unordered lists with the list-style-position property
list-style-position: value;
Values
inside
outside

List Style Type


You can control the type of bullet ordered and unordered lists use with the list-style-type property
list-style-type: value;
Values

none
disc
circle
square
decimal

decimal-leading-zero
lower-roman
upper-roman
lower-alpha
upper-alpha

Example:

ul{
list-style-position: inside;
list-style-type: lower-roman;
}

2.6 Styling Tables


Table Borders
To specify table borders in CSS, use the shorthand border property.
border: [border-width || border-style || border-color ];
The example below specifies a black border for table, th, and td elements:
table, th, td{
border: 1px solid black;
}

43

lower-greek
lower-latin
upper-latin
armenian
Georgian

Notice that the table in the example above has double borders. This is because both the table, th, and td
elements have separate borders.
Related properties which take the same value as border are:
border-left: [border-width || border-style || border-color ];
border-right: [border-width || border-style || border-color ];
border-top: [border-width || border-style || border-color ];
border-bottom: [border-width || border-style || border-color ];
Border Styles
The border style properties specify the line style of a boxs border (solid, double, dashed, etc.).
border-style: value;
The properties may take one of the following values:
none: no border.
hidden: same as none, but in the collapsing border model , also inhibits any other border.
dotted: the border is a series of dots.
dashed: the border is a series of short line segments.
solid: the border is a single line segment.
double: the border is two solid lines. The sum of the two lines and the space between them
equals the value of border-width.
groove: the border looks as though it were carved into the canvas.
ridge: the opposite of groove: the border looks as though it were coming out of the canvas.
inset: in the separated borders model , the border makes the entire box look as though it were
embedded in the canvas. In the collapsing border model, drawn the same as ridge.
outset: in the separated borders model, the border makes the entire box look as though it were
coming out of the canvas. In the collapsing border model, drawn the same as groove.
Related properties which take the same value as border-style are:
border-top-style: value;
border-bottom-style: value;
border-left-style: value;
border-right-style: value;
Border Width
The border width properties specify the width of the border area.
border-width: value;
Value can be:
thin: a thin border.
medium: a medium border.

44

thick: a thick border.


length_value: the borders thickness has an explicit value. E.g. 10px

If there is only one component value, it applies to all sides. If there are two values, the top and bottom
borders are set to the first value and the right and left are set to the second. If there are three values,
the top is set to the first value, the left and right are set to the second, and the bottom is set to the
third. If there are four values, they apply to the top, right, bottom, and left, respectively.
Example (top, right, bottom, and left):
h1 { border-width: thin } /* thin thin thin thin */
h1 { border-width: thin thick } /* thin thick thin thick */
h1 { border-width: thin thick medium } /* thin thick medium thick */

Related properties that take the same value as border-width are:


border-top-width: value;
border-right-width: value;
border-bottom-width: value;
border-left-width: value;
border-width: value;
Border Color
The border-color property sets the color of the four borders.
border-color: value;
Values can be:
color
transparent
The border-color property can have from one to four component values, and the values are set on the
different sides of the table just like border-width.
Related properties that take the same value as border-color are:
border-top-color: value;
border-right-color: value;
border-bottom-color: value;
border-left-color: value;
Collapse Borders
The border-collapse property sets whether the table borders are collapsed into a single border or
separated:
border-collapse: value;

45

Possible values:
collapse
separate
Example:
table{
border-collapse:collapse;
}
table, th, td{
border: 1px solid black;
}
Empty Cells
In the separated borders model, this property controls the rendering of borders and backgrounds
around cells that have no visible content. Empty cells and cells with the visibility property set to
hidden are considered to have no visible content.
empty-cells: value;
Possible values:
show
hide
Border Spacing
The lengths specify the distance that separates adjoining cell borders. If one length is specified, it gives
both the horizontal and vertical spacing. If two are specified, the first gives the horizontal spacing and
the second the vertical spacing.
border-spacing: length;
Table Width and Height
Width and height of a table is defined by the width and height properties. The example below sets the
width of the table to 100%, and the height of the th elements to 50px:
table{
width:100%; /*as wide as the screen*/
}
th{
height:50px;
}
Table Text Alignment
The text in a table is aligned with the text-align and vertical-align properties. The text-align property sets
the horizontal alignment, like left, right, or center:

46

td{
text-align:right;
}
Vertical Alignment
The vertical-align property of each table cell determines its alignment within the row. Each cells content
has a baseline, a top, a middle, and a bottom, as does the row itself. In the context of tables, values for
vertical-align have the following meanings:
baseline: The baseline of the cell is put at the same height as the baseline of the first of the rows
it spans.
top: The top of the cell box is aligned with the top of the first row it spans.
bottom: The bottom of the cell box is aligned with the bottom of the last row it spans.
middle: The center of the cell is aligned with the center of the rows it spans.
sub, super, text-top, text-bottom, <length>, <percentage>: These values do not apply to cells;
the cell is aligned at the baseline instead.

Fig structure of table


td {
height:50px;
vertical-align:bottom;
}

47

Table Padding
To control the space between the border and content in a table, use the padding property on td and th
elements:
td{
padding:15px;
}
Table Color
The color of the borders, and the text and background color of th elements can be specified:
table, td, th{
border:1px solid green;
}
th{
background-color:green;
color:white;
}

2.7 CSS Class and ID


2.7.1 CSS Class
Controlling the way all HTML elements look can be useful, but also limiting. It's excellent to be able to
change every paragraph, table cell or image with one line of CSS code, but sometimes you'll want to
change only few paragraphs or images, not all of them. You can add CSS code through the style attribute
of each element, but for more elements that method gets too complicated.
For example, paragraph can be defined in CSS file as follows:
p{
font-size: small;
color: #333333
}
However, lets say you want to change the word "sentence" in the paragraph formatted by the above
CSS to green bold text, while leaving the rest of the sentence untouched. This can be done by using
class.
There are two types of classes generic classes that can be applied to any element, and classes that can
be applied only to a certain type of HTML element.
Let's start with generic classes. Their selector starts with a dot (.), which states that it is a class. You can
name it anything you want:
.important { background-color: #FFFFDE; }

48

.emphasis { font-family: Verdana; }


.boooring { color: Gray; }
To apply a class to a certain HTML element, use its class attribute where you state the class name
without the dot.
<div class="emphasis">The big match today </div>
<i class="boooring">This sentence looks boring</i>
You can also use classes which can be applied only to certain HTML elements. Selectors of these classes
start with the HTML element name, followed with the dot and the class name:
div.big { font-weight: bold; font-size: 16pt; }
These classes can be applied only to a specified HTML element, in this case a DIV element.
<div class="big">Big bold text.</div>
<span class="big">Normal text - class not applied.</span>
Example: in your paragraph, you put this:
<span class="greenboldtext">sentence</span>
Then in the CSS file, add this style selector:
.greenboldtext {
font-size: small;
color: #008080;
font-weight: bold;
}
Pseudo Classes
Pseudo-classes are classes that define tag states. Most commonly, these are used to make link styles
change when the mouse pointer hovers over a hyperlink, hyperlink is clicked, etc.
Pseudo class
Link state
a:link

Normal link

a:visited

Already visited link

a:hover

Mouse hovers the link

a:active

User is clicking on the link

Table 3.1 pseudo classes


Example:
a:link {
text-decoration: underline;

49

font-weight: normal;
color: #003300;
}
a:visited {
text-decoration: underline;
font-weight: normal;
color: #999999;
}

2.7.2 CSS ID
IDs are similar to classes, except once a specific ID has been declared it cannot be used again within the
same (X)HTML file. The syntax of ID selectors is very similar to classes, but instead of a dot you must use
a hash sign (#).
The HTML content is:
<div id="container"> I was asleep, but my heart was awake. </div>
The CSS that formats the HTML content:
#container{
width: 80%;
padding: 20px;
margin: auto;
border: 1px solid blue;
background: red;
}

Practice 3.3
1. Write an external CSS that uses Class ID to format DIV element text to blue, font size 20, and
background to silver.
2. Write a CSS that changes visited links to yellow, and active links to green.
3. Write a CSS that creates lists that use small Roman numbers.

3. CSS Box Model


3.1 CSS Box Model
In CSS, the term box model is used when talking about design and layout. The CSS box model is
essentially a box that wraps around HTML elements, and it consists of: margins, borders, padding, and
the actual content.

50

The box model allows us to place a border around elements and space elements in relation to other
elements. The image below illustrates the box model.

Figure 3.1 CSS box model


Explanation of the different parts:
Margin - Clears an area around the border. The margin does not have a background color, and it
is completely transparent
Border - A border that lies around the padding and content. The border is affected by the
background color of the box
Padding - Clears an area around the content. The padding is affected by the background color of
the box
Content - The content of the box, where text and images appear
In order to set the width and height of an element correctly in all browsers, you need to know how the
box model works.

3.2 CSS Border


Border
You can set the color, style and width of the borders around an element in one declaration by using the
border property.
border: 1px solid #333333;
Values:
color
style

width

Or you can set each property individually


Border Color
You can set the color of a border independently with the border-color property.
border-color: value;

51

Values:
color name
hexadecimal number

RGB color code


transparent

Border Style
You can set the style of a border independently with the border-style property.
border-style: value;
Values:

dashed
dotted
double
groove

hidden
inset
none
outset

Figure 3.2 different border styles


Border Width
You can set the width of a border independently with the border-width property.
border-width: value;
Values:
Length

Thin

Or you can set the elements for each borders side individually

52

Medium
Thick

ridge
solid

Border Bottom
You can set the color, style and width of the bottom border around an element in one declaration with
the border-bottom property.
border-bottom: 1px solid #333333;
Values:
color
style
Or you can set each value individually

width

Border Bottom Color


You can set the color of the bottom border around an element with the border-bottom-color property.
border-bottom-color: value;
You can set the style of the bottom border around an element with the border-bottom-style property:
border-bottom-style: value;
Border Bottom Width
You can set the width of the bottom border around an element with the border-bottom-width property.
border-bottom-width: value;
Border Left
You can set the color, style and width of the left border around an element with the border-left
property.
border-left: 1px solid #333333;
Values:
color
style
Or you can set each value individually

width

Border Left Color


You can set the color of the left border around an element with the border-left-color property.
border-left-color: value;
Border Left Style
You can set the style of the left border around an element with the border-left-style property.
border-left-style: value;
Border Left Width
You can set the width of the left border around an element with the border-left-width property.

53

border-left-width: value;
Border Right
You can set the color, style and width of the right border around an element in one declaration with the
border-right property.
border-right: 1px solid #333333;
Values:
color
style
Or you can set each value individually

width

3.3 CSS Margin


The margin clears an area around an element (outside the border). The margin does not have a
background color, and is completely transparent.
The top, right, bottom, and left margin can be changed independently using separate properties. A
shorthand margin property can also be used, to change all margins at once.
Property

Description

Values

Margin

A shorthand property for setting


the margin properties in one
declaration

margin-bottom

Sets the bottom margin of an


element

margin-left

Sets the left margin of an


element

margin-right

Sets the right margin of an


element

margin-top

Sets the top margin of an


element

Table 3.2 CSS margin

54

margin-top
margin-right
margin-bottom
margin-left
auto
length
%
auto
length
%
auto
length
%
auto
length
%

3.4 CSS Padding


The padding clears an area around the content (inside the border) of an element. The padding is
affected by the background color of the element.
The top, right, bottom, and left padding can be changed independently using separate properties. A
shorthand padding property can also be used, to change all paddings at once.
Property
Padding

padding-bottom
padding-left
padding-right
padding-top

Description
Values
A shorthand property for setting all
padding-top
the padding properties in one
padding-right
declaration
padding-bottom
padding-left
Sets the bottom padding of an
length
element
%
Sets the left padding of an element
length
%
Sets the right padding of an
length
element
%
Sets the top padding of an element length
%

Table 3.3 CSS padding

Practice 3.4
1. Write a CSS that creates a <p> tag that has silver dotted borders around it.
2. Based on the above, change the top padding to 10, and 30 and see the effect.

55

Unit Four: JavaScript Programming


1. Introduction to JavaScript
1.1 Introduction
JavaScript is a cross-platform, object-oriented scripting language modeled after C++. Scripting languages
are programming languages that are generally easy to learn, easy to use, excellent for small routines and
applications, and developed to serve a particular purpose. JavaScript was written for the express
purpose of adding interactivity to Web pages.
As a scripting language, JavaScript is easy to learn and easy to use. You can embed commands directly
into your HTML code and the browser will interpret and run them at the appropriate time. JavaScript is
also much more forgiving than compiled languages such as Java and C++. Its syntax, the special
combination of words and symbols used by the language for programming commands, is simple and
easy to read.
Scripting languages are usually interpreted rather than compiled. JavaScript is an interpreted language.
That means that a software routine called an interpreter must translate a programs statements into
machine code, code understandable by a particular type of computer, before executing them every time
the program is run. Compiled languages, on the other hand, are translated into machine code and
stored for later execution. When the compiled program is run, it executes immediately without further
need of interpretation; it was interpreted into machine code when it was compiled. Because programs
written in interpreted languages must be translated into machine code every time they are run, they are
typically slower than compiled programs. However, this does not usually present a problem for the small
applications for which scripting languages are generally used.
Being interpreted does have its advantages. One is platform independence. Because an interpreter
performs the translation, you can write your program once and run it on a variety of platforms. All you
need is the correct interpreter. In the case of JavaScript, the interpreter is built into Web browsers.
Browsers are available for a variety of platforms and operating systems. Another advantage is that
scripting languages are often loosely typed and more forgiving than compiled languages.

1.2 Running the JavaScript


Any time you include JavaScript in an HTML document, you must enclose those lines inside a
<SCRIPT>...</SCRIPT> tag pair. These tags alert the browser program to begin interpreting all the text
between these tags as a script. Because other scripting languages (such as Microsofts VBScript) can
take advantage of these script tags, you must specify the precise name of the language in which the
enclosed code is written. Therefore, when the browser receives this signal that your script uses the
JavaScript language, it employs its built-in JavaScript interpreter to handle the code.

56

Now is a good time to instill an aspect of JavaScript that will be important to you throughout all your
scripting ventures: JavaScript is case-sensitive. Hence, you must enter any item in your script that uses a
JavaScript word with the correct uppercase and lowercase letters. Your HTML tags (including the
<SCRIPT> tag) can be in the case of your choice, but everything in JavaScript is case-sensitive. When a
line of JavaScript doesnt work, one of the things you have to do is look for the wrong case first.
<SCRIPT LANGUAGE=JavaScript>
//your script here
</SCRIPT>
Here are some tips to remember when writing JavaScript commands:
JavaScript code is case sensitive (e.g. age and Age are different variables)
White space between words and tabs are ignored
Line breaks are ignored except within a statement
JavaScript statements end with a semi colon (;)
Adding JavaScript
There are three ways to add JavaScript commands to your Web Pages.
Embedding code
Inline code
External file
External File
You can use the SRC attribute of the <SCRIPT> tag to call JavaScript code from an external text file. This
is useful if you have a lot of code or you want to run it from several pages, because any number of pages
can call the same external JavaScript file. The text file itself contains no HTML tags. It is called by the
following tag:
<SCRIPT language = "JavaScript" SRC = "filename">
</SCRIPT>
If you want to run the same JavaScript on several pages, without having to write the same script on
every page, you can write a JavaScript in an external file. Save the external JavaScript file with a .js file
extension. The external script cannot contain the <script></script> tags! To use the external script, point
to the .js file in the "src" attribute of the <script> tag.
Where to Put the JavaScript
JavaScripts in a page will be executed immediately while the page loads into the browser. This is not
always what we want. Sometimes we want to execute a script when a page loads, or at a later event,
such as when a user clicks a button. When this is the case we put the script inside a function (you will
learn about functions in a later chapter).

57

Scripts in <head>
Scripts to be executed when they are called, or when an event is triggered, are placed in functions. Put
your functions in the head section, this way they are all in one place, and they do not interfere with page
content.
<html>
<head>
<script language="javascript">
function message()
{
alert("This alert box was called with the onload event");
}
</script>
</head>
<body onload="message()">
</body>
</html>
Scripts in <body>
If you don't want your script to be placed inside a function, or if your script should write page content, it
should be placed in the body section.
<html>
<head> </head>
<body>
<script language="javascript">
document.write("This message is written by JavaScript");
</script>
</body>
</html>

Scripts in <head> and <body>


You can place an unlimited number of scripts in your document, so you can have scripts in both the body
and the head section.
Input-Output in Java
One of the most important things to do when learning a new language is to master basic input
and output. In JavaScript, input-output can be done in different ways:
document.write(message to display);
alert(message to display);
prompt(message to display, default value);
confirm(message to display);

58

documents.write method writes a string to the web page. Anything between double quotes will be
displayed as it is in the web page. However, if there is something out of quotes, it is evaluated as
expression and the result will be sent to the web page.
The alert method is produces a browser alert box. These are incredibly useful for debugging and learning
the language. However, they are not good way to communicate with the users. alert() displays a modal
window that presents a message to the user with a single Ok button to dismiss the dialog box.
The prompt display includes a message, field for user query, and two buttons (Ok, and Cancel). The
prompt() returns string of text entered by user. It takes two parameters: a message providing the
prompt for the response, and a default string which is used to fill in the text field.
A confirm dialog box presents a message in a modal dialog box along with Ok and Cancel buttons. Such
dialog boxes can be used to ask a question of the user, usually prior to performing actions that will not
be undoable. The dialog box returns a Boolean value of Ok=true, and Cancel=false;
Example:
var adult = confirm(Are you sure you are older than 18 years?)
if(adult)
alert(Yes);
else
alert(No);

1.3 Working with Variables and Data


With rare exception, every JavaScript statement you write does something with a hunk of information
data. Data may be text information displayed on the screen by a JavaScript statement or the on/off
setting of a radio button in a form. Each single piece of information in programming is also called a
value. Outside of programming, the term value usually connotes a number of some kind; in the
programming world, however, the term is not as restrictive. A string of letters is a value. A number is a
value. The setting of a check box (whether it is checked or not) is a value.
In JavaScript, a value can be one of several types. Table 4-1 lists JavaScripts formal data types, with
examples of the values.
Type

Example

Description

String

John

a series of characters inside quotation marks

Number

4.5

any number not inside quotes

Boolean

True

a logical true or false

Null

Null

completely devoid of any value

59

Object

a software thing that is defined by its properties and methods

Table 4.1 JavaScript data types


Declaring Variables
Creating variables in JavaScript is most often referred to as declaring variables. To declare variable, we
use the var keyword, followed by the name we want to give to thw variable. You can declare JavaScript
variables with the var keyword as follows:
var variablename;
Therefore, to declare a new variable called myAge, the JavaScript statement is
var myAge;
Variable names obey number of restrictions (rules). First, you cannot use any reserved keyword as a
variable name. That includes all keywords currently used by the language and all others held in reserve
for future versions of JavaScript.
Second, a variable name cannot contain space characters. Therefore, one-word variable names are fine.
Should your description really benefit from more than one word, you can use one of two conventions to
join multiple words as one. One convention is to place an underscore character between the words; the
other is to start the combination word with a lowercase letter and capitalize the first letter of each
subsequent word within the name. Both of the following examples are valid variable names:
var my_age;
var myAge;
Variable names have a couple of other important restrictions. Avoid all punctuation symbols except for
the underscore character. Also, the first character of a variable name cannot be a numeral.
To put together, a variable name can contain letters of the alphabet, both capital and small, number and
_(underscore). Still, the name should start with letters of the alphabet, or _, not digits
Example: correct variable declaration,
var firstName;
var weight;
var he89;
var TH_;
Example: Wrong variable names:
Var first name; //space not allowed
Var 89he; //cant start with digit
Var TH.; //punctuation mark not allowed

60

Assigning Values to Variables


After the declaration shown above, the variables are empty which means they have no data values yet.
After declaring a variable, it is possible to assign a value to it by using equal sign (=) as follows:
var myAge;
myAge = 45;
However, you can also assign values to the variables when you just declare them:
var age=5;
var carName="Volvo";
After the execution of the statements above, the variable age will hold the value 5, and carName will
hold the value Volvo. When you assign a text/string value to a variable, use quotes around the value.
Assigning Values to Undeclared Variables
If you assign values to variables that have not yet been declared, the variables will automatically be
declared. These statements:
age=5;
carName="Volvo";
The above statements have the same effect as:
var age=5;
var carName="Volvo";
Redeclaring JavaScript Variables
If you redeclare a JavaScript variable, it will not lose its original value.
var age=5;
var age;
After the execution of the statements above, the variable x will still have the value of 5. The value of x is
not reset (or cleared) when you redeclare it.
Comments
Comments are author notations that explain what a script does. Comments are ignored by the
interpreter. You add comments to a script for your benefit. They usually explain in plain language what a
statement or group of statements does. The purpose of including comments is to remind you how your
script works after long period has passed when you see your code.
JavaScript supports two types of comments:
Comments on a single line are preceded by a double-slash (//).
Comments that span multiple lines are preceded by /* and followed by */
Example: the following example shows two comments:
//This next line prints text into the document

61

document.write("This line came from some JavaScript");


/* This is a multiple-line comment. This line shows an alert so we know
things worked properly*/
alert("The text has been printed");

Practice 4.1
1. Write in body a JavaScript code that declares a variable called name and assigns a value
William to it.
2. Then display the content of the variable.

1.4 Operators and Expressions


An operator performs some kind of calculation (operation) or comparison with two values to reach a
third value. Generally, operators can be broadly categorized into two: mathematical operators,
comparison operators and logical operators.
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations between variables or values.
Operator
Description
+

Perform addition of numbers

Perform Subtraction

Multiply numbers

Divide numbers

Modulus (performs division and gets the remainder)

++

Increment

--

Decrement

Table 4.2 arithmetic operators


Given that the variable y=5, the table shows the result of arithmetic operations
Operation
Result
X = y+2

X=7

X = y-2

X=3

X = y*2

X=10

X = y/2

X=2.5

X = y%2

X=1

62

X = ++y

X=6

X = --y

X=4

Table 4.3 example arithmetic operators


JavaScript Assignment Operators
Assignment operators are used to perform arithmetic operation and then assign the result to variables.
Operator
Description
=

assignment operator

+=

Add and then assign

-=

Subtract and then assign

*=

Multiply and then assign

/=

Divide and then assign

%=

Modulate and then assign

Table 4.4 assignment operators


Given that variable x=10, and y=5, the table below shows the operations and the result:
Operations
Equivalent Result
x=y

x=5

x+=y

x=x+y

x=15

x-=y

x=x-y

x=5

x*=y

x=x*y

x=50

x/=y

x=x/y

x=2

x%=y

x=x%y

x=0

Table 4.5 example assignment operators


Comparison Operators
Comparison operators help you compare two or more values whether two values are equal, for
example. These kinds of comparisons return a value of the Boolean type true or false. Table 4.6 lists
the comparison operators. The operator that tests whether two items are equal consists of a pair of
equal signs to distinguish it from the single equal sign assignment operator.
Symbol
Description
==

Equals

===

Exactly equal to (value and type)

63

!=

Not equal to

>

Greater than

>=

Greater than or equal to

<

Less than

<=

Less than or equal to

Table 4.6 comparison operators


Logical Operators
Logical operators are used to determine the logic between variables or values.
Operator
Description
&&

And

||

Or

Not

Table 4.7 logical operators


Given that x=6 and y=3, the table below explains the logical operators and the results:
Example
Result
(x<10 && y>1)

true

(x==5 || y==5)

false

!(x==y)

true

Table 4.8 example logical operators


Operator Precedence
Operator type

Individual operators

member

. []

call / create instance

() new

negation/increment

! ~ - + ++ -- typeof void delete

multiply/divide

* / %

addition/subtraction

+-

bitwise shift

<< >> >>>

relational

< <= > >= in instanceof

equality

== != === !==

64

bitwise-and

&

bitwise-xor

bitwise-or

logical-and

&&

logical-or

||

Conditional

?:

assignment

= += -= *= /= %= <<= >>= >>>= &= ^= |=

comma

Table 4.9 operator precedence


Data Type Conversions
The type of data in an expression can trip up some script operations if the expected components of the
operation are not of the right data type. JavaScript tries its best to perform internal conversions to head
off such problems. However, if your intentions differ from the way JavaScript treats the values, you
wont get the results you expect.
A case in point is adding numbers that may be in the form of text strings. In a simple arithmetic
statement that adds two numbers together, you get the expected result:
3 + 3; // result = 6
But if one of those numbers is a string, JavaScript leans toward converting the other value to a string
thus turning the plus signs action from arithmetic addition to concatenating strings. Therefore, in the
statement
3 + 3 // result = 33
the string-ness of the second value prevails over the entire operation. The first value is automatically
converted to a string, and the result joins the two strings.
If you take this one step further, look what happens when another number is added to the statement:
3 + 3 + 3 // result = 63
This might seem illogical, but there is logic behind this result. The expression is evaluated from left to
right. The first plus operation works on two numbers, yielding a value of 6. But as the 6 is about to be
added to the 3, JavaScript lets the string-ness of the 3 rule. The 6 is converted to a string, and two
string values are joined to yield 63.
Converting strings to numbers
If a numeric value is stored as a stringas it is when entered into a form text fieldyour scripts will
have difficulty applying that value to a math operation. The JavaScript language provides two built-in
functions to convert string representations of numbers to true numbers: parseInt() and parseFloat().

65

To use either of these conversion functions, pass the string value you wish to convert as a parameter to
the function.
parseInt(string [,radix])
parseFloat(string [,radix])
radix, which is optional, specifies the base of the number to convert to: hexadecimal, octal, or decimal, ..
For example, look at the results of two different string values when passed through the parseInt()
function:
parseInt(42) // result = 42
parseInt(42.33) // result = 42
Even though the second expression passes the string version of a floating-point number to the function,
the value returned by the function is an integer. No rounding of the value occurs here. The decimal and
everything to its right are simply stripped off.
The parseFloat() function returns an integer if it can; otherwise, it returns a floating-point number as
follows:
parseFloat(42) // result = 42
parseFloat(42.33) // result = 42.33
Converting numbers to strings
Youll have less need for converting a number to its string equivalent than the other way around.
JavaScript gravitates toward strings when faced with an expression containing mixed data types. The
simplest way to convert a number to a string is by adding an empty string to a number:
( + 2500) // result = 2500
( + 2500).length // result = 4
A more elegant way is to use the toString() method. For example, to convert the dollars variable value to
a string, use this statement:
Var dollars = 2500;
dollars.toString() // result = 2500
You can specify a number base for the string representation of the number. Called the radix, the base
number is added as a parameter to the method name. Here is an example of creating a
numeric value for conversion to its hexadecimal equivalent as a string:
var x = 30
var y = x.toString(16) // result = 1e

Practice 4.2
1. Write a JavaScript code that calculates 850*230
2. Write a JavaScript code that return the remainder of dividing 43 by 30

66

1.5 Working with Conditional Statements


Conditional statements are used to perform different actions based on different conditions. Broadly,
there are two ways to execute code conditionally:
If statement
switch statement
If condition
The simplest program decision is to follow a special branch or path of the program if a certain condition
is true. Formal syntax for this construction follows:
if (condition) {
statement[s] if true
}
Lets examine the basic structure of the statement. The keyword if is a must. In the parentheses goes an
expression that evaluates to a Boolean value. This is the condition being tested as the program runs past
this point. If the condition evaluates to true, then one or more statements inside the curly braces
execute before continuing on with the next statement after the closing brace. If the condition evaluates
to false, then the statements inside the curly brace are ignored and processing continues with the next
statement after the closing brace. Items in italics are replaced with expressions and statements that fit
the situation.
Example:
if (myAge < 18) {
alert(Sorry, you cannot vote.)
}

if . . . else Condition
Not all program decisions are as simple as the one shown above. Rather than specifying one detour for a
given condition, you might want the program to follow one of many branches depending on that
condition. In the plain if construction, no special processing is performed when the condition evaluates
to false. But if processing must follow one of two special paths, you need the if...else construction. The
formal syntax definition for an if...else construction is as follows:
if (condition) {
statement(s) if true
}
[else if(condition){
statement(s) if true
}]
[else {

67

statement(s) if false
}]
[] indicates optional parts of the JavaScript code. Such statements can be left out of the script.
Example:
If(mark>80)
status=excellent;
else if(mark>60)
status=very good;
else if(mark>50)
Status = fair;
else
status =poor;
switch Statement
A switch statement allows a program to evaluate an expression and attempt to match the expression's
value to a case label. If a match is found, the program executes the associated statement. A switch
statement looks as follows:
switch (expression) {
case label1:
statements1
[break;]
case label2:
statements2
[break;]
...
default:
statementsdefault
[break;]
}
The program first looks for a case clause with a label matching the value of expression. If found, it then
transfers control to that clause, executing the associated statements. If no matching label is found, the
program looks for the optional default clause, and if found, transfers control to that clause, executing
the associated statements. If no default clause is found, the program continues execution at the
statement following the end of switch. By convention, the default clause is the last clause, but it does
not need to be so.
The optional break statement associated with each case clause ensures that the program breaks out of
switch once the matched statement is executed and continues execution at the statement following

68

switch. If break is omitted, the program continues execution at the next statement in the switch
statement.
Example:
switch (fruittype) {
case "Apples":
document.write("Apples are $0.32 a pound.<br>");
break;
case "Bananas":
document.write("Bananas are $0.48 a pound.<br>");
break;
case "Mangoes":
case "Papayas":
document.write("Mangoes and papayas are $2.79 a pound.<br>");
break;
default:
document.write("Sorry, we are out of " + fruittype + ".<br>");
}

Practice 4.3
1. Write a program that checks if student mark is not less than 0 and not greater than 100.
2. Write a program that gives letter grades using student mark. Use the following scale:
A >85
B >75
C > 50
D >40

2. Arrays, loops, and Functions


2.1 Using Arrays
Just think of an example where you want to store 100 different names. How could you do this with
JavaScript? Well, you could define 100 variables and assign the different names to them. This is quite
complicated and tiresome. This can be solved with arrays which can be seen as many variables bundled
together.
An array is an ordered collection of data. You can best visualize an array as a table, not much different
from a spreadsheet. In JavaScript, arrays are limited to a table holding one column of data, with as many
rows as needed to hold your data.
A JavaScript-enabled browser creates a number of internal arrays for the objects in your HTML
documents and browser properties. For example, if your document contains five links, the browser

69

maintains a table of those links. You access them by number (with 0 being the first link) in the array
syntax as in document.links[0], which represents the first link in the document.
To initialize an array for your script, use the new keyword to construct the object for you while assigning
the array object to a variable of your choice:
var myArray = new makeArray(n)
where n is the number of entries you anticipate for the array. This initialization does not make any array
entries or create any placeholders. Such preconditioning of arrays is not necessary in JavaScript.
Example: an array that stores the names of planets
planet = new Array(9); //an array with 9 entries
planet[0] = Mercury
planet[1] = Venus
planet[2] = Earth
planet[3] = Mars
planet[4] = Jupiter
planet[5] = Saturn
planet[6] = Uranus
planet[7] = Neptune
planet[8] = Pluto
You can also create array by directly giving the values:
planet= new Array(Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune,
Pluto);
Access an Array
You can refer to a particular element in an array by referring to the name of the array and the index
number. The index number starts at 0 and end at n-1 for array of n entries. For example, to access the
fifth planet in the planets array, we use:
planet[4]; //Jupiter
Deleting Array Entries
You can always set the value of an array entry to null or an empty string to wipe out any data that used
to occupy that space. But with the delete operator, you could not completely remove the element.
Deleting an array element eliminates the index from the list of accessible index values but does not
reduce the arrays length, as in the following sequence of statements:
planet.length; // result: 9
delete planet[2];
planet.length; //result: 9
document.write(planet[2]); //result: undefined
Array Object Methods

70

array.concat(array2)
The array.concat() method allows you to join two array objects into a new, third array object. The action
of concatenating the arrays does not alter the contents or behavior of the two original arrays.
For example:
var array1 = new Array(1,2,3)
var array2 = new Array(a,b,c)
var array3 = array1.concat(array2)
// result: array with values 1,2,3,a,b,c
If an array element is a string or number value (not a string or number object), the values are copied
from the original arrays into the new one. All connection with the original arrays ceases for those items.
array.sort([compareFunction])
This methods returns array of entries in the order as determined by the compareFunction algorithm.
Look first at the kind of sorting you can do with the array.sort() method by itself. When no parameter is
specified, JavaScript takes a snapshot of the contents of the array and converts items to strings. From
there, it performs a string sort of the values. ASCII values of characters govern the sort, which means
that numbers are sorted by their string values, not their numeric values. This fact has strong implications
if your array consists of numeric data: The value 201 sorts before 88, because the sorting mechanism
compares the first characters of the strings (2 versus 8) to determine the sort order. For simple
alphabetical sorting of string values in arrays, the plain array.sort() method does the trick.
Fortunately, additional intelligence is available that you can add to array sorting. The key tactic is to
define a function that helps the sort() method compare items in the array. A comparison function is
passed two values from the array (what you dont see is that the array.sort() method rapidly sends
numerous pairs of values from the array to help it sort through all entries). The comparison function lets
the sort() method know which of the two items comes before the other, based on the value the function
returns. Assuming that the function compares two values, a and b, the returned value reveals
information to the sort() method:
Return Value Range

Meaning

<0

value b should sort later than a

The order of a and b should not change

>0

Value a should sort later than b

Table 4.10 sort function


Example: a function that sorts numbers

71

myArray = new Array(12, 5, 200, 80)


function compare(a,b) {
return a - b;
}
myArray.sort(compare);
Other array object methods
Method
Description
every()

Returns true if every element in this array satisfies the provided testing function.

filter()

Creates a new array with all of the elements of this array for which the provided
filtering function returns true.

forEach()

Calls a function for each element in the array.

indexOf(value)

Returns the first (least) index of an element within the array equal to the
specified value, or -1 if none is found.
Joins all elements of an array into a string using separator

join(separator)
lastIndexOf(value)

Returns the last (greatest) index of an element within the array equal to the
specified value, or -1 if none is found.

pop()

Removes the last element from an array and returns that element.

push(value)

Adds one or more elements to the end of an array and returns the new length of
the array.

reverse()
shift()

Reverses the order of the elements of an array the first becomes the last, and
the last becomes the first.
Removes the first element from an array and returns that element.

slice(start [,end])

Extracts a section of an array and returns a new array.

splice(start, count)

Adds and/or removes elements from an array.

toString()

Returns a string representing the array and its elements.

unshift(value)

Adds one or more elements to the front of an array and returns the new length
of the array.
Table 4.11 array object methods
Example: some array functions
<html>
<head>

72

<title>javascript test</title>
<script language="JavaScript">
function arrayFunction() {
var grade = new Array("70", "60", "80", "90", "20");
document.write("<br> Popped: " + grade.pop());
document.write("<br> After poping:");
for(var i=0;i<grade.length; i++)
document.write(" " + grade[i]);
grade.reverse();
document.write("<br>Reversed: ");
for(var i=0;i<grade.length; i++)
document.write(" " + grade[i]);
document.write("<br>Search 80: " + grade.indexOf("80"));
document.write("<br>Converted to string: " + grade.toString());
document.write("<br>Sliced: " + grade.slice(2));
document.write("<br>Spliced: " + grade.splice(1));
}
</script>
</head>
<body onLoad="arrayFunction();">
</body>
</html>

2.2 Working with Loops


A loop is a set of commands that executes repeatedly until a specified condition is met. JavaScript
supports the for, do while, and while loop statements. In addition, you can use the break and continue
statements within loop statements.
Another statement, for...in, executes statements repeatedly but is used for object manipulation.
There are three loop statements in JavaScript:
for Statement
do...while Statement
while Statement
for Loop
A for loop repeats until a specified condition evaluates to false. A for statement looks as follows:

73

for ([initialization]; [condition]; [increment]){


Statement(s)
}
When a for loop executes, the following occurs:
1. The initializing expression initialization, if any, is executed. This expression usually initializes one or
more loop counters. This expression can also declare variables.
2. The condition expression is evaluated. If the value of condition is true, the loop statements execute.
If the value of condition is false, the loop terminates. If the condition expression is omitted entirely,
the condition is assumed to be true.
3. The statement executes. To execute multiple statements, use a block statement ({ ... }) to group
those statements.
4. Execute the increment expression, if there is one, and control returns to step 2.
Example: a program that adds numbers from 0 to 10
var counter = 10;
var sum = 0;
for (var i = 0; i <= counter; i++) {
sum = sum + i;
}
document.write(the sum is + sum);
do...while Statement
The do...while statement repeats until a specified condition evaluates to false. A do...while statement
looks as follows:
do{
statement
}while (condition);
statement executes once before the condition is checked. If condition is true, the statement executes
again. At the end of every execution, the condition is checked. When the condition is false, execution
stops and control passes to the statement following do...while.
Example: the do loop iterates at least once and reiterates until i is no longer less than 5.
i=1;
do
{
i += 1;
document.write(i);
} while (i < 5);

74

while Statement
A while statement executes its statements as long as a specified condition evaluates to true. A while
statement looks as follows:
while (condition){
statement
}
The condition test occurs before statement in the loop are executed. If the condition returns true,
statement is executed and the condition is tested again. If the condition returns false, execution stops
and control is passed to the statement following while.
Example 1: the following while loop iterates as long as n is less than three:
n = 0;
x = 0;
while (n < 3)
{
n++;
x += n;
}
break and continue statements
Use the break statement to terminate a loop, switch, or label statement. It is used to stop the loop when
the condition we need is fulfilled.
Example: the following example loops until the value of loop counter is 5:
for (i = 0; i < 100; i++) {
if (i== 5)
break;
}
The continue statement can be used to restart a while, do-while, for, or label statement. When you use
continue, it terminates the current iteration and continues execution of the loop with the next iteration.
In contrast to the break statement, continue does not terminate the execution of the loop entirely. In a
while loop, it jumps back to the condition check, and in a for loop, it jumps to the increment-expression.
Example: a program that adds numbers between 0 and 100 with the exception of 60, 70, and 80
var counter = 100;
var sum = 0;
for (var i = 0; i <= counter; i++)
{
if(i==60 || i==70 || i==80)
continue;

75

sum = sum + i;
}
document.write(the sum is + sum);

Practice 4.4
1. Write a program that accepts marks of 20 students.
2. Write a program that adds numbers between 1 and 100(1+2+3+..+99+100).
3. Write a program that displays all even numbers between 50 and 100

2.3 JavaScript Functions


Functions are one of the fundamental building blocks in JavaScript. A function is a set of statements that
performs a specific task. To use a function, you must first define it; then your script can call it.
Defining Functions
A function definition consists of the function keyword, followed by:
The name of the function.
A list of arguments to the function, enclosed in parentheses and separated by commas.
The JavaScript statements that define the function, enclosed in curly braces, { }. The statements
in a function can include calls to other functions defined in the current application.
The syntax to define function:
function functionName ( [parameter1]...[,parameterN] ) {
statement[s]
}
Function names have the same restrictions as variable names. You should devise a name that succinctly
describes what the function does. It is possible to use multiword names with the interCap (internally
capitalized) format that start with a verb because functions are action items.
Example: the following code defines a simple function named square:
function square(number) {
return number * number;
}
The function square takes one argument, called number. The function consists of one statement that
indicates to return the argument of the function multiplied by itself. The return statement specifies the
value returned by the function.
Function Parameters
You can define functions so they receive parameter values from the calling statement. Parameters (also
known as arguments) provide a mechanism for handing off a value from one statement to another by

76

way of a function call. If no parameters occur in the function definition, both the function definition and
call to the function have only empty sets of parentheses.
When a function receives parameters, it assigns the incoming values to the variable names specified in
the function definitions parentheses. Consider the following script segment:
function sayHiToFirst(first, second, third) {
alert(Say hello, + first)
}
sayHiToFirst(Gracie, George, Harry)
sayHiToFirst(Larry, Moe, Curly)
After the function is defined in the script, the next statement calls that very function, passing three
strings as parameters. The function definition automatically assigns the strings to variables first, second,
and third. Therefore, before the alert() statement inside the function ever runs, first evaluates to
Gracie, second evaluates to George, and third evaluates to Harry. In the alert() statement, only the
first value is used and the alert reads
Say hello, Gracie
When the user closes the first alert, the next call to the function occurs. This time through, different
values are passed to the function and assigned to first, second, and third. The alert dialog box reads
Say hello, Larry
Unlike other variables that you define in your script, function parameters do not use the var keyword to
initialize them. They are automatically initialized whenever the function is called.
The return Statement
The return statement is used to specify the value that is returned from the function. So, functions that
are going to return a value must use the return statement. The example below returns the product of
two numbers (a and b):
<html>
<head>
<script type="text/javascript">
function product(op1, op2){
return op1*op2;
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(product(4,3));
</script>
</body>

77

</html>

Practice 4.5
1. Write a function that that accepts two numbers and displays their sum, difference, product,
quotient, and modulus.
2. Write a JavaScript program accepts five numbers and return their average.

3. JavaScript Objects and Events


3.1 Working with JavaScript Objects
JavaScript has many built-in objects that you can use to perform different activities. The most
important objects are discussed next.
3.1.1 Math Object
The predefined Math object has properties and methods for mathematical constants and functions. For
example, the Math objects PI property has the value of pi (3.141...), which you would use in an
application as
Math.PI
Similarly, standard mathematical functions are methods of Math. These include trigonometric,
logarithmic, exponential, and other functions. For example, if you want to use the trigonometric
function sine, you would write:
Math.sin(1.56)
Note that all trigonometric methods of Math take arguments in radians.
Math Object Properties
Property

Value

Description

Math.E

2.718281828459045091

Eulers constant

Math.LN2

0.6931471805599452862

Natural log of 2

Math.LN10

2.302585092994045901

Natural log of 10

Math.LOG2E

1.442695040888963387

Log base-2 of E

Math.LOG10E

0.4342944819032518167

Log base-10 of E

Math.PI

3.141592653589793116

Math.SQRT1_2

0.7071067811865475727

Square root of 1/2

Math.SQRT2

1.414213562373095145

Square root of 2

Table 4.12 Math object properties

78

Functions of the Math Object


abs (x): returns the absolute value of x; the result has the same magnitude as x but has positive sign.
acos (x): returns the arc cosine of x. The result is expressed in radians and ranges from +0 to +.
asin (x): returns the arc sine of x. The result is expressed in radians and ranges from /2 to +/2.
atan (x): returns the arc tangent of x. The result is expressed in radians and ranges from /2 to +/2.
atan2 (y, x)
Returns the arc tangent of the quotient y/x of the arguments y and x, where the signs of y and x are
used to determine the quadrant of the result. Note that it is intentional and traditional for the twoargument arc tangent function that the argument named y be first and the argument named x be
second. The result is expressed in radians and ranges from to +.
cos (x): returns the cosine of x. The argument is expressed in radians.
Example:
Math.cos(0);
exp (x): returns the exponential function of x (e raised to the power of x, where e is the base of the
natural logarithms).
Example:
Math.exp(3);
floor (x): returns the greatest number that is not greater than x and is equal to a mathematical integer. If
x is already an integer, the result is x. The value of Math.floor(x) is the same as the value of -Math.ceil(x).
ceil (x): returns the smallest (closest to ) number value that is not less than x and is equal to a
mathematical integer. If x is already an integer, the result is x. The value of Math.ceil(x) is the same as
the value of -Math.floor(-x).
Example:
Math.floor(1.6); //result: 1
Math.ceil(1.6); //result: 2
log (x): returns the natural logarithm of x.
Example:
Math.log(20);
max ( [ value1 [ , value2 [ , ... ] ] ] )
Given zero or more arguments, calls ToNumber on each of the arguments and returns the largest of the
resulting values.

79

min ( [ value1 [ , value2 [ , ... ] ] ] )


Given zero or more arguments, calls ToNumber on each of the arguments and returns the smallest of
the resulting values.
pow (x, y): returns an result of raising x to the power y.
Example:
Math.pow(5,2); //output: 25
random ( )
Returns a number value with positive sign, greater than or equal to 0 but less than 1, chosen randomly
or pseudo randomly with approximately uniform distribution over that range. This function takes no
arguments.
round (x)
Returns the number value that is closest to x and is equal to a mathematical integer. If two integer
number values are equally close to x, then the result is the number value that is closer to +. If x is
already an integer, the result is x.
Example:
Math.round(3.5); // output: 4
Math.round(3.5); //output: 3.
The value of Math.round(x) is the same as the value of Math.floor(x+0.5), except when x is 0 or is less
than 0 but greater than or equal to -0.5; for these cases Math.round(x) returns 0, but Math.oor(x+0.5)
returns +0.
sin (x): returns the sine of x. The argument is expressed in radians.
Example:
Math.sin(90);
sqrt (x): returns the square root of x.
tan (x): returns the tangent of x. The argument is expressed in radians.
Example:
Math.tan(45);

Practice 4.6
1. Write a program that calculates quadratic equation.
2. Write a program that calculates 1030
3. Write a program that returns the largest and smallest numbers from the given number list.

80

3.1.2 Date Object


Most of your date and time work is done with the Date object. The basic syntax for generating a new
date object is as follows:
var dateObjectName = new Date([parameters])
The parameter can be:
new Date(Month dd, yyyy hh:mm:ss)
new Date(Month dd, yyyy)
new Date(yy,mm,dd,hh,mm,ss)
new Date(yy,mm,dd)
new Date(milliseconds)
Method

Value Range

Description

dateObj.getTime()

0-...

returns Milliseconds since 1/1/70 00:00:00 GMT

dateObj.getYear()

70-...

dateObj.getFullYear()

1970-...

returns Specified year minus 1900


returns four-digit year for 2000+
returns four-digit year (Y2K-compliant)

dateObj.getMonth()

0-11

returns Month within the year (January = 0)

dateObj.getDate()

1-31

returns Date within the month

dateObj.getDay()

0-6

returns Day of week (Sunday = 0)

dateObj.getHours()

0-23

returns Hour of the day in 24-hour time

dateObj.getMinutes()

0-59

returns Minute of the specified hour

dateObj.getSeconds()

0-59

returns Second within the specified minute

dateObj.setTime(val)

0-...

sets Milliseconds since 1/1/70 00:00:00 GMT

dateObj.setYear(val)

70-...

dateObj.setMonth(val)

0-11

sets Specified year minus 1900


sets four-digit year for 2000+
sets Month within the year (January = 0)

dateObj.setDate(val)

1-31

sets Date within the month

dateObj.setDay(val)

0-6

sets Day of week (Sunday = 0)

dateObj.setHours(val)

0-23

sets Hour of the day in 24-hour time

dateObj.setMinutes(val)

0-59

sets Minute of the specified hour

dateObj.setSeconds(val)

0-59

sets Second within the specified minute

Table 4.13 Date object methods


Example: display current date and time

81

today = new Date();


var date = today.getDate();
var month = today.getMonth();
var year = today.getFullYear();
document.write(Todays date: +date+/+month+/+year);
output:
Date today: 4/11/2010
Example: to set date to some past time like birth date
myBirthday = new Date(September 11, 2001)
result = myBirthday.getDay() // result = 2, a Tuesday
myBirthday.setYear(2002) // bump up to next year
result = myBirthday.getDay() // result = 3, a Wednesday

3.1.3 String Object


The syntax to define string object is:
var stringVar = new String(characters)
Method

Description

charAt(index)

Returns the character at the specified index.

charCodeAt(index)

Returns a number indicating the Unicode value of the character at the


given index.
Combines the text of two strings and returns a new string.

concat(string)
indexOf(string, [start])
lastIndexOf(string,[start])

Returns the index within the calling String object of the first occurrence of
the specified value, or -1 if not found.
Returns the index within the calling String object of the last occurrence of
the specified value, or -1 if not found.

localeCompare(string2)

Returns a number indicating whether a reference string comes before or


after or is the same as the given string in sort order.

length()

Returns the length of the string.

match(regExpression)

Used to match a regular expression against a string.

replace(regExpression,replacer) Used to find a match between a regular expression and a string, and to
replace the matched substring with a new substring.
search(regExpression)
Executes the search for a match between a regular expression and a
specified string.
slice(startIndex [,end])
Extracts a section of a string and returns a new string.

82

split(delimiter [,limit])
substr(start [, length])
substring(start, end)
toLocaleLowerCase()

Splits a String object into an array of strings by separating the string into
substrings.
Returns the characters in a string beginning at the specified location
through the specified number of characters.
Returns the characters in a string between the two indexes into a string.

toLowerCase()

The characters within a string are converted to lower case while


respecting the current locale.
The characters within a string are converted to upper case while
respecting the current locale.
Returns the calling string value converted to lower case.

toString()

Returns a string representing the specified object.

toUpperCase()

Returns the calling string value converted to uppercase.

toLocaleUpperCase()

Table 4.14 string object methods


Example:
var name = new String(Konrad Zuse);
name.concat( - created the first computer);
name.substring(0,10);
name.indexOf(Zuse);
name.replace(a,#);
name.toUpperCase();
Output:
Konrad Zuse - created the first computer
Konrad Zuse
7
KONRAD ZUSE
Konr#d Zuse

3.1.4 Document Object


Contains information on the current document. Document object contains properties and methods that
can be used to access the page elements.
Properties:
title - Current document title. If no title is defined, title contains Untitled.
location - Full URL of the document.
lastModified - A Date object-compatible string containing the date the document was last
modified.

83

bgColor - Background color, expressed as a hexadecimal RGB value compatible with HTML
syntax (for example, #FFFFF" for white). Equivalent to the BGCOLOR attribute of the <BODY>
tag.
fgColor - Foreground (text) color, expressed as a hexadecimal RGB value compatible with HTM
syntax. Equivalent to the TEXT attribute of the <BODY> tag.
linkColor - Hyperlink color, expressed as a hexadecimal RGB value compatible with HTML syntax.
Equivalent to the vlinkColor Visited hyperlink color, expressed as a hexadecimal RGB value
compatible with HTML syntax. Equivalent to the VLINK attribute of the <BODY> tag.
alinkColor - Activated (after button press, before button release) hyperlink color, expressed as a
hexadecimal RGB value compatible with HTML syntax. Equivalent to the ALINK attribute of the
<BODY> tag.
forms[ ] - Array of form objects in the document, in the order specified in the source. Each form
has its own form object.
forms.length - The number of form objects within the document.
links[ ] - Array objects corresponding to all HREF links in the document, in the order specified in
the source.
links.length - The number of HREF links in the document.
anchors[ ] - Array of all "named" anchors (between the <A NAME=""> and </A> tags) within the
document, in the order specified in the source.
anchors.length - The number of named anchors in the document.
images[] - Image objects that correspond to each image on the page.
applets[] - Java applet objects that correspond to each applet on the page.
embeds[] - Plugins object that represent each plug-in on the page.

Methods:
write("string")-Writes string to the current window. string may include HTML tags.
writeln("string") - Performs the same as write(), but adds a carriage return. This affects only
preformatted text (inside a <PRE> or <XMP> tag).
clear( ) - Clears the window.
close( ) - Closes the window.

3.1.5 History Object


The history object contains a list of strings representing the URLs the client has visited. You can access
the current, next, and previous history entries by using the history objects current, next, and previous
properties. You can access the other history values using the history array. This array contains an entry
for each history entry in source order; each array entry is a string containing a URL.
You can also redirect the client to any history entry by using the go method. For example, the following
code loads the URL that is two entries back in the clients history list.
history.go(-2)

84

The following code reloads the current page:


history.go(0)
Properties

Methods

Current

back()

Length

forward()

Next

go()

Previous
Table 4.15 History object properties and methods
history.back() goes back to last visited page
history.forward() goes forward just like clicking forward button on toolbar
history.go(location) goes to the specified history location

3.1.6 Number Object


The Number object contains some information and power of value to serious programmers. The
Number.MAX_VALUE and Number.MIN_VALUE properties belong to the static Number object. They
represent constants for the largest and smallest possible positive numbers that JavaScript can work
with. Their actual values are 1.7976931348623157 * 10308, and 5 * 10-324, respectively.
A number that falls outside the range of allowable numbers is equal to the constant
Number.POSITIVE_INFINITY or Number.NEGATIVE_INFINITY.
Properties
MAX_VALUE

Methods
toExponential()

MIN_VALUE

toFixed()

NaN

toLocaleString()

NEGATIVE_INFINITY

toString()

POSITIVE_INFINITY

toPrecision()
valueOf()

There are three Number object methods that let scripts control the formatting of numbers for display as
string text. Each method has a unique purpose, but they all return strings. You should perform all math
operations as unformatted number objects because the values have the most precision. Only after you
are ready to display the results should you use one of these methods to convert the number to a string
for display as body text or assignment to a text field.

85

The toExponential() method forces a number to display in exponential notation. The parameter is an
integer specifying how many digits to the right of the decimal should be returned. For example, if a
variable contains the numeric value 345, applying toExponential(3) to that value yields 3.450e+2, which
is JavaScripts exponential notation for 3.45 102.
Use the toFixed() method when you want to format a number with a specific number of digits to the
right of the decimal. This is the method you use, for instance, to display the results of a financial
calculation in units and hundredths of units (for example, dollars and cents). If the number being
formatted has more numbers to the right of the decimal, the method rounds the rightmost visible digit.
For example, the value 123.455 fixed to two digits to the right of the decimal is rounded up to 123.46.
But if the starting value is 123.4549, the method ignores the 9 and sees that the 4 to the right of the 5
should be rounded down; therefore, the result is 123.45.
The final method is toPrecision(), which enables you to define how many total digits (including digits to
the left and right of the decimal) to display of a number. In other words, you define the precision of a
number. The following list demonstrates the results of several parameter values signifying a variety of
precisions:
var num = 123.45
num.toPrecision(1) // result = 1e+2
num.toPrecision(2) // result = 1.2e+2
num.toPrecision(3) // result = 123
num.toPrecision(4) // result = 123.5
num.toPrecision(5) // result = 123.45
num.toPrecision(6) // result = 123.450

3.1.7 Window Object


window.open() - this method opens a new window. The syntax is:
window.open(URL, name [, windowfeatures]);
Parameters:
URL is a string that points to the window you want to open.
name is a string that names the new window.
windowfeatures is one or more of the following in a comma-separated list:
toolbar - toolbar is present
location Location bar is present
directories
status statusbar is present
menubar menubar is present
scrollbars scrollbars are present
resizable window is resizable
copyhistory

86

width width of the window


height height of the window

window.open(btest2.html, testing , toolbar,status);

Method

Description

window.alert(message)

Displays an alert dialog.

window.back()

Moves back one in the window history.

window.blur()
window.captureEvents((Event.eventType)

Sets focus away from the window.


Registers the window to capture all specified events.

window.clearInterval(intervalID)

Clears a delay thats been set for a specific function.

window.clearTimeout(timeoutID)

Clears the delay set by window.setTimeout().

window.close()

Closes the current window.

window.confirm(message)
window.dump(message)

Displays a dialog with a message that the user needs to


respond to.
Writes a message to the console.

window.escape(text)

Encodes a string.

window.focus()

Sets focus on the current window.

window.forward()

Moves the window one document forward in the history.

window.GetAttention()

Flashes the application icon to get user attention.

window.getSelection()
window.home()

Returns the selection object representing the selected


item(s).
Returns the browser to the home page.

window.moveBy(pixelX, pixelY)

Moves the current window by a specified amount.

window.moveTo(x, y)

Moves the window to the specified coordinates.

window.open(URL,name[,features])

Opens a new window.

window.print()

Prints the current document.

window.prompt(message[,default])

Returns the text entered by the user in a prompt dialog.

window.releaseEvents(Event.eventType)
window.resizeBy(pixelX, pixelY)

Releases the window from trapping events of a specific


type.
Resizes the current window by a certain amount.

window.resizeTo(iWidth, iHeight)

Dynamically resizes window.

window.scroll(x-coord, y-coord)

Scrolls the window to a particular place in the document.

window.scrollBy(pixelX, pixelY)
window.scrollByLines(lines)

Scrolls the document in the window by the given amount.


Scrolls the document by the given number of lines.

87

window.scrollTo(x-coord, y-coord)

Scrolls the current document by the specified number of


pages.
Scrolls to a particular set of coordinates in the document.

window.setCursor(cursortype)

Changes the cursor.

window.setInterval(funcName, delay)

Set a delay for a specific function.

window.setTimeout(funcName, delay)

Sets a delay for executing a function.

window.scrollByPages(pages)

Some of the properties of Window object are:


window.name - Gets/sets the name of the window.
window.location - Gets/sets the location, or current URL, of the window object.
window.status - Gets/sets the text in the statusbar at the bottom of the browser.
window.statusbar - Returns the statusbar object, whose visibility can be toggled in the window.
window.toolbar - Returns the toolbar object, whose visibility can be toggled in the window.
window.menubar - Returns the menubar object, whose visibility can be toggled in the window.
window.length - Returns the number of frames in the window.

Practice 4.7
1. Write a program that counts how many letters are there in your full name.
2. Write a program that has two buttons where one of the button acts like the back button in
toolbar and the other acts like forward button in toolbar.
3. Write a program that returns array of images and links in your web page.

3.2 Managing Events


Events are occurrences generated by the browser, such as loading a document, or by the user, such as
moving the mouse. They are the user and browser activities to which we may respond dynamically with
a scripting language like JavaScript.
There are several more events that we can capture with JavaScript, but the ones listed in table 4.16 are,
by far, the most popular. Here is a short list of events that Web developers like to capture:
Event

Event Handler

Description

Load

onLoad

Browser finishes loading a Web document

Unload

onUnload

Visitor requests a new document in the browser window

Mouseover

onMouseOver

Mouseout

onMouseOut

Visitor moves the mouse over some object in the document


window
Visitor moves the mouse off of some object in the document
window

88

MouseDown

onMouseDown

A mouse button was pressed

MouseMove

onMouseMove

The mouse moved

MouseUp

onMouseUp

The mouse button was released

Select

onSelect

Text has been selected.

Click

onClick

Visitor clicks the mouse button

Focus

onFocus

Blur

onBlur

Visitor gives focus to or makes active a particular window or


form element by clicking on it with a mouse or other pointing
device or tabbing to it
A form field lost the focus (user moved to another field)

Change

onChange

Visitor changes the data selected or contained in a form element

Submit

onSubmit

Visitor submits a form

Reset

onReset

Visitor resets a form

Abort

onAbort

An image failed to load

Change

onChange

The contents of a field has changed

DblClick

onDblClick

User double-clicked on this item

Error

onError

An error occurred while loading an image

Keydown

onKeyDown

A key was pressed

KeyPress

onKeyPress

A key was pressed OR released

KeyUP

onKeyUp

A key was released

Table 4.16 most commonly used events


Example: a program that adds or subtracts two numbers when respective button is clicked
<html>
<head>
<script language="JavaScript">
function adder(num1, num2)
{
var sum = 0;
sum = num1 + num2;
document.write("The sum is " + sum);
}
function subtractor(num1, num2)
{
var difference = 0;

89

difference = num1 - num2;


document.write("The difference is " + difference);
}
</script>
</head>
<body>
<form name="event_example">
<input type="button" value="add" name="add" onClick="adder(10,30)">
<input type="button" value="subtract" name="subtract" onClick="subtractor(20,50)">
</form>
</body>
</html>

3.3 Form Processing and Validation


3.3.1 Accessing Form and Form Elements
It is possible to access form and form elements from JavaScript. You can set attributes for NAME,
TARGET, ACTION, METHOD, and ENCTYPE for form. Each of these is a property of a FORM object,
accessed by all lowercase versions of those words, as in
document.forms[0].action
//based on forms array of the document
document.formName.action //references exact form b name
To change any of these properties, simply assign new values to them:
document.registration.action = http://www.giantco.com/cgi/login.pl
Forms support different events. The event handlers used with form object are:
onFocus -- an event is triggered with a form object gets input focus (the insertion point is clicked
there).
onBlur this event is triggered when a form object loses input focus.
onChange -- an event is triggered when a new item is selected in a list box. This event is also
trigged with a text or text area box loses focus and the contents of the box has changed.
onSelect -- an event is triggered when text in a text or text area box is selected.
onSubmit -- an event is triggered when the form is submitted to the server (more about this
important hander later in the column).
Text boxes and Text areas
Text fields have a value property. The value property of the input text box, is both readable and
writable. That is, you can read whatever is typed into the textfield, and you can write data back into it.
To access text input fields, you can use the syntax:
value = document.formName.textName.value; //read content
document.formName.textName.value = value; //set content

90

Text area has the same property as text field: the value property. Using this property, you can set or
read the content of text area.
Example:
<HTML>
<HEAD>
<TITLE>Test Input</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function hello ()
{
var urname = document.test.name.value;
alert ("Hello, " + urname);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="test" ACTION="" METHOD="GET">
Enter your name: <INPUT TYPE="text" NAME="name" VALUE=""><br>
<INPUT TYPE="button" NAME="button" Value="Say Hello" onClick="hello()">
</FORM>
</BODY>
</HTML>
Checkboxes and Radio Buttons
To define radio buttons for JavaScript, provide each object with the same name. JavaScript will create an
array using the name you've provided; you then reference the buttons using the array indexes. The first
button in the series is numbered 0, the second is numbered 1, and so forth. Use the checked property to
know the state of the individual radio buttons.
<HTML>
<HEAD>
<TITLE>Test Input</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function hello () {
var urname = document.test.name.value;
var sex;
if(document.test.sex[0].checked)
sex="male";
else if(document.test.sex[1].checked)
sex="female";
alert ("Hello, " + urname + "! Your are "+sex);
}

91

</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="test" ACTION="" METHOD="GET">
Enter your name: <INPUT TYPE="text" NAME="name" VALUE=""><br>
Sex: <INPUT TYPE="radio" NAME="sex" Value="Male">Male<BR>
<INPUT TYPE="radio" NAME="sex" Value="Female">Female<BR>
<INPUT TYPE="button" NAME="button" Value="Say Hello" onClick="hello()">
</FORM>
</BODY>
</HTML>
Check boxes are stand-alone elements which means they don't interact with neighboring elements like
radio buttons do. Using JavaScript you can test if a check box is checked using the checked property.
Likewise, you can set the checked property to add or remove the checkmark from a check box.
Using Selection Lists
List boxes let you pick the item you want out of a multiple-choice box. Use the selectedIndex property to
test which option item is selected in the list. The item is returned as an index value, with 0 being the first
option, 1 being the second, and so forth. If no item is selected, the value is -1.
<HTML>
<HEAD>
<TITLE>List Box Test</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function testSelect () {
Item = document.sele.list.selectedIndex;
Result = document.sele.list.options[Item].text;
alert (Result);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="sele" ACTION="" METHOD="GET">
Fruit: <SELECT NAME="list" SIZE="1">
<OPTION>none</OPTION>
<OPTION>Orange</OPTION>
<OPTION>Apple</OPTION>
<OPTION>Papaya</OPTION>
<OPTION>Banana</OPTION>
</SELECT>
<INPUT TYPE="button" NAME="button" Value="Test" onClick="testSelect()">

92

</FORM>
</BODY>
</HTML>

3.3.2 Form Validation


Forms are widely used on the Internet. The form input is often sent back to the server or mailed to a
certain e-mail account. But how can you be certain that a valid input was filled by the user? With the
help of JavaScript the form input can easily be checked before sending it over the Internet. It is sent only
if the input is valid.
Form data that typically are checked by a JavaScript could be:
has the user left required fields empty?
has the user entered a valid e-mail address?
has the user entered a valid date?
has the user entered text in a numeric field?
Let us see an example. First of all we create an HTML-page that contains form. The form contains three
text inputs, a text area, and a button. The user has to write his name into the first, age in the second, an
e-mail address in the third text fields, and message in the text area.
In the name field, you will receive an error message when nothing is entered. Of course, this does not
prevent the user from entering any wrong name. The browser even accepts numbers. So if you enter
'17' you will get 'Hi 17!'. So this might not be a good check in this particular example. However, you can
add a check for numbers in the name field and reject the name if you like.
Age is number and we expect a positive number only. If user enters characters which are not number, or
negative value, it is not valid age. So the script should check this and determine its validity.
The email field is a little bit more sophisticated. It shouldnt work if there is no @ symbol in the email
because valid email addresses contain that symbol. The criteria for accepting the input as a valid e-mail
address is the @. The person may enter wrong emails which could pass as valid but this is the least
check we could do.

93

Figure 4.1 form validation


Example: a script that creates and validates the above form:
<html>
<head>
<script language="JavaScript">
function check(form)
{
if (form.urname.value == "")
alert("Please enter a string as your name!")
else
alert("Hi " + form.urname.value + "! Name ok!");
if(form.age.value < 0 || form.age.value=="")
alert("Age should be number and greater than 0");
else
alert("Age ok");
if (form.email.value == "" || form.email.value.indexOf('@', 0) == -1)
alert("No valid e-mail address!");
else
alert("Email oK!");
if(form.urmessage.value=="")
alert("No message written");

94

else
alert("Message ok");
}
</script>
</head>
<body>
<h2> <u> Form validation </u> </h2>
<form name="first">
Enter your name: <input type="text" name="urname"> <br>
Enter your age: <input type="text" name="age"> <br>
Enter your e-mail address: <input type="text" name="email"> <br>
write message: <textarea name="urmessage" cols=40 rows=10></textarea><br><br>
<input type="button" name="validate" value="Check Input" onClick="check(this.form)">
</body>
</html>

Practice 4.8
1. Write a program that uses forms to accept two numbers and calculates their average when a
button is clicked.
2. Can you create a simple JavaScript calculator?

95

Unit Five: Dynamicity in HTML: DHTML and DOM


1. DOM
1.1 Introduction to DOM
The Document Object Model is an API for HTML and XML documents. It does two things for web
developers: it provides a structural representation of the document, and it defines the way that structure
is to be accessed from script, allowing you to get at the web page as a structured group of nodes.
Essentially, it connects web pages to scripts or programming languages.
All of the properties, methods, and events available to the web developer for manipulating and creating
web pages are organized into objects (e.g., the document object that represents the document itself, the
table object that represents a HTML table elements, and so forth). Those objects are accessible via
scripting languages in most recent web browsers.
The DOM is most often used in conjunction with JavaScript. That is, the code is written in JavaScript, but
it uses the DOM to access the web page and its elements. The DOM is not a programming language, but
without it, the JavaScript language wouldnt have any model or notion of the web pages, XML pages, and
elements with which it is usually concerned. Every element in a documentthe document as a whole,
the head, tables within the document, table headers, text within the table cellsis part of the document
object model for that document, so they can all be accessed and manipulated using the DOM and a
scripting language like JavaScript.
The DOM was designed to be independent of any particular programming language, making the
structural representation of the document available from a single, consistent API. Though we focus
exclusively on JavaScript in this course, implementations of the DOM can be built for any language.

1.2 DOM Nodes and Node Tree


The HTML DOM views a HTML document as a tree-structure. The tree structure is called a node-tree. All
nodes can be accessed through the tree. Their contents can be modified or deleted, and new elements
can be created.

96

Figure 5.1 set of nodes, and the connections between them


The nodes in the node tree have a hierarchical relationship to each other. The terms parent, child, and
sibling are used to describe the relationships. Parent nodes have children. Children on the same level are
called siblings (brothers or sisters).
In a node tree, the top node is called the root
Every node, except the root, has exactly one parent node
A node can have any number of children
A leaf is a node with no children
Siblings are nodes with the same parent
Look at the following HTML fragment:
<html>
<head>
<title>DOM Tutorial</title>
</head>
<body>
<h1>DOM Lesson one</h1>
<p>Hello world!</p>
</body>
</html>
From the HTML above:
The <html> node has no parent node; it is the root node
The parent node of the <head> and <body> nodes is the <html> node
The parent node of the "Hello world!" text node is the <p> node
And

The <html> node has two child nodes; <head> and <body>

97

The <head> node has one child node; the <title> node
The <title> node also has one child node; the text node "DOM Tutorial"
The <h1> and <p> nodes are siblings, and both child nodes of <body>
The DOM Lesson one is the child of <h1> node and Hello world is the child node of <p>
node

1.3 DOM Properties and Methods


Some DOM properties:
x.innerHTML - the text value of x
x.nodeName - the name of x
x.nodeValue - the value of x
x.parentNode - the parent node of x
x.childNodes - the array of child nodes of x
x. firstChild - the first direct child of the current node
x.lastChild - the last child of the current node
x.nextSibling - the node immediately following the current one in the tree
x.previousSibling - the node immediately previous to the current one in the tree
x.title - the title of the document.
x.attributes - the attributes nodes of x
x.id - gets/sets the id of the current element.
Note that in the list above, x is a node object (HTML element).
Some DOM methods:
x.getElementById(id) - get the element with a specified id
x.getElementsByTagName(name) - get all elements with a specified tag name
x.appendChild(node) - insert a child node to x
x.removeChild(node) - remove a child node from x
createElement() creates new HTML tag
createTextNode() creates new text content
Note that in the list above, x is a node object (HTML element).
The two important ones for H TML documents are createElement() and createTextNode(). The first
generates an element with whatever HTML tag you pass as a parameter. The second generates a text
node with whatever text you pass to it.
The following is a code to get the innerHTML (text) from the <p> element with id="intro":
Example:
<html>
<body>

98

<p id="intro">Hello World!</p>


<script type="text/javascript">
txt = document.getElementById("intro").innerHTML;
document.write("<p>The text from the intro paragraph: " + txt + "</p>");
</script>
</body>
</html>
Example: a DOM that creates new paragraph and add to HTML page
var newParagraph = document.createElement("P");
newParagraph.id = "IP";
var newText = document.createTextNode("This is the new paragraph.");
newParagraph.appendChild(newText);
document.body.appendChild(newParagraph);

1.4 DOM Node Access


With the DOM, you can access every node in an HTML document. You can access a node in three ways:
By using the getElementById() method
By using the getElementsByTagName() method
By navigating the node tree, using the node relationships
The getElementById() Method
The getElementById() method returns the element with the specified ID:
node.getElementById("id");
The following example gets the element with id="intro":
document.getElementById("intro");
The getElementsByTagName() Method
getElementsByTagName() returns all elements with a specified tag name. Syntax:
node.getElementsByTagName("tagname");
The following example returns a nodeList of all <p> elements in the document:
document.getElementsByTagName("p");
The following example returns a nodeList of all <p> elements that are descendants of the element with
id="main":
document.getElementById('main').getElementsByTagName("p");
DOM Node List
The getElementsByTagName() method returns a node-list. A node-list is an array of nodes.

99

The following code selects all <p> nodes in a node-list:


x=document.getElementsByTagName("p");
The nodes can be accessed by index number. To access the second <p> you can write:
y = x[1];
The index starts at 0.
DOM Node List Length
The length property defines the number of nodes in a node-list.
You can loop through a node-list by using the length property:
x=document.getElementsByTagName("p");
for (i = 0; i < x.length; i++)
{
document.write(x[i].innerHTML);
document.write("<br />");
}
Example explained:
Get all <p> element nodes
For each <p> element, output the value of its text node

Navigating Node Relationships


The three properties; parentNode, firstChild, and lastChild, follow the document structure and allow
short-distance travel in a document.
Look at the following HTML fragment:
<html>
<body>
<p>Hello World!</p>
<div>
<p>The DOM is very useful!</p>
<p>This example demonstrates node relationships.</p>
</div>
</body>
</html>
In the HTML code above, the first p element is the first child node (firstChild) of the body element, and
the div element is the last child node (lastChild) of the body element. The parent node (parentNode) of
the first p element and the div element, is the the body element, and the parent node of the p elements
inside the div element, is the div element.

100

The firstChild property can also be used to access the text of an element:
Example
<html>
<body>
<p id="intro">Hello World!</p>
<script type="text/javascript">
x=document.getElementById("intro");
document.write(x.firstChild.nodeValue);
</script>
</body>
</html>

DOM Root Nodes


There are two special document properties that allow access to the tags:
document.documentElement - returns the root node of the document
document.body - gives direct access to the <body> tag

Practice 5.1
1. Can you write a DOM program that can change the content of the given <p> tag?
2. Write a DOM program that returns the title of the document
3. Write a program that adds a <p> child to HTML <body>.

1.5 DOM Events


Every element on a web page has certain events which can trigger JavaScript functions. For example, we
can use the onClick event of a button element to indicate that a function will run when a user clicks on
the button. We define the events in the HTML elements.
Examples of events:
A mouse click
A web page or an image loading
Mousing over a hot spot on the web page
Selecting an input box in an HTML form
Submitting an HTML form
A keystroke
Events are normally used in combination with functions, and the function will not be executed before
the event occurs.

101

2. Dynamic HTML(DHTML)
2.1 Introduction to DHTML
DHTML stands for Dynamic HTML. DHTML is not a language or a web standard. To most people DHTML
means the combination of HTML, JavaScript, DOM and CSS. It is the art of combining HTML, JavaScript,
DOM, and CSS.
According to the World Wide Web Consortium (W3C):
Dynamic HTML is a term used by some vendors to describe the combination of HTML, style sheets and
scripts that allows documents to be animated.
DHTML is not a scripting language like JavaScript. It is a feature that allows your browser to be dynamic.
Also, DHTML is not one particular, technology or set of features. It includes several technologies and
describes how these technologies interact.
Web pages built with Dynamic HTML are richer and more interactive, react faster, and dont use much
bandwidth. The major elements of DHTML include HTML code, scripting languages such as JavaScript,
the Document Object Model, Cascading Style Sheets, multimedia filters, and the browser itself.

2.2 DHTML JavaScript


A JavaScript can also be used to change the content or attributes of HTML elements. To change the
content of an HTML element:
document.getElementById(id).innerHTML=new HTML
To change the attribute of an HTML element:
document.getElementById(id).attribute=new value
A JavaScript can also change the style of HTML elements. To change the style of an HTML element:
document.getElementById(id).style.property=new style
Example: photo slide show DHTML in JavaScript (you need pictures named flat1.jpg, flat2.jpg, )
<html>
<head>
<script language="JavaScript">
photonames = new Array('flat1.jpg','flat2.jpg','flat3.jpg','flat4.jpg','flat5.jpg');
currentphoto = 0;
document.write('<img src="' + photonames[0] + '" id="photo" alt="photo" /\>');
function slideshow(direction)
{
if(currentphoto + direction < 0)
{

102

alert("This is the first picture");


return;
}
if(currentphoto + direction > photonames.length-1)
{
alert('This is the last picture');
return;
}
currentphoto += direction;
updatecounter();
document.images.photo.src = photonames[currentphoto];
}
function updatecounter()
{
counter = '&nbsp;&nbsp;'+(currentphoto+1);
counter += ' of ' + photonames.length + '&nbsp;&nbsp;';
document.getElementById('counter').innerHTML = counter;
alert("done");
}
</script>
</head>
<body>
<p>
<a href="#" onclick="slideshow(-1);return false">&#60;&#60;</a>
<span id="counter"></span>
<a href="#" onclick="slideshow(1);return false">&#62;&#62;</a>
</p><br />
</body>
</html>

2.3 DHTML DOM


The HTML DOM defines the objects and properties of all HTML elements, and the methods to access
them. In other words, the HTML DOM is a standard for how to get, change, add, or delete HTML
elements. Using HTML DOM, it is possible to change content of HTML elements.
Example: The following example changes the content of an h1 element:
<html>
<body>
<h1 id="header">Old Header</h1>
<script type="text/javascript">
document.getElementById("header").innerHTML="New Header";

103

</script>
</body>
</html>
Example: The following example changes the src attibute of an img element:
<html>
<body>
<img id="image" src="smiley.gif">
<script type="text/javascript">
document.getElementById("image").src="landscape.jpg";
</script>
</body>
</html>

2.4 DHTML CSS


To change the style of the current HTML element, use the following statement:
this.style.property=new style
Example: a title that changes its color when you click on it
<html>
<body>
<h1 onclick="this.style.color='red'">Click Me!</h1>
</body>
</html>
To change the style of a specific HTML element, use the following statement:
document.getElementById(id).style.property=new style
Some of the styles are the following:
fontSize
fontFamily
fontWeight
fontStyle
lineHeight
textDecoration
textTransform
textAlign
textIndent
margins()
marginTop
marginRight

marginBottom
marginLeft
paddings()
paddingTop
paddingRight
paddingBottom
paddingLeft
color
backgroundColor
backgroundImage
borderStyle
borderColor

104

borderWidths
borderTopWidth
borderRightWidth
borderBottomWidth
borderLeftWidth
width
align
clear
display
listStyleType
whiteSpace

Example: a title that changes its color when you click on it


<html>
<body>
<h1 id="h1" onclick="document.getElementById('h1').style.color='red'">Click Me!</h1>
</body>
</html>

Practice 5.2
1. Create a link that changes its color to green when a mouse is over it.
2. Create a simple remark message using DIV that changes its font size when a mouse is over it.

105

Unit Six: Server Side Programming


1. Server Side Programming with CGI
Static vs Dynamic Pages and Client side vs Server Side Scripting
The most basic type of Web page is a completely static, text-based one, written entirely in HTML. The
contents of the HTML file on the server are exactly the same as the source code of the page on the
client.
If the user reloads a static website, they would see the exact same content every time. Its content was
written directly by an author, and when the user goes to the site, that code is downloaded into a
browser and interpreted.
<html>
<title>An Average Website</title>
<body bgcolor="#003399" text="#ffcc33">
<h1>An Average Website</h1>
<p>This is an average website. </p>
</html>
The above HTML code is static.
Client-side technologies, listed in Table 6.1, cannot do anything that requires connecting to a back end
server. JavaScript cannot assemble a customized drop-down list on the fly from user preferences stored
in a database if a change is needed in the list, the Web developer must go in and edit the page by
hand. This gap is filled by server-side scripting/programming.
Client-Side Technology

Main Use

Example Effects

Cascading Style Sheets,


Dynamic HTML

Formatting pages: controlling


size, color, placement, layout,
timing of elements
Event handling: controlling
consequences of defined
events
Delivering small standalone
applications
Animation

Overlapping, different
colored/sized fonts
Layers, exact positioning
Link that changes color on
mouseover
Mortgage calculator
Moving logo
Crossword puzzle
Short cartoon

Client-side scripting
(JavaScript, VBScript)
Java applets
Flash animations film

Table 6.1 client side technologies


What does dynamic web page mean? A basic and often-repeated distinction exists between static and
dynamic Web pages but dynamic can mean almost anything beyond plain HTML. Web developers use
the term to describe both client- and server-side functions. On the client, it can mean multimedia

106

presentations, scrolling headlines, pages that update themselves automatically, or elements that appear
and disappear.
On server side, the term generally denotes content assembled on the fly, at the time the page is
requested. If you display the current date and time on a page, for example, the content will change from
one occasion to another and thus will be dynamic. In contrast to a static website, a dynamic website is
one whose content is regenerated every time a user visits or reloads the site.
Server-side Web scripting is mostly about connecting Web sites to back end servers, such as databases.
This enables the following types of two-way communication:
Server to client: Web pages can be assembled from back end-server output.
Client to server: Customer-entered information can be acted upon.
Common examples of client-to-server interaction are online forms with some drop-down lists (usually
the ones that require you to click a button) that the script assembles dynamically on the server.

What is CGI?
The Common Gateway Interface (CGI) is a method used by web servers to run external programs
(known as CGI scripts), most often to generate web content dynamically. Whenever a web page queries
a database, or a user submits a form, a CGI script is usually called upon to do the work.
A plain HTML document that the Web daemon retrieves is static, which means it exists in a constant
state: a text file that doesn't change. A CGI program, on the other hand, is executed in real-time, so that
it can output dynamic information.
CGI is simply a specification, which defines a standard way for web servers to run CGI scripts and for
those programs to send their results back to the server. The job of the CGI script is to read information
that the browser has sent (via the server) and to generate some form of valid response usually (but not
always) visible content. Once it has completed its task, the CGI script finishes and exits.
CGI is not a language. It is a simple protocol that can be used to communicate between Web forms and
your program. A CGI program can be written in any programming language: C/C++, Python, Perl, Visual
Basic, etc. Perl is a very popular language for CGI scripting because of its unrivalled text-handling

abilities, easy scripting, and relative speed.

Here is what happens during execution of CGI:

107

Client sends request with a URL+additional info


Web server receives the request
Web server identifies the request as a CGI request

Web server locates the handler program

Web server starts up the handling program. This is heavy weight process creation.
Web server feeds request parameters to handler. This happens through stdin or environment

variables

Handler program executes


Output of the handler is sent to the Web server via stdout. Output is typically a web page.

Web server returns output to the requesting web browser

Fig CGI execution

The Hello world Test


A CGI program must always send back at least one header line indicating the data type of the content
(usually text/html). The header line should be the first output statement in the program. The web
server will typically add a few header lines of its own like Date, Server, Connection, etc.
You could use the following program that just prints Hello world but preceded by HTTP headers as
required by the CGI interface. Here the header specifies that the data is text or html.
#include <iostream.h>
int main(void) {
cout<<"Content-Type: text/html \n\n"; //you must include
cout<<"Hello world\n\n";
return 0;
}
The CGI program can send back an http status line. However, the web server would send one if you
dont.

108

cout<<HTTP/1.1 200 OK\r\n;


There are few other important HTTP headers which you will use frequently in your CGI Programming.
Header
Description
Content-type:
A MIME string defining the format of the file being returned. Example:
Content-type:text/html
Expires: Date

The date the information becomes invalid. This should be used by the
browser to decide when a page needs to be refreshed. A valid date string
should be in the format 01 Jan 1998 12:00:00 GMT.

Location: URL

The URL that should be returned instead of the URL requested. You can use
this field to redirect a request to any file.

Last-modified: Date

The date of last modification of the resource.

Content-length: N

The length, in bytes, of the data being returned. The browser uses this value
to report the estimated download time for a file.

Set-Cookie: String

Set the cookie passed through the string

Getting Data and Other Information


Much of the most crucial information needed by CGI applications is made available via environment
variables. Programs can access this information as they would any environment variable (e.g.,
getenv(name) function in C++).

Fig interaction between HTTP server and CGI program via environment variables
The environment variables are shown in the table below:
Environment variable Description
AUTH_TYPE
The authentication method used to validate a user.
CONTENT_LENGTH

The length of the data (in bytes or the number of characters) passed
109

CONTENT_TYPE
DOCUMENT_ROOT

to the CGI program through standard input.


The MIME type of the query data, such as "text/html".
The directory from which Web documents are served.

GATEWAY_INTERFACE The revision of the Common Gateway Interface that the server uses.
HTTP_ACCEPT
A list of the MIME types that the client can accept.
HTTP_COOKIE
The visitors cookie, if one is set
HTTP_FROM
HTTP_REFERER
HTTP_USER_AGENT
HTTPS
PATH
PATH_INFO
PATH_TRANSLATED
QUERY_STRING
REMOTE_ADDR
REMOTE_HOST
REMOTE_IDENT
REMOTE_USER
REQUEST_METHOD
REQUEST_URI
SCRIPT_FILENAME
SCRIPT_NAME
SERVER_NAME
SERVER_PORT
SERVER_PROTOCOL
SERVER_SOFTWARE

The email address of the user making the request. Most browsers do
not support this variable.
The URL of the document that the client points to before accessing
the CGI program.
The browser the client is using to issue the request.
on if the program is being called through a secure server
The system path your server is running under
Extra path information passed to a CGI program.
The translated version of the path given by the variable PATH_INFO.
The query information passed to the program. It is appended to the
URL with a "?".
The remote IP address of the user making the request.
The remote hostname of the user making the request.
The user making the request. This variable will only be set if NCSA
IdentityCheck flag is enabled
The authenticated name of the user.
The method with which the information request was issued.
The interpreted pathname of the requested document or CGI
(relative to the document root)
The full pathname of the current CGI
The virtual path (e.g., /cgi-bin/program.pl) of the script being
executed.
The server's hostname or IP address.
The port number of the host on which the server is running.
The name and revision of the information protocol the request came
in with.
The name and version of the server software that is answering the
client request.
Table Environment variables

Example: display content of all environment variable


110

#include<stdio.h>
#include<stdlib.h>
#include <iostream.h>
const char* ENV[ 24 ] = {
"COMSPEC", "DOCUMENT_ROOT", "GATEWAY_INTERFACE", "HTTP_ACCEPT",
"HTTP_ACCEPT_ENCODING", "HTTP_ACCEPT_LANGUAGE", "HTTP_CONNECTION",
"HTTP_HOST", "HTTP_USER_AGENT", "PATH", "QUERY_STRING", "REMOTE_ADDR",
"REMOTE_PORT", "REQUEST_METHOD", "REQUEST_URI", "SCRIPT_FILENAME",
"SCRIPT_NAME", "SERVER_ADDR", "SERVER_ADMIN", "SERVER_NAME",
"SERVER_PORT", "SERVER_PROTOCOL", "SERVER_SIGNATURE","SERVER_SOFTWARE"
};
int main ()
{
cout << "Content-type:text/html\r\n\r\n";
cout << "<html>\n";
cout << "<head>\n";
cout << "<title>CGI Envrionment Variables</title>\n";
cout << "</head>\n";
cout << "<body>\n";
cout << "<table border = \"0\" cellspacing = \"2\">";
for ( int i = 0; i < 24; i++ )
{
cout << "<tr><td>" << ENV[ i ] << "</td><td>";
// attempt to retrieve value of environment variable
char *value = getenv( ENV[ i]);
if ( value != 0 )
cout << value;
else
cout << "Environment variable does not exist.";
cout << "</td></tr>\n";
}
cout << "</table><\n";
cout << "</body>\n";
cout << "</html>\n";
return 0;
}

111

Processing Forms
For forms that use METHOD="GET", the data is passed to the script or program in an environment
variable called QUERY_STRING.
It depends on the scripting or programming language used how a program can access the value of an
environment variable. In the C++ language, you would use the library function getenv (envvarname),
which is defined in the standard library stdlib, to access the value as a string. You might then use various
techniques to pick up data from the string, convert parts of it to numeric values, etc.
The output from the script or program to primary output stream (such as cout in the C++ language) is
handled in a special way. Effectively, it is directed so that it gets sent back to the browser. Thus, by
writing a C++ program that it writes an HTML document onto its standard output, you will make that
document appear on users screen as a response to the form submission.
GET vs POST
The difference between the GET and POST is how the information from the form is sent to the CGI
program, from the server. A GET will provide the user's input to the CGI program as an environment
variable called QUERY_STRING. The CGI program would read this environment variable using the C/C++
getenv() function and parse it to get the user's input.
A GET method will show the input data to the user in the URL area of the browser, showing a string like
www.check.com/cgi-bin/test.cgi?name=Tola&sex=male&age=25. The GET method is acceptable for
small amounts of data. It is also the default method when a CGI program is run via a link.
With GET method, there is a limit how large a URL can be before the server starts to have trouble
processing it. The maximum length of a URL, as decreed by HTTP standard, is 256 characters. However,
longer URL may still work, but servers are not obliged to accept them.
In POST, query string is encoded in the HTTP request body, not as part of the URL. As a result, they are
not limited in size. Unlike GET, POST allows arbitrarily long form data to be communicated. Arguments
usually do not appear in server logs. Example POST method is shown below.
POST / HTTP/1.1
Host: localhost:1888
User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.7.12)
Gecko/20051010 Firefox/1.0.7 (Ubuntu package 1.0.7)
Accept:
text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,
*/*; q=0.5
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7

112

Keep-Alive: 300
Connection: keep-alive
Referer: http://springer/~s133ar/cform1.html
Content-Type: application/x-www-form-urlencoded
Content-Length: 22
name=Tola&sex=male&age=25
Your CGI program should inspect the REQUEST_METHOD environment variable to determine if the form
was a GET or POST method, and take the appropriate action to retrieve the form. The CGI Program can
get the request method, Post or Get, using getenv() and environment variable REQUEST_METHOD. Here
is how this can be done in C/C++:
char *method;
method = getenv(REQUEST_METHOD);
if (method==NULL) /* error! */ {}
else if(if (strcmp(method,get)==0)) {}
else if (strcmp(method,post)==0) {}
Example GET handler:
int main()
{
char *method, *query;
method = getenv(REQUEST_METHOD);
if (method==NULL) /* error! */{}
else if(if (strcmp(method,get)==0))
query = getenv(QUERY_STRING);
Cout<<Content-type: text/html\r\n\r\n;
Cout<<<H1>Your query was <<query << </H1>\n;
return(0);
}
A POST will provide the user's input to the CGI program, as if it were type at the keyboard, using the
standard input device, or stdin. If POST is used, then an environment variable called CONTENT_LENGTH
indicates how much data is being sent. You can read this data into a buffer, by doing something like:
char *method, *query;
method = getenv(REQUEST_METHOD);
if(strcmp(method, post) == 0)
{
int len = atoi( getenv("INPUT_LENGTH") );
query = new char[len+1];
fread(query, 1, len, stdin );
}
Cout<<Content-type: text/html\r\n\r\n;

113

Cout<<<H1>Your query was <<Buffer << </H1>\n;

Data Parsing
Now we have the data passed from a form stored in a string variable and we want to use it. However,
the data is still in unusable form as it is URL encoded. If you have a form with two input fields, lets call
them name and email, declared as follows
< INPUT TYPE=text MAXLENGTH=30 NAME="name">
< INPUT TYPE=text MAXLENGTH=20 NAME="email">
Suppose the user types John David into name and he types david@host.domain into email. What will
then be read in by your program is
name=John+David&email=david%40host.domain
So as you can see, the data from the fields is not in a particularly usable form because it is in URL
encoded form. Hence, you have to do some further processing to get the data you need.
Data String Formatting
The string consists of the name of the input followed by the value that input takes.
The field name is separated from the data value by an "="
One set of field and data is separated from the next by an "&"
Spaces in the input data are replaced by "+"
Non letters and numbers are replaced by "%xx" where "xx" is the hex value corresponding to
that character.
First, each form element's name, specified by the NAME attribute, is equated with the value entered by
the user to create a key-value pair. For example, if the user entered "30" when asked for the age, the
key-value pair would be age=30. Each key-value pair is separated by the "&" character.
Second, since the variable names for the form element and the actual form data are standard text, it is
possible this text could consist of characters that will confuse browsers. To prevent possible errors, the
encoding scheme translates all special characters to their corresponding hexadecimal codes. These
special characters include control characters and certain alphanumeric symbols. For example, the string
"Thanks for the help!" would be converted to "Thanks+for+the+help%21". This process is repeated for
each key-value pair to create a query string.
URLs can only be sent over the Internet using the ASCII character-set. Since URLs often contain
characters outside the ASCII set, the URL has to be converted into a valid ASCII format. URL encoding
replaces non ASCII characters with a "%" followed by two hexadecimal digits. URLs cannot contain
spaces. URL encoding normally replaces a space with a + sign.
URL encoding example:

114

Character

URL-encoding

Character

URL-encoding

%80
%A3
%A9

!
"
#

%21
%22
%23

%AE
%C0
%C1
%C2

$
%
&
'

%24
%25
%26
%27

%C3
%C4
%C5

(
)

%28
%29

For text and password fields, the user input will represent the value. If no information was entered, the
key-value pair will be sent anyway, with the value left blank (i.e., "name="). For radio buttons and
checkboxes, the VALUE attribute represents the value when the button element is checked. If no VALUE
is specified, the value defaults to "on." An unchecked checkbox will not be sent as a key-value pair; it will
be ignored.
The CGI program then has to "decode" this information in order to access the form data. The encoding
scheme is the same for both GET and POST.
Understanding the Decoding Process
In order to access the information contained within the form, a decoding must be applied to the data.
First, the program must determine how the data was passed by the client, get or post. If the value
indicates a GET request, either the query string or the extra path information must be obtained from the
environment variables. On the other hand, if it is a POST request, the number of bytes specified by the
CONTENT_LENGTH environment variable must be read from standard input.
The algorithm for decoding form data follows:
1. Determine request protocol (either GET or POST) by checking the REQUEST_METHOD
environment variable.
2. If the protocol is GET, read the query string from QUERY_STRING and/or the extra path
information from PATH_INFO.
3. If the protocol is POST, determine the size of the request using CONTENT_LENGTH and read that
amount of data from the standard input.
4. Split the query string on the "&" character, which separates key-value pairs (the format is
key=value&key=value...).
5. Decode the hexadecimal and "+" characters in each key-value pair.
6. Create a key-value table with the key as the index.

115

Example for removing URL encoding:


char* changeSpecialCharacters(char *query)
{
int t = 0;
char digits[18], hex[4], temp[1000], ch;
strcpy(digits, "0123456789ABCDEF\0");
for(int i = 0; i < strlen(query); i++)
{
if(query[i] == '+') //if space
temp[t++] = ' ';
else if(query[i] == '%') //if hexadecimal encoded character is found
{
hex[0] = query[++i];
hex[1] = query[++i];
hex[2] = '\0';
for(int j = 0; j < strlen(digits); j++) //convert first hexadecimal digit to num
{
if(hex[0] == digits[j])
{
ch = 16 * j;
break;
}
}
for(int j = 0; j < strlen(digits); j++)//convert second hexadecimal digit to num
{
if(hex[1] == digits[j])
{
ch = ch + j;
break;
}
}
temp[t++] = ch;
}
else
temp[t++] = query[i];
}
temp[t] = '\0';
query = (char*)temp;
return query;
}
Example all put together (test.cpp):

116

#include<iostream.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
char *method, *query;
char str[1000], temp[100];
int prevo = -1;
char sepr[100];
char* separate(char []);
char* GET(char *);
char*POST(char*);
void changeSpecialCharacters();
//gets the data submitted by the form
void getQuery()
{
method = getenv("REQUEST_METHOD");
for(int i = 0; i < strlen(method); i++)
method[i] = toupper(method[i]);
if(strcmp(method, "GET") == 0)
query = getenv("QUERY_STRING");
else if(strcmp(method,"POST") == 0)
{
int len = atoi(getenv("CONTENT_LENGTH"));
query = new char[len + 1];
fread(query, len, 1, stdin);
}
else
query = "unknown";
}
//removes URL encoding from form data
void changeSpecialCharacters()
{
int t = 0;
char hex[4], ch;
char digits[17];
strcpy(digits, "0123456789ABCDEF");
strcpy(temp, "\0");
for(int i = 0; i < strlen(query); i++)
{
if(query[i] == '+')
temp[t++] = ' ';
else if(query[i] == '%')
{
hex[0] = query[++i];
hex[1] = query[++i];

117

hex[2] = '\0';
for(int j = 0; j < strlen(digits); j++)
{
if(hex[0] == digits[j])
{
ch = 16 * j;
break;
}
}
for(int j = 0; j < strlen(digits); j++)
{
if(hex[1] == digits[j])
{
ch = ch + j;
break;
}
}
temp[t++] = ch;
}
else
temp[t++] = query[i];
}
temp[t] = '\0';
query = (char*)temp;
cout<<"\n<br>Decoded URL: "<<query;
}
//returns the data entered in the given input name submitted using post method
char* POST(char *name)
{
return (GET(name));
}
//returns the data entered in the given input name submitted using get method
char* GET(char *name)
{
char *value;
int eq = -1;
strcpy(str, "\0");
prevo = -1;
for(int i = 0; i < strlen(query); i++)
{
strcpy(str, "\0");
if(query[i] == '&')
{
for(int j = (prevo + 1), t = 0; j < i; j++, t++)
{
str[t] = query[j];
str[t+1] = '\0';
}

118

if(strncmp(str, name, strlen(name)) == 0)


{
value = separate(str);
return value;
}
prevo = i;
}
}
//clear any content
strcpy(str, "\0");
for(int i = (prevo + 1), t = 0; i < strlen(query); i++, t++)
{
str[t] = query[i];
str[t+1] = '\0';
}
if(strncmp(str, name, strlen(name)) == 0)
{
value = separate(str);
return value;
}
return "";
}
//separates the key from the value(key=value is separated and value is retuned)
char* separate(char field[])
{
int u = 0;
//ar sepr[100];
char *ret;
strcpy(sepr,"");
for(int t = 0; t < strlen(field); t++)
{
if(field[t] == '=')
{
for(int i = (t + 1); i < strlen(field); i++)
sepr[u++] = field[i];
sepr[u] = '\0'; //terminate string
break;
}
}
ret = sepr;
return ret;
}
int main()
{
cout<<"Content-type: text/html\r\n\r\n";
getQuery();

119

changeSpecialCharacters();
if (method == NULL)
{
cout<<"<p>No posting method identified.</p>";
return 0;
}
cout<<"\n<br> First name: "<<GET("first_name");
cout<<"\n<br> Last name: "<<GET("last_name");
cout<<"\n<br> Password: "<<GET("password");
return 0;
}
HTML form for above CGI:
<html>
<head>
<title>CGI Test</title>
<script language="JavaScript">
function validate()
{
if(inp.first_name.value=="") {
alert("First name is empty");
return false;
}
if(inp.last_name.value=="") {
alert("Last name is empty");
return false;
}
if(inp.password.value=="") {
alert("Password name is empty");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="inp" method="get" action="/cgi-bin/Test.cgi" onSubmit="return validate();">
<span class="style1"><strong>Registration Form</strong></span>
<br /> <br />
First name: <input type="text" name="first_name" />
<br /> <br />
Last name: <input type="text" name="last_name" />

120

<br /> <br />


Password: <input type="password" name="password" />
<br /> <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ;&nbsp; ;&nbsp;
<input type="submit" value="Submit">
</form>
</body>
</html>
To test the above CGI, first compile the C++ file and run it. This will create an executable file. Rename
the executable file to Test.cgi and put in the CGI directory. Now you can open the form, fill and then
submit it to run the CGI program.

Security
Since a CGI program is executable, it is basically the equivalent of letting the world run a program on
your system, which isn't safe at all it creates security risk. Therefore, there are some security
precautions that need to be taken when it comes to using CGI programs. The first one is the fact that CGI
programs need to reside in a special directory, so that the Web server knows to execute the program
rather than just display it to the browser. This directory is usually under direct control of the webmaster,
prohibiting the average user from creating CGI programs.
The other is, when dealing with forms, it is extremely critical to check the data. A malicious user can
embed shell metacharacters characters that have special meaning to the shell in the form data. This
could cause big problem to your system. For example, here is a form that asks for user name:
<FORM action="/cgi-bin/finger.cgi" method="POST">
<input type="text" name="user" size=40>
<input type="submit" value="Get Information">
</form>
#include<dos.h>
int main()
{
system(mkdir <<get(user));
return 0;
}
What would happen if the user enters danger; del *

121

2. Server Side Programming with PHP


1.1 Introduction to PHP
PHP is the Web development language written by and for Web developers. PHP stands for PHP:
Hypertext Preprocessor. PHP is currently in its fifth major version called PHP5.
PHP is a server-side scripting language, which can be embedded in HTML or used as a standalone binary
(although the former use is much more common). Proprietary products in this niche are Microsofts
Active Server Pages, Macromedias ColdFusion, and Suns Java Server Pages. Over the past few years,
however, PHP and server-side Java have gained momentum, while ASP has lost mindshare.
PHP is a server-side scripting language, which means that the scripts are executed on the server, the
computer where the Web site is located. This is different than JavaScript, another popular language for
dynamic Web sites. JavaScript is executed by the browser, on the users computer. Thus, JavaScript is a
client-side language.
Because PHP scripts execute on the server, PHP can dynamically create the HTML code that generates
the Web page, which allows individual users to see customized Web pages. Web page visitors see the
output from scripts, but not the scripts themselves.
PHP is particularly strong in its ability to interact with databases. PHP supports pretty much every
database youve ever heard of and some you havent. PHP handles connecting to the database and
communicating with it, so you dont need to know the technical details for connecting to a database or
for exchanging messages with it. You tell PHP the name of the database and where it is, and PHP
handles the details. It connects to the database, passes your instructions to the database, and returns
the database response to you.
Major databases currently supported by PHP include the following:
dBASE
mSQL
Informix
MySQL
Ingres
Oracle
Microsoft SQL Server
PostgreSQL

122

Sybase

PHP supports other databases as well, such as filePro, FrontBase, and InterBase. In addition, PHP
supports ODBC (Open Database Connectivity), a standard that allows you to communicate with even
more databases, such as Access and IBM DB2.
PHP works well for a database-driven Web site. PHP scripts in the Web site can store data in and
retrieve data from any supported database. PHP also can interact with supported databases outside a
Web environment. Database use is one of PHPs best features.
Software Requirements
To work with PHP and to try the example codes given in this unit, you need to install a web server, PHP,
and database server. There are many web servers to choose from; the most commonly used web server
is called Apache which you can download from the internet freely. Similarly, for database, there are
many options to use; the most popular database server for web pages is MySQL which again you can
download freely from internet. PHP is also available freely on the internet.
You can download each of the above three software independently and integrate them by configuring
Apache and PHP to get them work together. However, this is difficult most of the times for
inexperienced web developers. To solve this, software producers integrate the three software and offer
them as bundle. One such bundle that contains Apache, PHP, and MySQL is Vertrigo. Vertrigo is a free
software that you can download from internet and install on your computer. Once you install Vertrigo,
you have all the necessary things to write server side scripting with PHP.
For the apache code to execute properly, it should be saved in your web directory. Your web directory
depends on what web server you use. For example, on my machine which runs vertrigo web server, my
web directory is C:\Program Files\VertrigoServ\www. Hence, I should save my PHP files in this folder.
In addition, you cant run PHP files by opening them using Web browsers directly, unlike html files. For
PHP to execute properly, you should work using your web server. This can be done by typing the address
of your computer in your web browser like:
http://127.0.0.1/
You can add PHP file to execute at the end of the above address like:
http://127.0.0.1/test.php

Practice 6.1
1. Go to www.google.com and search for download location of vertrigo.
2. Download the vertrigo server into your computer.
3. Install the vertrigo server by going to the path it is downloaded to

123

NB: If you have done the above tasks successfully, you now have a vertrigo on your machine. You can
start vertrigo by going to Start->programs->vertrigoServ->vertrigoServ. You will see a vertrigo icon in the
tray.
Attaching PHP to Web Pages
PHP file is attached to web pages by using the <form> tag. Since PHP is written to process data sent from
client computers and form is the means to get that data, this is a logical place to attach the PHP to
HTML.
The form tag has an attribute called action. We use this attribute to specify the PHP to execute when the
web page is submitted. The syntax is:
<form name=formname method=submitingmethod action=phpfiletoexecute.php>
form elements
</form>
Example: to attach a php called saver.php to an HTML page
<form name=detail method=post action=saver.php>
form content
</form>
When this form is submitted, the web server looks for saver.php and executes it. The result from
executed php, saver.php in this case, is sent back the client machine.

Writing PHP
You add PHP code to your web page by using tags, similar, but not identical, to other tags in the HTML
file. The PHP code section is enclosed in PHP tags with the following form:
<?php
PHP statements
?>
For example, you can add the following PHP section to your HTML file.
Remark: Web pages that contains PHP should be saved with .php extension. You can also add several
PHP sections to a Web page.
<?php
echo This line brought to you by PHP;
?>
When the Web server gets the file and sees the .php extension, it checks for PHP tags. When it finds the
PHP tag, it executes the PHP echo statement instead of sending it to the browser. Only the output from
the PHP section (This line brought to you by PHP) is sent on to the browser. In your browser window, you
see the output at the location in the page where you added the PHP section. Even if you view the source
in your browser, you only see the output, not the PHP code.

124

Example: your first hello world PHP script


<html>
<head><title>Hello World Script</title></head>
<body>
<?php
echo <p>Hello World!</p>
?>
</body>
</html>
When the PHP section is processed, it is replaced with the output. In this case, the output is as follows:
<p>Hello World!</p>

Output Statements
Output statements are used in almost every PHP script. Its rare that you would write a script that would
do something and not output anything. True, a script can do things that are invisible, like checking your
entire hard disk to see if a certain file exists. You would not see it checking. However, the search is pretty
pointless if the script doesnt tell you what it found. Youd want to know where it looked, when it
finished, and whether or not it found the file. Because of this, almost all scripts use output statements.
The two most basic constructs for displaying output in PHP are echo and print. Both can be used either
with parentheses or without them. Function calls always have the name of the function first, followed by
a parenthesized list of the arguments to the function.
The general format of the echo statement is as follows:
echo outputitem1,outputitem2,outputitem3, . . .;
echo (output);
The parameterized version of echo does not accept multiple arguments.
The general format of the print statement is as follows:
print output;
print(output);
Example: different ways of echo and print
echo 123; //output: 123
echo Hello World!;
//output: Hello world!
echo (Hello World!); //output: Hello world!
echo Hello,World!; //output: Hello World!
echo Hello World!;
//output: error, string should be enclosed in quotes
print (Hello world!); //output: Hello world!

125

The command print is very similar to echo, with two important differences:
Unlike echo, print can accept only one argument.
Unlike echo, print returns a value, which represents whether the print statement succeeded.
The value returned by print will be 1 if the printing was successful and 0 if unsuccessful. It is rare that a
syntactically correct print statement will fail, but in theory this return value provides a means to test, for
example, if the users browser has closed the connection.
It is possible to embed HTML tags in echo or print statements. The browser will parse and interpret them
like any tag included in HTML page and display the page accordingly.
echo/print statement

PHP output

web page display

echo Hello World;

HelloWorld!

HelloWorld!

echo Hello;
echo World!;
echo Hello\nWorld!;

HelloWorld!

HelloWorld!
Hello World!

echo Hello<br>World!;

Hello
World!
Hello<br>World

echo <u> <i> Hello world!</i></u>;

<u>Hello world!</u>

Hello
World!
Hello world!

Table 6.2 how to use echo statement


Notice where spaces are included in the output. The first echo statement includes a space so the space is
output. The second row has two echo statements, but neither includes a space, so no space appears in
the Web page. Each echo statement output does not go to new line unless we insert \n. The third row
shows a space on the Web page, even though no space is included in the echo statement. The space is
added by the browser when it reads the PHP output as HTML. In HTML, a new line is not displayed as a
new line; it is just interpreted as a single space.

Comments
Adding comments to your script is essential. Comments describe your script what it does and how it
does it. The larger, more complicated, or more unusual your code is, the more you need comments.
After working 20 hours a day on a script, you may believe its code is permanently burned into your brain.
However, two years from now, when you need to revise this script, you will swear it was written by a
stranger. And theres also the possibility that your scripts may need to be revised by an actual stranger.
Programmers leave a company making it difficult to revise code unless commented.
Comments are notes that are embedded in the script itself. PHP ignores comments; comments are for
humans. You can embed comments in your script anywhere as long as you tell PHP that they are

126

comments.
PHP supports two types of comments: single-line comment (short comment), and multi-line comment
(long comment). The format for multi-line comments is as follows:
/* comment text
more comment text
*/
Your comments can be as long or as short as you need. When PHP sees code that indicates the start of a
comment (/*), it ignores everything until it sees the code that indicates the end of a comment (*/).
PHP has a short comment format too. You can specify a single line comment by using the # or two
slashes (//) in the following manner:
# This is comment line 1
// This is comment line 2
It is customary and useful to put a block of comments at the top of your script giving information about
the script and an overview of what it does. For example, heres one possible format for a comment block
at the top of your script:
/*
name: hello.php
description: Displays Hello World! on a Web page.
written by: Joe Programmer
created: 2/1/03
modified: 3/15/03
*/

1.2 Working with Variables


A variable is a special container that you can define to hold a value such as number, string, object, array,
or a Boolean for you.
The rules for variable names are as follows:
All variable names should start with a dollar sign ($). This tells PHP that it is a variable name.
Variable names can be any length.
Variable names can include letters, numbers, and underscores only.
Variable names must begin with a letter or an underscore. They cannot begin with a number.
variable names are case-sensitive. $favoritecity and $Favoritecity are not the same variable. If
you store information in $FavoriteCity, you cant retrieve that information later in the script by
using the variable name $favoriteCity.
To store information in a variable, just like in JavaScript, you use a single equal sign (=). For example, the

127

following four PHP statements assign information to variables:


$age = 21;
$price = 20.52;
$temperature = -5;
$name = Clark Kent;
echo Your age is $age;
Numbers are not enclosed in quotes when they are assigned to variable. However, strings should be
enclosed in either single or double quotes ( or ). The quotes tell PHP that the characters are a string,
handled by PHP as a unit. Without the quotes, PHP doesnt know the characters are a string and wont
handle them correctly.
PHP has a total of eight types: integers, doubles, Booleans, strings, arrays, objects, NULL, and
resources:
Integers are whole numbers, without a decimal point, like 495.
Doubles are floating-point numbers, like 3.14159 or 49.0.
Booleans have only two possible values: TRUE and FALSE.
NULL is a special type that only has one value: NULL.
Strings are sequences of characters, like PHP is very interesting.
Arrays are named and indexed collections of other values.
Objects are instances of programmer-defined classes, which can package up both other kinds of
values and functions that are specific to the class.
Resources are special variables that hold references to resources external to PHP (such as
database connections).
Of these, the first five are simple types, and the next two (arrays and objects) are compound types the
compound types can package up other arbitrary values of arbitrary type, whereas the simple types
cannot.
You can store the value of one variable in another variable, as shown in the following statements:
$name1 = Sally;
$name2 = Susan;
$favorite_name = $name2;
After these statements are executed, the variable $favorite_name contains the value Susan from
$name2.

Displaying variable values


You can display the value stored in a variable with print statement. You can output the value of a variable
as in the following statements:
$today = Sunday;
print(The day today is $today);

128

The output from the preceding statements is The day today is Sunday.
Checking variable content
Sometimes you just need to know whether a variable exists or what type of data is in the variable. Here
are some common ways to test variables:
isset($varname) - true if variable is set, even if nothing is stored in it.
empty($varname) - true if value is 0 or is a string with no characters in it or is not set.
You can also test what type of data is in the variable. For example, to see if the value is an integer, you
can use the following:
is_int($number) - the comparison is TRUE if the value in $number is an integer.
Some other tests provided by PHP are as follows:
is_array($var2): Checks to see if $var2 is an array
is_float($number): Checks to see if $number is a floating point number
is_null($var1): Checks to see if $var1 is equal to 0
is_numeric($string): Checks to see if $string is a numeric string
is_string($string): Checks to see if $string is a string
You can test for a negative, as well, by using an exclamation point (!) in front of the expression. For
example, the following statement returns TRUE if the variable does not exist at all:
!isset($varname)

Removing Variables
You can uncreate the variable by using this statement:
unset($age);
After this statement, the variable $age no longer exists. If you try to echo it, you get an undefined
variable notice. You can unset more than one variable at once, as follows:
unset($age, $name, $address);

Working with Constants


Constants are similar to variables. Constants are given names, and values are stored in them. However,
constants are constant; they cant be changed by the script. After you set the value for a constant, it
stays the same.
We use constants to define values that do not change like PI in maths(3.14..), number of days in a
week(7), number of minutes in an hour(60), etc.

Creating constants
Constants are set by using the define statement. The general format is as follows:

129

define(constantname, constantvalue);
For example, to set a constant with the weather, use the following statement:
define(PI,3.141);
This statement creates a constant called PI and sets its value to 3.141.
When naming constants, use descriptive names, as you do for variables. However, unlike variables,
constant names do not begin with a dollar sign ($). By convention, constants are given names that are all
uppercase so you can see easily that theyre constants. However, PHP accepts lowercase letters without
complaint.
You can store either a string or a number in a constant. The following statement, which defines a
constant named INTEREST and assigns to it the value .01, is perfectly okay with PHP:
define (INTEREST,.01);
Constants should not be given names that are keywords for PHP. Keywords are words that have meaning
for PHP, such as echo, and they cant be used as constants because PHP treats them as the PHP feature
of the same name.

Displaying constants
You can determine the value of a constant by using print as follows:
print(INTEREST);
You can also use a constant in an echo statement:
echo INTEREST;
When you echo a constant, you cant enclose it in quotes. If you do, it echoes the constant name rather
than the value. You can echo the constant as shown in the preceding example, or you can enclose it with
parentheses. You can build more complicated output statements by using commas, as in the following
example:
echo The Canadian exchange rate is $, INTEREST;
The output from this statement is the following: The Canadian exchange rate is $1.52.

Practice 6.2
1. Write a PHP program that displays your age from a variable with echo statement.
2. Write a PHP program that defines that defines the distance between earth and moon and
displays it using print statement.

1.3 Using Operators


PHP supports many operators.

130

Mathematical Operators
Arithmetic operators are straightforwardthey are just the normal mathematical operators.
Operator
Description
+
Adds two numbers together.
-

Subtracts the second number from the first number.

Multiplies two numbers together.

Divides the first number by the second number.

Finds the remainder when the first number is divided by the second number. This
is called modulus.
Table 6.3 mathematical operators
Example: a program that performs all mathematical operation on two numbers
$a = 10;
$b = 20;
$c = $a + $b; //result: 30
$c = $a - $b; //result: -10
$c = $a * $b; //result: 200
$c = $a / $b; //result: 0.5
$c = $a % $b; //result: 10
You should note that arithmetic operators are usually applied to integers or doubles. If you apply them
to strings, PHP will try and convert the string to a number. If it contains an e or an E, it will be
converted to a double; otherwise it will be converted to an int. PHP will look for digits at the start of the
string and use those as the valueif there are none, the value of the string will be zero.

Pre- and Post-Increment and Decrement operators


operator

description

example

meaning

++

postfix increment

$x++

$x=$x+1

--

postfix decrement

$x--

$x=$x-1

++

prefix increment

++$x

$x=$x+1

--

prefix decrement

--$x

$x=$x+1

Table 6.4 prefix and postfix operators


Example: a program that performs postfix and prefix operations
$a=4;
echo <br>, ++$a;
$b=10;
echo <br>, $b++;

131

echo <br>, $b;


The output is:
5
10
11
All the increment operators have two effectsthey increment and assign a value. Consider the
following:
$a=4;
echo ++$a;
The second line uses the prefix increment operator, so called because the ++ appears before the
$a. This has the effect of first, incrementing $a by 1, and second, returning the incremented
value. In this case, $a is incremented to 5 and then the value 5 is returned and printed. The
value of this whole expression is 5.
However, if the ++ is after the $a, we are using the postfix increment operator. This has a different effect.
Consider the following:
$a=4;
echo $a++;
In this case, the effects are reversed. That is, first, the value of $a is returned and printed, and
second, it is incremented. The value of this whole expression is 4. This is the value that will be
printed. However, the value of $a after this statement is executed is 5.
As you can probably guess, the behavior is similar for the -- operator. However, the value of
$a is decremented instead of being incremented.

Combination Assignment Operators


Operator

description

example

meaning

+=

add and assign

$x += 5

$x = $x + 5

-=

subtract and assign

$x -= 5

$x = $x 5

/=

divide and assign

$x /= 5

$x = $x / 5

*=

multiply and assign

$x *= 5

$x = $x * 5

%=

modulate and assign

$x %= 5

$x = $x % 5

.=

concatenate and assign

$x .= " test"

$x = $x." test"

Table 6.5 assignment operators

Comparison operators
132

The comparison operators are used to compare two values. Expressions using these operators
return either true or false depending on the result of the comparison.
Operator
Name
description
==

Equal

!=

Not equal

<

Less than

>

Greater than

<=

Less than or equal to

>=

Greater than or equal to

===

Identical

True if its arguments are equal to each other, false


otherwise
False if its arguments are equal to each other, true
otherwise
True if the left-hand argument is less than its right-hand
argument, but false otherwise
True if the left-hand argument is greater than its righthand argument, but false otherwise
True if the left-hand argument is less than its right-hand
argument or equal to it, but false otherwise
True if the left-hand argument is greater than its righthand argument or equal to it, but false otherwise
True if its arguments are equal to each other and of the
same type, but false otherwise

Table 6.6 comparison operators

Logical Operators
The logical operators are used to combine the results of logical conditions. For example, we might be
interested in a case where the value of a variable is between 0 and 100. We would need to test the
conditions $a >= 0 and $a <= 100, using the AND operator, as follows
$a >= 0 && $a <=100
Operator

description

And

Is true if and only if both of its arguments are true

Or

Is true if either (or both) of its arguments are true.

!
Xor

Is true if its single argument (to the right) is false and false if its
argument is true
Is true if either (but not both) of its arguments are true

&&

Same as and, but binds to its arguments more tightly

||

Same as or but binds to its arguments more tightly

Table 6.7 logical operators

The ternary operator


One especially useful construct is the ternary conditional operator, which plays a role somewhere
between a Boolean operator and a true branching construct. Its job is to take three expressions and use

133

the truth value of the first expression to decide which of the other two expressions to evaluate and
return. The syntax looks like:
test-expression ? yes-expression : no-expression
The value of this expression is the result of yes-expression if test-expression is true; otherwise, it is the
same as no-expression.
For example, the following expression assigns to $max_num either $first_num or $second_num,
whichever is larger:
$max_num = $first_num > $second_num ? $first_num : $second_num;

1.4 Conditional Statements


1.4.1 if Statements
We can use an if statement to make a decision. You should give the if statement a condition that is
evaluated to true or false. If the condition is true, the associated block of code will be executed.
Conditions in if statements must be surrounded by brackets ().
The syntax of if statement:
if(condition) {
statements;
}
Example: an if statement that checks if a variable value is less than 50 (student failed course)
if($mark<50){
print(You have to improve your mark);
}
if..else statements
An else statement allows you to define an alternative action to be taken when the condition in an if
statement is false. This allows to take one action when the condition is true and another action when
the condition is false.
The syntax of if statement:
if(condition) {
statements;
}
else {
statements;
}
Example:

134

if($mark<50) {
print(You failed this course);
}
else{
print(You have passed the course);
}
else if Statements
For many of the decisions we make, there are more than two options. We can create a sequence of
many options using the elseif statement. The elseif statement is a combination of an else and an if
statement. By providing a sequence of conditions, the program can check each until it finds one that is
true.
Example: a program that checks if a variable value is between 1 and 5 and display message accordingly
if ($day == 5)
print(Five golden rings<BR>);
elseif ($day == 4)
print(Four calling birds<BR>);
elseif ($day == 3)
print(Three French hens<BR>);
elseif ($day == 2)
print(Two turtledoves<BR>);
elseif ($day == 1)
print(A partridge in a pear tree<BR>);

1.4.2 switch statements


The switch statement works in a similar way to the if statement, but allows the condition to take more
than two values. In an if statement, the condition can be either true or false. In a switch statement, the
condition can take any number of different values, as long as it evaluates to a simple type (integer,
string, or double). You need to provide a case statement to handle each value you want to react to and,
optionally, a default case to handle any that you do not provide a specific case statement for.
switch (expression) {
case result1:
// execute this if expression results in result1
break;
case result2:
// execute this if expression results in result2
break;
default:
// execute this if no break statement

135

// has been encountered


}
The expression used in a switch statement is often just a variable. Within the switch statement's block of
code, you find a number of case statements. Each of these cases tests a value against the result of the
switch expression. If the case is equivalent to the expression result, the code after the case statement is
executed.
The break statement ends the execution of the switch statement altogether. If the break statement is
left out, the next case statement is evaluated. If the optional default statement is reached, its code is
executed. It is important to include a break statement at the end of any code that will be executed as
part of a case statement. Without a break statement, the program flow will continue to the next case
statement and ultimately to the default statement. In most cases, this will result in unexpected
behavior, likely incorrect!
Example: switch statement that checks the mood of the person
<html>
<head>
<title>Listing 5.4</title>
</head>
<body>
<?php
$mood = "sad";
switch ($mood)
{
case "happy":
echo "Hooray, I'm in a good mood";
break;
case "sad":
echo "Awww. Don't be down!";
break;
default:
print "Neither happy nor sad but $mood";
break;
}
?>
</body>
</html>

Practice 6.3
1. Write a PHP code that checks the day of week and display appropriate message. For example,
Today is Friday if the day is Friday. Use switch statement.

136

2. Write a program that accepts marks of five courses of a student and calculate the total, the
average, and the range.
3. Write a program that accepts mark of a student and determine if he/she has failed the course or
not (<50 is failure).

1.5 Using Loops


Scripts can decide how many times to execute a block of code. Loop statements are designed to enable
you to achieve repetitive tasks. A loop will continue to operate until a condition is achieved, or you
explicitly choose to exit the loop.
Loops are used frequently in scripts to set up a block of statements that repeat. The loop can repeat a
specified number of times. For example, a loop that echoes all the state capitals cities of all countries in
the world needs to repeat more than 200 times. Or the loop can repeat until a certain condition is met.
For example, a loop that echoes the names of all the files in a directory needs to repeat until it runs out
of files, regardless of how many files there are. Here are three types of loops:
for loop: Sets up a counter; repeats a block of statements until the counter reaches a specified
number
while loop: Sets up a condition; checks the condition, and if its true, repeats a block of
statements until the condition becomes false
do..while loop: Sets up a condition; executes a block of statements; checks the condition; if the
condition is true, repeats the block of statements until the condition becomes false

1.5.1 for loop


The most basic for loops are based on a counter. You set the beginning value for the counter, set the
ending value, and set how the counter is incremented/decremented each time the statement block is
executed. The general format is as follows:
for (startingvalue; endingcondition; increment)
{
block of statements;
}
Example:
for ($i=1;$i<=3;$i++) {
echo $i. Hello World!<br>;
}
The following is the output from these statements:
1. Hello World!
2. Hello World!
3. Hello World!

137

The statements in the block do not need to be indented. PHP doesnt care whether theyre indented.
However, indenting the blocks makes it much easier for you to understand the script.
You can nest for loops inside of for loops. Suppose you want to print out the times tables from 1 to 9.
1x1=1
...
1x9=9
2x1=2
...
2 x 9 = 18

9x1=9

9 x 9 = 81
You can use the following nested loop statements:
for($i=1; $i<=9; $i++)
{
for($j=1; $j<=9; $j++)
{
$result = $i * $j;
echo $i x $j = $result\n;
}
}

1.5.2 while loop


One of PHP looping construct is while, which has the following syntax:
while (condition)
{
statement
}
The while loop evaluates the condition expression as a Boolean if it is true, it executes statement and
then starts again by evaluating condition. If the condition is false, the while loop terminates. Of course,
just as with if, statement may be a single statement or it may be a brace-enclosed block. The body of a
while loop may not execute even once, as in:
while (FALSE)
print(This will never print.<BR>);
Or it may execute forever, as in this code snippet:

138

while (TRUE)
print(All work and no play makes Jack a dull boy.<BR>);
or it may execute a predictable number of times, as in:
$count = 1;
while ($count <= 10)
{
print(count is $count<BR>);
$count = $count + 1;
}
which will print exactly 10 lines.

1.5.3 do..while loop


A do..while loop is very similar to a while loop. Like a while loop, a do..while loop continues repeating as
long as certain conditions are true. Unlike while loops, however, those conditions are tested at the
bottom of each loop. If the condition is true, the loop repeats. When the condition is not true, the loop
stops.
The general format for a do..while loop is as follows:
do
{
block of statements
} while (condition);
Example: a loop that displays numbers from 1 to 10
$count = 1;
do
{
print(count is $count<BR>);
$count = $count + 1;
}
while ($count <= 10)
Avoiding infinite loops
You can easily set up loops so that they never stop. These are called infinite loops. They repeat forever.
However, seldom does anyone create an infinite loop intentionally. It is usually a mistake in the
programming.
If your loop is running infinitely, your script is running for an infinite amount of time. This is very
stressful on your Web server, and renders the Web page in question unusable.

139

Example: infinite loop


$i = 1;
while($i < 10)
{
print(i is $i);
}
output:
i is 1
i is 1
i is 1
...
Why is it infinite loop? The variable $i is not incremented in the body of the while loop. As a result, the
value of $i is always 1 making the while condition, $i<10, always true. This leads to infinite loop.
Breaking out of a loop
Sometimes you want your script to break out of a loop. PHP provides two statements for this purpose:
break: breaks completely out of a loop and continues with the script statements after the loop.
continue: stops current iteration and goes back to condition check. If condition check is true, it
will go to the next iteration.
The break and continue statements are usually used in conditional statements. In particular, break is
used most often in switch statements.
Example: break statement
$counter = 0;
while ( $counter < 5 )
{
$counter++;
if ( $counter == 3 )
{
echo break\n;
break;
}
echo Last line in loop: counter=$counter\n;
}
echo First line after loop\n\n;
The output of this statement is the following:
Last line in loop: counter=1
Last line in loop: counter=2
break

140

First line after loop

1.6 Arrays
The variables that we looked at in the previous chapters are scalar variables, which store a single value.
An array is a variable that stores a set or sequence of values. One array can have many elements. Each
element can hold a single value, such as text or numbers, or another array. An array containing other
arrays is known as a multidimensional array.
A scalar variable is a named location in which to store a single value; similarly, an array is a named place
to store a set of values, thereby allowing you to group common scalars.
The values stored in an array are called the array elements. Each array element has an associated index
(also called a key) that is used to access the element. Arrays in most programming languages have
numerical indexes that typically start from zero or one. PHP supports this type of array.
In addition to numerical indexes, PHP also supports associative arrays. Associative arrays can have
almost anything as the array indices, but typically use strings.
Creating Arrays
There are different ways to create an array in a PHP script: by assigning a value into one (and thereby
implicitly creating it), by using the array() construct, or by calling a function that happens to return an
array as its value.
The simplest way to create an array is to act as though a variable is already an array and assign a value
into it.
Example: the following code will create an array called $products by assigning value:
$products[0] = Tires;
$products[1] = Oil;
$products[2] = Spark Plugs;
$products[3] = battery;
$products[4] = jar;
If $products does not already exist (which is true in this case), the first line will create a new array with
just one element. The subsequent lines add values to the array. The number in the [] are array indexes
that identify where the element is stored.
The other way to create an array is via the array() construct, which creates a new array from the
specification of its elements and associated keys. In its simplest version, array() is called with no
arguments, which creates a new empty array. In its next simplest version, array() takes a commaseparated list of elements to be stored, without any specification of keys. The result is that the elements
are stored in the array in the order specified and are assigned integer keys beginning with zero.

141

For example, the statement:


$fruit = array(apple, orange, banana, pear);
This causes the variable $fruit to be assigned to an array with four string elements(apple, banana,
orange, pear), with the indexes 0, 1, 2, and 3, respectively. In addition, the array will remember
the order in which the elements were stored.
Associative Arrays
In the products array, we allowed PHP to give each item the default index. This meant that the first item
we added became item 0, the second item 1, and so on. PHP also supports associative arrays. In an
associative array, we can associate any key or index we want with each value.
An associative array can be viewed as a list of key/value pairs, stored as follows:
$arrayname[key1] = value1;
$arrayname[key2] = value2;
$arrayname[key3] = value3;
Initializing an Associative Array
$person = array("name" => "Bob", "occupation" => "engineer", "age" => 30, "power" => "x-ray vision");
The four keys in the $person array are called name, occupation, age, and special power. The associated
values are Bob, engineer, 30, and x-ray vision. You can reference specific elements of an associative
array using the specific key.
Example: to access associative array element
echo $person['occupation']; //output: engineer
Walking through Array
It is possible to traverse through an array in different ways. One is by using loop together with array
index.
for($i = 0; $i < 4; $i++)
print(\n$product[$i]);
output:
Tires
Oil
Spark Plugs
battery
Jar
Using foreach to walk through an array

142

You can use foreach to walk through an array one value at a time and execute a block of statements by
using each value in the array. The general format is as follows:
foreach ( $arrayname as $keyname => $valuename)
{
block of statements;
}
In this format, you need to fill in the following information:
arrayname: The name of the array you are walking through.
keyname: The name of the variable where you want to store the key. The keyname variable is
optional. If you leave out $keyname =>, only the value is stored into $valuename.
valuename: The name of the variable where you want to store the value.
Example: foreach loop
$population = array ( Oro => 25000, Amh => 20000, Tig => 5000);
ksort($population);
foreach($population as $state => $population)
{
$population = number_format($population);
echo $state: $population.<br>;
}
Multidimensional Arrays
Arrays do not have to be a simple list of keys and valueseach location in the array can hold another
array. This way, we can create a two-dimensional array. You can think of a two dimensional array as a
matrix, or grid, with width and height or rows and columns.
If we want to store more than one piece of data about products, we could use a two-dimensional array.

Figure 6.1 sample product table


Using array() construct:
$products = array( array( TIR, Tires, 100 ),

143

array( OIL, Oil, 10 ),


array( SPK, Spark Plugs, 4 ) );
Using assigning values:
$product[0][0] = TIR;
$product[0][1] = Tires;
$product[0][2] = 100;
$product[1][0] = OIL;
$product[1][1] = Oil;
$product[1][2] = 10;
$product[0][0] = SPK;
$product[0][1] = Spark Plugs;
$product[0][2] = 4;
Array Functions
Sorting Arrays
It is often useful to sort related data stored in an array. Taking a one-dimensional array and sorting it
into order is quite easy.
The following code results in the array being sorted into ascending alphabetical order:
$products = array( Tires, Oil, Spark Plugs );
sort($products);
Our array elements will now be in the order Oil, Spark Plugs, Tires.
Note that the sort function is case sensitive. All capital letters come before all lowercase letters.
So A is less than Z, but Z is less than a.
Example:
$streets[0] = Elm St.;
$streets[1] = Oak Dr.;
$streets[2] = 7th Ave.;
You enter the following sort statement:
sort($streets);
Now the array becomes as follows:
$streets[0] = 7th Ave.;
$streets[1] = Elm St.;
$streets[2] = Oak Dr.;

144

If we are using an associative array to store items and their prices, we need to use different kinds of sort
functions to keep keys and values together as they are sorted. In this case, we use either asort() or
ksort().
The function asort() orders the array according to the value of each element. If the sorting should be
done by key instead of value, we use ksort(). You can use several other sort statements to sort in other
ways. The table lists all the available sort functions.
Sort Statement
What It Does
sort($arrayname)

Sorts by value; assigns new numbers as the keys.

asort($arrayname)
rsort($arrayname)

Sorts by value; keeps the same key. Good for associative arrays, but not for
indexed arrays.
Sorts by value in reverse order; assigns new numbers as the keys.

arsort($arrayname)

Sorts by value in reverse order; keeps the same key.

ksort($arrayname)

Sorts by key.

krsort($arrayname)

Sorts by key in reverse order.

natsort($arrayname)

Sorts mixed string/number values in natural order. For example, given an array
with values day1, day5, day11, day2, it sorts into the following order: day1,
day2, day5, day11. The previous sort functions sort the array into this order:
day1, day11, day2, day5.

The following code creates an associative array containing the three products and their associated
prices, and then sorts the array into ascending price order.
$prices = array( Tires=>100, Oil=>10, Spark Plugs=>4 );
asort($prices);
//sorts by key
$prices = array( Tires=>100, Oil=>10, Spark Plugs=>4 );
ksort($prices);
Example:
$capitals[1] = Sacramento;
$capitals[2] = Austin;
$capitals[3] = Salem;
After an asort statement, the new array would be as follows:
$capitals[2] = Austin
$capitals[1] = Sacramento
$capitals[3] = Salem

145

Determining Size of Array


You can find out the size of your array by using either the count statement or a sizeof statement. The
format for these statements is as follows:
$n = count($arrayname);
$n = sizeof($arrayname);
After either of these statements, $n will contain the number of elements in the array.

146

PHP: indicates the earliest version of PHP that supports the function.
Function

Description

array()

Creates an array

array_change_key_case() Returns an array with all keys in lowercase or


uppercase
array_chunk()

Splits an array into chunks of arrays

array_combine()

Creates an array by using one array for keys and


another for its values

array_count_values()

Returns an array with the number of occurrences


for each value

array_diff()

Compares array
differences

array_diff_assoc()

Compares array keys and values, and returns the


differences

array_diff_key()

Compares array keys, and returns the differences

array_fill()

Fills an array with values

array_filter()

Filters elements of an array using a user-made


function

array_flip()

Exchanges all keys with their associated values in


an array

array_intersect()

Compares array values, and returns the matches

array_intersect_assoc()

Compares array keys and values, and returns the


matches

array_intersect_key()

Compares array keys, and returns the


matches

values,

and

returns

the

147

array_key_exists()

Checks if the specified key exists in the array

array_keys()

Returns all the keys of an array

array_merge()

Merges one or more arrays into one array

array_multisort()

Sorts multiple or multi-dimensional arrays

array_pad()

Inserts a specified number of items, with a


specified value, to an array

array_pop()

Deletes the last element of an array

array_product()

Calculates the product of the values in an


array

array_push()

Inserts one or more elements to the end of $data = array("Donald", "Jim", "Tom");
an array
array_push($data, "Harry"); //Donald Jim Tom Harry

array_rand()

Returns one or more random values from an $data = array("white", "black", "red");
array
echo "Today's color is " . $data[array_rand($data)];

array_reduce()

Returns an array as a string, using a userdefined function

array_reverse()

Returns an array in the reverse order

array_search()

Searches an array for a given value and


returns the key

array_shift()

Removes the first element from an array, and $data = array("Donald", "Jim", "Tom");
returns the value of the removed element
array_shift($data); //Jim Tom

$data = array("hero" => "Holmes", "villain" =>


"Moriarty");
print_r(array_keys($data)); //hero villain

$data
=
array("Donald",
array_pop($data); //removes Tom

148

"Jim",

"Tom");

array_slice()

Returns selected parts of an array

array_splice()

Removes and replaces specified elements of


an array

array_sum()

Returns the sum of the values in an array

array_udiff()

Compares array values in a user-made


function and returns an array

array_unique()

Removes duplicate values from an array

array_unshift()

Adds one or more elements to the beginning


of an array

array_values()

Returns all the values of an array

array_walk()

Applies a user function to every member of


an array

arsort()

Sorts an array in reverse order and maintain


index association

asort()

Sorts an array and maintain index association

compact()

Create array containing variables and their


values

count()

Counts elements in an array

current()

Returns the current element in an array

each()

Returns the current key and value pair from


an array

end()

Sets the internal pointer of an array to its last


element

149

extract()

Imports variables into the current symbol


table from an array

in_array()

Checks if a specified value exists in an array

key()

Fetches a key from an array

krsort()

Sorts an array by key in reverse order

ksort()

Sorts an array by key

list()

Assigns variables as if they were an array

natcasesort()

Sorts an array using a case insensitive "natural


order" algorithm

natsort()

Sorts an array using a "natural order"


algorithm

next()

Advance the internal array pointer of an array

pos()

Alias of current()

prev()

Rewinds the internal array pointer

range()

Creates an array containing a range of


elements

reset()

Sets the internal pointer of an array to its first


element

rsort()

Sorts an array in reverse order

shuffle()

Shuffles an array

sizeof()

Alias of count()

sort()

Sorts an array

uasort()

Sorts an array with a user-defined function


and maintain index association

$data = array("hero"=>"Holmes", "villain"=>"Moris");


print_r(array_keys($data)); //villain hero

150

Built-in Arrays
PHP has several built-in arrays that you can use when writing PHP scripts. Different types of information
are stored in different arrays. For example, information about your server (such as headers, paths, and
script locations) is stored in an array called $_SERVER.
Array
$GLOBALS[]

Description
Contains all the global variables. For example, if you use the statement,
$testvar = 1, you can then access the variable as $GLOBALS [testvar].
$ _POST[]
Contains all the variables contained in a form if the form uses method=post.
$HTTP_POST_VARS[]
Same as $ _POST.
$ _GET[]
Contains all the variables passed from a previous page as part of the URL. This
includes variables passed in a form using method=get.
$HTTP_GET_VARS[]
Same as $ _GET.
$ _COOKIE[]
Contains all the cookie variables.
$HTTP_COOKIE_VARS[] Same as $ _COOKIE.
$ _SESSION[]
Contains all the session variables.
$HTTP_SESSION_VARS[] Same as $ _SESSION.
$_REQUEST[]
Contains all the variables together that are in $_POST, $_GET, and $_SESSION.
$_FILES[]
Contains the names of files that have been uploaded.
$HTTP_FILES_VARS[]
Same as $_FILES.
$_SERVER[]
Contains information about your server. Because your Web server provides
the information, the information thats available depends on what server
youre using.
$HTTP_SERVER_VARS[] Same as $_SERVER.
$_ENV[]
Contains information provided by your operating system, such as the
operating system name, the system drive, and the path to your temp
directory. This info varies depending on your operating system
$HTTP_ENV_VARS[]
Same as $_ENV.

The $_SERVER and $_ENV arrays contain different information, depending on the server and operating
system youre using. You can see what information is in the arrays for your particular server and
operating system by using the following statements:
foreach($_SERVER as $key =>$value)
echo Key=$key, Value=$value\n;
The output includes such lines as the following:
Key=HTTP_HOST, Value=127.0.0.1
Key=HTTP_ACCEPT, Value=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Key=HTTP_ACCEPT_LANGUAGE, Value=en-us,en;q=0.5

151

Key=HTTP_ACCEPT_ENCODING, Value=gzip, deflate


Key=HTTP_ACCEPT_CHARSET, Value=ISO-8859-1,utf-8;q=0.7,*;q=0.7
Key=HTTP_CONNECTION, Value=keep-alive
Key=WINDIR, Value=C:\Windows
Key=SERVER_SIGNATURE, Value=
Key=SERVER_SOFTWARE, Value=Apache/2.2.17 (Win32) PHP/5.3.6
Key=SERVER_ADDR, Value=127.0.0.1
Key=SERVER_PORT, Value=80
Key=REMOTE_ADDR, Value=127.0.0.1
Key=DOCUMENT_ROOT, Value=C:/Program Files (x86)/VertrigoServ/www
Key=SERVER_ADMIN, Value=lata@jal.com
Key=SCRIPT_FILENAME, Value=C:/Program Files (x86)/VertrigoServ/www/environment.php
Key=REMOTE_PORT, Value=2005
Key=GATEWAY_INTERFACE, Value=CGI/1.1
Key=SERVER_PROTOCOL, Value=HTTP/1.1
Key=REQUEST_METHOD, Value=GET
Key=QUERY_STRING, Value=
Key=SCRIPT_NAME, Value=/environment.php
Key=PHP_SELF, Value=/environment.php
The PHP_SELF element shows the file that contains the script that is currently running. You can see the
information in the $_ENV array by using the phpinfo() statement with a 16 to specify the environmental
variables, as follows:
phpinfo(16);

Practice 6.4
1. Write a program that calculates the factorial of a number. For example 10! (10x9xx2x1)
2. Write a program that prints the following:
123456789
23456789
3456789
456789
56789
6789
789
89
9
3. Write a program stores name, sex, age and income of a person using associative array.

152

1.7 Functions in PHP


Applications often perform the same task at different points in the script or in different scripts. This is
when functions come in handy. A function is a group of PHP statements that perform a specific task. You
can use the function wherever you need to perform the task.
Defining Functions
You can create a function by putting the code into a function block. The general format is as follows:
function functionname($argument1, $argument2, .)
{
block of statements;
return value;
}
Example:
function addNumbers($a, $b)
{
$sum = $a +$b;
return $sum
}
Calling a function
The following line is the simplest possible call to a function:
function_name();
This calls a function named function_name that does not require parameters. This line of code
ignores any value that might be returned by this function.
Most functions do require one or more parametersinformation given to a function when it is called
that influences the outcome of executing the function. We pass parameters by placing the data or the
name of a variable holding the data inside parentheses after the function name. A call to a function with
a parameter resembles the following:
function_name(parameter);
Example: other possible calls
function_name(2);
function_name(7.993);
function_name($variable);
In the last line, $variable might be any type of PHP variable, including an array. A parameter can be any
type of data, but particular functions will usually require particular data types.
You can call functions by passing multiple values to the function by putting the values between the
parentheses as follows:

153

functionname(value1,value2,...);
Example: to call the above addNumbers function:
$result = addNumbers(30,20);
Pass by Reference Versus Pass by Value
If we want to write a function called increment() that allows us to increment a value, we might be
tempted to try writing it as follows:
function increment($value, $amount)
{
$value = $value +$amount;
}
This code will be of no use. The output from the following test code will be 10.
$value = 10;
increment ($value, 1);
echo $value;
The contents of $value have not changed. This is because of the scope rules. This code creates a variable
called $value which contains 10. It then calls the function increment(). The variable $value in the
function is created when the function is called. One is added to it, so the value of $value is 11 inside the
function, until the function ends, and we return to the code that called it. In this code, the variable
$value is a different variable, with global scope, and therefore unchanged.
One way of overcoming this is to declare $value in the function as global, but this means that in order to
use this function, the variable that we wanted to increment would need to be named $value. A better
approach would be to use pass by reference.
The normal way that function parameters are called is called pass by value. When you pass a parameter,
a new variable is created which contains the value passed in. It is a copy of the original. You are free to
modify this value in any way, but the value of the original variable outside the function remains
unchanged.
The better approach is to use pass by reference. Here, when a parameter is passed to a function, rather
than creating a new variable, the function receives a reference to the original variable. This reference
has a variable name, beginning with a dollar sign, and can be used in exactly the same way as another
variable. The difference is that rather than having a value of its own, it merely refers to the original. Any
modifications made to the reference also affect the original.
We specify that a parameter is to use pass by reference by placing an ampersand (&) before the
parameter name in the functions definition. No change is required in the function call.

154

The preceding increment() example can be modified to have one parameter passed by reference, and it
will work correctly.
function increment(&$value, $amount = 1)
{
$value = $value +$amount;
}
We now have a working function, and are free to name the variable we want to increment anything we
like. As already mentioned, it is confusing to humans to use the same name inside and outside a
function, so we will give the variable in the main script a new name. The following test code will now
echo 10 before the call to increment(), and 11 afterwards.
$a = 10;
echo $a;
increment ($a);
echo $a ;
Variable Scope
A variable declared within a function remains local to that function. In other words, it will not be
available outside the function or within other functions. In larger projects, this can save you from
accidentally overwriting the contents of a variable when you declare two variables with the same name
in separate functions.
A variables scope controls where that variable is visible and useable. Different programming languages
have different rules that set the scope of variables. PHP has fairly simple rules:
Variables declared inside a function are in scope from the statement in which they are declared
to the closing brace at the end of the function. This is called function scope. These variables are
called local variables.
Variables declared outside of functions are in scope from the statement in which they are
declared to the end of the file, but not inside functions. This is called global scope. These
variables are called global variables.
Using require() and include() statements does not affect scope. If the statement is used within a
function, function scope applies. If it is not inside a function, global scope applies.
The keyword global can be used to manually specify that a variable defined or used within a
function will have global scope.
Variables can be manually deleted by calling unset($variable_name). A variable is no longer in
scope if it has been unset.
Example: local variable
<?php
function test()
{
$testvariable = "this is a test variable";

155

}
echo "test variable: $testvariable<br>";
?>
The value of the variable $testvariable is not printed. This is because no such variable exists outside the
test() function. Note that the attempt to access a nonexistent variable does not cause an error. Similarly,
a variable declared outside a function will not automatically be available within it.
If you want a variable created within a function to be global, we can use the keyword global as follows:
function fn() {
global $var;
$var = contents;
echo inside the function, \$var = .$var.<br>;
}
fn();
echo outside the function, \$var = .$var.<br>;
output:
inside the function, $var = contents
outside the function, $var = contents

Practice 6.5
1. Write a PHP function that identifies the largest number of the given numbers.
2. Write a PHP function that returns the cubed value of the given number.
3. Write a PHP function that displays numbers between 150 and 200 that are divisible ten.

3. Processing Data with PHP


2.1 Working with Forms
We use one of two methods to submit form information. The methods pass the form data differently
and have different advantages and disadvantages:
GET method: The form data is passed by adding it to the URL that calls the form-processing
script. For example, the URL may look like this:
processform.php?lname=Smith&fname=Goliath
The advantages of this method are simplicity and speed. The disadvantages are that less data
can be passed and the information is displayed in the browser, which can be a security problem
in some situations.

156

POST method: The form data is passed as a package in a separate communication with the
processing script. The advantages of this method are unlimited information passing and security
of the data. The disadvantages are the additional overhead and slower speed.

The form data is available in the processing script in the PHP built-in arrays. Information from forms that
use the POST method is available in the built-in array called $_POST. If your form uses the GET method,
the information is available in the array $_GET. Both types of form information are also stored in an
array called $_REQUEST. Each array index is the name of the input field in the form. You get information
from the array by using the form field name as the array key. The syntax is:
$_POST[form element name]
$_GET[form element name]
For example, suppose that you echo the following field in your form that uses the POST method:
<input type=text name=firstName>;
The value entered in this textbox can be accessed by $_POST[firstName] which contains the text the
user typed into the field. If the form uses GET method, the above textbox can be accessed as
$_GET[firstName].

2.2 Database Programming


In this course, we use MySQL as our database server. MySQL is a free and open source database that has
a lot of users especially for web applications. It can be downloaded from internet freely.
Whichever database youre using, the steps to interact with a database are similar:
1. Connect to the database.
2. Send an SQL query that contains instructions for the database software.
3. If you retrieved data from the database, process the data.
4. Close the connection to the database.
Connecting to the database
The first step in a database interaction is connecting to the database. You use a PHP function to connect
to the database. To make the connection, you need to supply the function with three things:
Location: The database does not need to be on the same computer where PHP is installed.
Therefore, you need to tell the PHP connect function the name of the computer where the
database is located (the hostname). You can supply either a domain name (such as
mycompany.com) or an IP address (such as 172.17.204.2). If the database is on the same
computer as PHP, you can use localhost for the hostname.
Account name: You must provide a valid account name that can be used to access the database.
The database administrator sets this up. If youre using a Web hosting company, you will be
given a valid account name.

157

Password: You have to have a valid password to access the database. The database
administrator sets this up. If youre using a Web hosting company, you will be given a valid
password for your account.

The syntax for creating connection to MySQL database:


$connect = mysql_connect($host,$account,$password);
ID
FirstName
LastName
sam232
John
Walter
sam543
Samuel
David
sam534
George
Graham
sam979
Ana
Bush

Table 6.8 sample database used as an example

Sex
M
M
M
F

Telephone
4325456342
5424256345
2634345643
3462737485

Status
1
1
0
0

After connecting to the database, the next step is selecting database. An RDBMS can create and
maintain many databases, so you need to tell it which database you want to use.
The syntax for selecting database is:
$db = mysql_select_db(string database, [int database_connection] );
Example:
<?php
$con = mysql_connect("localhost","root","vertrigo");
mysql_select_db(books);
//other statements
?>
Querying the Database
To actually perform the query, we can use the mysql_query() function. Before doing this, however, its a
good idea to set up the query you want to run:
$query = select * from books;
We can now run the query:
$result = mysql_query($query);
The mysql_query() function has the following prototype:
int mysql_query(string query, [int database_connection] );

158

You pass it the query you want to run, and optionally, the database connection (again, in this case $db).
If not specified, the function will use the last opened link. If there isnt one, the function will open the
default one as if you had called mysql_connect().
You might want to use the mysql_db_query() function instead. It has the following prototype:
int mysql_db_query(string database, string query, [int database_connection] );
Its very similar but allows you to specify which database you would like to run the query on. It is like a
combination of the mysql_select_db() and mysql_query() functions. Both of these functions return a
result identifier (that allows you to retrieve the query results) on success and false on failure. You should
store this (as we have in this case in $result) so that you can do something useful with it.
Example: executing query
$sql = SELECT * FROM Product;
$result = mysql_query($sql,$connect);
Putting all together:
<?php
$account = david;
$password = gotago;
$connect = mysql_connect($host, $account, $password);
$db = mysql_select_db(Catalog, $connect);
$sql = SELECT * FROM Product;
$result = mysql_query($sql, $connect);
//other code
?>
Processing Data
To process the data returned from database, you need to get it from the temporary table where it was
placed when the SQL query was executed. You use PHP database functions to get the data from the
temporary table.
The data is stored in the temporary table in rows and columns. You can use PHP functions to retrieve
one row from the table and store it in an array, with the field names as the array keys. For MySQL, the
statement is as follows:
$row = mysql_fetch_array($result);
It requires one of the mysql_fetch functions to make the data fully available to PHP. The fetching
functions of PHP are as follows:
mysql_fetch_assoc: returns rows as associative array
mysql_fetch_row: returns row as an enumerated array

159

mysql_fetch_object: returns row as an object


mysql_fetch_array: returns row as an associative array or enumerated array
mysql_result: returns one cell of data
The difference between the three main fetching functions is small.
The most useful fetching function, mysql_fetch_array, offers the choice of results as an associative or an
enumerated array or both, which is the default. This means you can refer to outputs by database field
name rather than number:
$query = SELECT ID, LastName, FirstName FROM users WHERE Status = 1;
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
echo $row[ID], $row[LastName], $row[FirstName]<BR>\n;
}
Remember that mysql_fetch_array can also be used exactly the same way as mysql_fetch_row with
numerical identifiers rather than field names. By using this function, you leave yourself the option. If you
want to specify offset or field name rather than making both available, you can do it like this:
$offset_row = mysql_fetch_array($result, MYSQL_NUM); or
$associative_row = mysql_fetch_array($result, MYSQL_ASSOC);
Its also possible to use MYSQL_BOTH as the second value.
$both = mysql_fetch_array($result, MYSQL_BOTH);
The mysql_fetch_assoc function returns an associative array that corresponds to the fetched row, or
FALSE if there are no more rows. mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with
MYSQL_ASSOC for the optional second parameter. It only returns an associative array.
$query = SELECT ID, LastName, FirstName FROM users WHERE Status = 1;
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result))
{
echo $row[ID], $row[LastName], $row[FirstName]<BR>\n;
}
The function mysql_fetch_object performs much the same task, except the row is returned as an object
rather than an array. Obviously, this is helpful for those among those who utilize the object-oriented
notation:
$query = SELECT ID, LastName, FirstName FROM users WHERE Status = 1;
$result = mysql_query($query);
while ($row = mysql_fetch_object($result))
{

160

echo $row->ID, $row->LastName, $row->FirstName<BR>\n;


}
mysql_fetch_row() fetches one row of data from the result associated with the specified result
identifier. The row is returned as an array. Each result column is stored in an array offset, starting at
offset 0. Subsequent call to mysql_fetch_row() would return the next row in the result set, or FALSE if
there are no more rows.
The most general one is mysql_fetch_row, which can be used something like this:
$query = SELECT ID, LastName, FirstName FROM users WHERE Status = 1;
$result = mysql_query($query);
while ($name_row = mysql_fetch_row($result))
{
print($name_row[0] $name_row[1] $name_row[2]<BR>\n);
}
This code will output the specified rows from the database, each line containing one row or the
information associated with a unique ID (if any).
In early versions of PHP, mysql_fetch_row was considered to be significantly faster than
mysql_fetch_object and mysql_fetch_array, but this is no longer an issue, as the speed differences have
become imperceptible. The PHP group now recommends use of mysql_fetch_array over
mysql_fetch_row because it offers increased functionality and choice at little cost in terms of
programming difficulty, performance loss, or maintainability.
Last and least of the fetching functions is mysql_result(). You should only consider using this function in
situations where you are positive you need only one piece of data to be returned from MySQL. An
example of its usage follows:
$query = SELECT count(*) FROM users;
$db_result = mysql_query($query);
$datapoint = mysql_result($db_result, 0, 0);
The mysql_result function takes three arguments: result identifier, row identifier, and (optionally) field.
Field can take the value of the field offset as above, or its name as in an associative array (Surname),
or its MySQL field-dot-table name (personal_info.Surname).
Example: a program that retrieves data from database and display in table
<?php
$con = mysql_connect("localhost","",""); //if no username and password needed
mysql_select_db(customers);
$query = SELECT * FROM users;
$result = mysql_query($query);
echo(<TABLE>\n<TR><TH>Customers of ABC company</TH></TR>\n<TR>);

161

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


echo(<TD>$users_row[ID]</TD>\n);
echo(<TD>$users_row[FirstName]</TD>\n);
echo(<TD>$users_row[LastName]</TD>\n);
echo(<TD>$users_row[Sex]</TD>\n);
echo(<TD>$users_row[Telephone]</TD>\n);
echo(<TD>$users_row[Status]</TD>\n);
}
echo(</TR></TABLE><BR>\n);
?>
Inserting Data into Database
Inserting new items into the database is remarkably similar to getting items out of the database. You
follow the same basic stepsmake a connection, send a query, and check the results. In this case, the
query you send will be an INSERT rather than a SELECT.

Figure 6.2 customer registration form


The HTML to accept user data is:
<HTML>
<HEAD>
<TITLE>Processing HTML forms with PHP</TITLE>

162

</HEAD>
<BODY>
<H1>Newsletter sign-up form</H1>
<P> Please, fill the form to be our registered customer</P>
<FORM METHOD=post ACTION=customer.php>
ID: <INPUT TYPE=text NAME=ID> <BR>
First name: <INPUT TYPE=text NAME=FirstName> <BR>
Last name: <INPUT TYPE=text NAME=LastName> <BR>
Sex: <INPUT TYPE=text NAME=Sex> <BR>
Telephone: <INPUT TYPE=text NAME=Telephone> <BR><BR>
<INPUT TYPE=submit NAME=submit VALUE=Submit>
</FORM>
</BODY>
</HTML>
The customer.php file that process the data collected by the above form is the following:
<?php
// Open connection to the database
mysql_connect(localhost, phpuser, sesame) or die(Failure to connect to database);
mysql_select_db(customers);
$ID = $_POST[ID]);
$fn = $_POST[FirstName];
$ln = $_POST[LastName];
$sx = $_POST[Sex];
$tl = $_POST[Telephone];
$st = 1;
$query = INSERT INTO users VALUES($ID, $fn, $ln, $sx, $tl, $st);
$result = mysql_query($query);
if (mysql_affected_rows() == 1) {
echo <P>Your information has been saved.</P>;
}
else {
echo <P>Something went wrong with your signup attempt.</P>;
}
?>
Example: a program that displays the content of a table called employee from HR database in table
format
$con = mysql_connect(localhost, root, vertrigo) or
die(Cant connect to databse);

163

mysql_select_db(HR);
$res=mysql_query(select * from employee, $con);
echo <table border=1>;
while($row=mysql_feth_array($res, MYSQL_BOTH))
{
echo <tr>
echo <td> $row[name] </td>;
echo <td> $row[ID] </td>;
echo <td> $row[salary] </td>;
echo <td> $row[sex] </td>;
echo <td> $row[BD] </td>;
echo </tr>;
}
echo </table>;
Closing the connection
Any open database connections are closed when the script ends. However, it is good programming
practice to close the connections in the script to avoid any possible problems. You close database
connections the same way you open them with a PHP function. For example, for MySQL, use the
following function to close a database connection:
mysql_close($connect);
Other Important PHP-Database Functions
mysql_affected_rows Get number of affected rows in previous MySQL operation. It helps you to
know how many rows have been deleted, inserted, modified, etc. by the last mysql_query() operation.
int mysql_affected_rows ( [resource link_identifier])
mysql_affected_rows() returns the number of rows affected by the last INSERT, UPDATE or DELETE
query associated with link_identifier. If the link identifier isn't specified, the last link opened by
mysql_connect() is assumed.
mysql_create_db Create a MySQL database. The syntax is:
bool mysql_create_db (string database name [, resource link_identifier]);
mysql_create_db() attempts to create a new database on the server associated with the specified link
identifier.
mysql_drop_db Drop (delete) a MySQL database
bool mysql_drop_db ( string database_name [, resource link_identifier])
mysql_drop_db() attempts to drop (remove) an entire database from the server associated with the
specified link identifier.
mysql_num_rows Get number of rows in result. The syntax is:

164

int mysql_num_rows ( resource result)


mysql_num_rows() returns the number of rows in a result set. This command is only valid for SELECT
statements. To retrieve the number of rows affected by a INSERT, UPDATE or DELETE query, use
mysql_affected_rows().
mysql_num_fields Get number of fields in result. The syntax is:
int mysql_num_fields ( resource result)
mysql_num_fields() returns the number of fields(columns) in a result set.
mysql_field_name Get the name of the specified field in a result. The syntax is:
string mysql_field_name ( resource result, int field_index)
mysql_field_name() returns the name of the specified field index. result must be a valid result identifier
and field_index is the numerical offset of the field. Note that field_index starts at 0.
mysql_list_tables List tables in a MySQL database. The syntax is:
resource mysql_list_tables ( string database [, resource link_identifier])
mysql_list_tables() takes a database name and returns a result pointer much like the mysql_query()
function. You can use the mysql_tablename() function to extract the actual table names from the result
pointer, or any other result table function such as mysql_fetch_assoc(). The database parameter is the
name of the database to retrieve the list of tables from. Upon failure, mysql_list_tables() returns FALSE.
Example:
<?php
$link = mysql_connect('localhost', 'root', 'vertrigo');
$db_list = mysql_list_dbs($link);
while ($row = mysql_fetch_object($db_list)) {
echo $row->Database . "<br>";
}
$tn = mysql_list_tables("teaching", $link);
$row = mysql_fetch_array($tn, MYSQL_NUM);
echo $row[0];
?>

Using ODBC
PHP can also connect to databases by using ODBC. The following are the functions you can use for such
purpose.
odbc_connect ( string datasourcename, string user, string password [, int cursor_type])
This function returns an ODBC connection id or 0 on error. The connection id returned by this functions
is needed by other ODBC functions. You can have multiple connections open at once.

165

The optional fourth parameter sets the type of cursor to be used for this connection. This parameter is
not normally needed, but can be useful. The following constants are defined for cursortype:
SQL_CUR_USE_IF_NEEDED
SQL_CUR_USE_ODBC
SQL_CUR_USE_DRIVER
SQL_CUR_DEFAULT
odbc_exec ( resource connection_id, string query_string)
This returns an ODBC result identifier if the SQL command was executed successfully. odbc_exec() will
send an SQL statement to the database server specified by connection_id. This parameter must be a
valid identifier returned by odbc_connect().
odbc_do ( resource conn_id, string query)
This will execute a query on the given connection just like odbc_exec.
odbc_fetch_array ( resource result [, int rownumber])
This fetches a result row as an associative array
odbc_fetch_object (resource result [, int rownumber])
This fetches a result row as an object
odbc_fetch_row ( resource result_id [, int row_number])
If odbc_fetch_row() was succesful (there was a row), TRUE is returned. If there are no more rows, FALSE
is returned.
odbc_fetch_row() fetches a row of the data that was returned by odbc_do() / odbc_exec(). After
odbc_fetch_row() is called, the fields of that row can be accessed with odbc_result(). If row_number is
not specified, odbc_fetch_row() will try to fetch the next row in the result set.
odbc_commit ( resource connection_id)
All pending transactions on connection_id are committed. It returns TRUE on success, FALSE on failure.
odbc_close ( resource connection_id)
odbc_close() will close down the connection to the database server associated with the given
connection identifier.
Example:
<?php
$con = odbc_connect(registrar", root", vertrigo") or
die("Connecting to databse failed.");
$sql = "select * from student where ID='" . $_POST['ID']. "'";
$rs = odbc_exec($con, $sql);

166

while(($row = odbc_fetch_array($rs, ODBC_ASSOC_ARRAY)) != NULL)


{
print("&nbsp;". $row['fullname']. "<BR>");
print("&nbsp;". $row['birth_date']. "<BR>");
print("&nbsp;". $row['email']. "<BR>");
}
odbc_close($con);
?>

Practice 6.6
1. Write a program that connects and retrieves data from database. Create a database called
student first, and then fill some data to it. Connect to this database and display its content in
your web page. Student database contains the following table:
first name

last name

city

email

2. Write a program that accepts data from students and store it in the students table created
above.
3. Write a program that deletes a student with ID SSD/2314/00 from the above table
4. Write a program that displays students who are from Jimma.

4. Advanced concepts in PHP


3.1 Classes in PHP
The basic elements of object-oriented programs are objects. Its easiest to understand objects as
physical objects. For example, a car is an object.
A car has properties, such as color, model, engine, and tires, also called attributes. A car has things it can
do, too, such as move forward, move backward, park, roll over, and play dead (well, mine does anyway).
A class is the script that serves as the template, or the pattern, that is used to create an object. The class
defines the properties, the attributes, of the object. It also defines the things the object can do its
responsibilities. For example, you write a class that defines a car as four wheels and an engine and lists
the things it can do, such as move forward and park. Then, given that class, you can write a statement
that creates a car object.

Defining a Class
A minimal class definition looks as follows:
class classname

167

{
}
In order to be useful, our classes need attributes and operations. We create attributes by declaring
variables within a class definition using the keyword var. The following code creates a class called
classname with two attributes, $attribute1 and $attribute2.
We create operations by declaring functions within the class definition. The following code will create a
class named classname with two operations. The operation operation1() takes no parameters and
operation2() takes two parameters.
class classname
{
var $attribute1;
var $attribute2;
function operation1()
{
//code here
}
function operation2($param1, $param2)
{
//code here
}
}

Constructors
Most classes will have a special type of operation called a constructor. A constructor is called when an
object is created, and it also normally performs useful initialization tasks such as setting attributes to
sensible starting values or creating other objects needed by this object.
A constructor is declared in the same way as other operations, but has the same name as the class.
Though we can manually call the constructor, its main purpose is to be called automatically when an
object is created. The following code declares a class with a constructor:
class classname
{
function classname($param)
{
echo Constructor called with parameter $param <br>;
}
}

Instantiation of Class
168

After we have declared a class, we need to create an objecta particular individual that is a member of
the classto work with. This is also known as creating an instance or instantiating a class. We create an
object using the new keyword. We need to specify what class our object will be an instance of, and
provide any parameters required by our constructor.
The following code declares a class called person with a constructor, and then creates three objects of
type person:
class person
{
function person($param)
{
echo Constructor called with parameter $param <br>;
}
}
$a = new person(First); //instantiation
$b = new person(Second); //another instantiation
$c = new person();//yet another instantiation
When we use a class method or property, we must use the -> operator. The keyword this tells PHP
that the property of method belongs to the class being defined.
<?php
class automobile_class
{
var $color; //the color of the car
var $max_speed; //the maximum speed
var $price; //the price of the car, in dollars
function is_cheap()
{
$this->display();
return ($this->price < 5000); //returns TRUE if the price is smaller than 5000 dollars
}
function display()
{
echo "The price is $this->price<br>";
}
}
$car_object = new automobile_class();
$car_object->color = "red";
$car_object->price = 6000;
$cheap = $car_object->is_cheap(); //call is_cheap() method of the class
if($cheap)
print "This car is cheap!";

169

else
print "This car is expensive!";
?>
You can see that we use the "->" operator to access and modify objects properties. After that, we use
the same operator to call a method.

Implementing Inheritance in PHP


If our class is to be a subclass of another, you can use the extends keyword to specify this. The following
code creates a class named B that inherits from some previously defined class named A.
class A
{
var $attribute1;
function operation1()
{
//code here
}
}
class B extends A
{
var $attribute2;
function operation2()
{
//code here
}
}
All the following accesses to operations and attributes of an object of type B would be valid:
$b = new B();
$b->operation1();
$b->attribute1 = 10;
$b->operation2();
$b->attribute2 = 10;
Because class B extends class A, we can refer to operation1() and $attribute1, although these were
declared in class A. As a subclass of A, B inherits all the functionality and data. In addition, B has declared
an attribute and an operation of its own.

3.2 Working with Files


3.2.1 Uploading Files
You may want users to upload files to your Web site. For example, you may want users to be able to
upload resumes to your job-search Web site or pictures to your photo album Web site.

170

You can display a form that allows a user to upload a file by using an HTML form designed for that
purpose. The general format of the form is as follows:
<form enctype=multipart/form-data action=processfile.php method=POST>
<input type=hidden name=MAX_FILE_SIZE value=30000>
<input type=file name=user_file>
<input type=submit value=Upload File>
</form>
Notice the following points regarding the form:
 The enctype attribute is used in the form tag. You must set this attribute to multipart/form-data
when uploading a file to ensure the file arrives correctly.
 A hidden field is included that sends a value (in bytes) for MAX_FILE_SIZE. If the user tries to
upload a file that is larger than this value, it wont upload. When sending the value for
MAX_FILE_SIZE in your form, you need to consider two size settings in php.ini, as follows
upload_max_filesize: The MAX_FILE_SIZE you send in your upload form cant be larger than the
value of upload_max_filesize. If you are uploading a larger file and need to send a
MAX_FILE_SIZE larger than the current value of upload_max_filesize, you need to increase the
value of upload_max_filesize by editing the php.ini file. The default value for this setting is 2M.
post_max_size: The total amount of information you send in a POST form cant be larger than
the value of post_max_size. The default value for this setting is 8M. You can increase this value if
necessary by editing your php.ini file.
 The input field that uploads the file is of type file.
The value for MAX_FILE_SIZE must be sent before the file is uploaded if you want the file size limit to
apply to the uploading file.
When the user submits the form, the file is uploaded to a temporary location. The script that processes
the form needs to copy the file to another location because the temporary file is deleted as soon as the
script is finished. You can use phpinfo() to see where the temporary files are stored. If you dont like the
location of the temporary directory, you can change it by changing upload_tmp_dir in the php.ini file. If
no directory is specified in php.ini, a default temporary directory is used.

Accessing Information About An Uploaded File


Along with the file, information about the file is sent with the form. This information is stored in the PHP
built-in array called $_FILES. An array of information is available for each file that was uploaded. As with
any other form, you can obtain the information from the array by using the name of the field. You can
get information about the uploaded file from the following array:
$_FILES[fieldname][name]
$_FILES[fieldname][type]
$_FILES[fieldname][tmp_name]
$_FILES[fieldname][size]

171

For example, suppose you use the following field to upload a file:
<input type=file name=user_file>
If the user uploads a file named test.txt by using the form, the resulting array that can be used by the
processing script looks something like this:
echo $_FILES[user_file][name];
// test.txt
echo $_FILES[user_file][type];
// text/plain
echo $_FILES[user_file][tmp_name]; //D:\WINNT\php92C.tmp
echo $_FILES[user_file][size];
// 435
In this array, name is the name of the file that was uploaded, type is the type of file, tmp_name is the
path/filename of the temporary file, and size is the size of the file. Notice that name contains only the
filename, while tmp_name includes the path to the file as well as the filename.
If the file is too large to upload, the tmp_name in the array is set to none, and the size is set to 0. By
default, PHP stores the temporary uploaded file in your system directory on Windows (Windows for
Win98/XP and Winnt for Win2000) or /tmp on Unix/Linux. You can change the location of temporary
files by setting php.ini. Look in your php.ini file for the following line:
upload_tmp_dir =

Moving Uploaded Files To Their Destination


Since the temporary file created during upload is deleted when the script finishes, it has to be moved to
another location if you want to store it permanently. The general format of the statement that moves
the file is as follows:
move_uploaded_file(path/tempfilename, path/permfilename);
You can use the following statement to move the file to your desired location, in this case,
c:\data\new_file.txt:
move_uploaded_file($_FILES[user_file][tmp_name], c:\data\new_file.txt);
The destination directory (in this case, c:\data) must exist before the file can be moved to it. This
statement doesnt create the destination directory.
Security can be an issue when uploading files. Allowing strangers to load files onto your computer is
risky; malicious files are possible. So, you probably want to check the files for as many factors as possible
after they are uploaded, using conditional statements to check file characteristics, such as checking for
the expected file type and for the size. In some cases, for even more security, it may be a good idea to
change the name of the file to something else so users dont know where their files are or what theyre
called.

Putting It All Together


This script displays a form for the user to upload an image file, saves the uploaded file, and then displays

172

a message after the file has been successfully uploaded. This script expects the uploaded file to be an
image file, and tests to make sure that it is an image file, but any type of file can be uploaded.
<?php
/* Script name: uploadFile.php
* Description: Uploads a file via HTTP using a POST form.
*/
if($_FILES[pix][tmp_name] == none)
{
echo <b>File did not successfully upload. Check the file size. File must be less than 500K.<br>;
include(form_upload.inc);
exit();
}
if(!ereg(image,$_FILES[pix][type]))
{
echo <b>File is not a picture. Please try another file.</b><br>;
include(form_upload.inc);
exit();
}
else
{
$destination = c:\data.\\.$_FILES[pix][name];
$temp_file = $_FILES[pix][tmp_name];
move_uploaded_file($temp_file,$destination);
echo <p>The file has successfully uploaded: $_FILES[pix][name] $_FILES[pix][size];
}
?>

An Include File That Displays the File Upload Form


<!-- Script Name: form_upload.inc
Description: Displays a form to upload a file -->
<html>
<head><title>File Upload</title></head>
<body>
<ol>
<li>Enter the name of the picture you want to upload to our picture archive or use the browse
button to navigate to the picture file.</li>
<li>When the path to the picture file shows in the text field, click the Upload Picture button.</li>
</ol>
<form enctype=multipart/form-data action=uploadFile.php method=POST>
<input type=hidden name=MAX_FILE_SIZE value=500000>
<input type=file name=pix size=20>
<p><input type=submit name=Upload value=Upload Picture>

173

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

3.2.2 File Input/Output


Many applications require the long-term storage of information. Information can be stored on the
server in flat files or in databases. Flat files are text files stored in the computer file system. Humans can
read flat files by using the operating system commands that display files, such as cat in Linux and Unix.
You can access and edit these files by using any text file editor, such as notepad or gedit. The
information in the flat file is stored as strings, and the PHP script that retrieves the data needs to know
how the data is stored. For example, to retrieve a customer name from a file, the PHP script needs to
know that the customer name is stored in the first 20 characters of every line.
Using a database for data storage requires you to install and learn to use database software, such as
MySQL or Oracle. The data is stored in files created by the database software and can only be accessed
by the database software. Databases can store very complex information that you can retrieve easily.
You dont need to know how the data is stored, just how to interact with the database software. For
example, to retrieve a customer name, the PHP script needs to know only how to tell the database
software that it wants the customer name, using a standard communication language called SQL. The
database software handles the storage and delivers the data, without the script needing to know exactly
where or how the customer name is stored.
Flat files have some advantages over databases:
Available and versatile: You can create and save data in any operating systems file system. You
dont need to install any extra software. Additionally, text data stored in flat files can be read by
a variety of software programs, such as word processors or spreadsheets.
Easy to use: You dont need to do any extra preparation, such as install database software,
design a database, create a database, and so on. Just create the file and store the data with
statements in your PHP script.
Smaller: Flat files store data by using less disk space than databases.
Databases have some advantages as well:
Security: A database provides a security layer of its own, in addition to the security provided by
the operating system. A database protects the data from outside intrusion better than a flat file.
Accessibility of data: You can store data in a database by using a very complex data structure,
specifying data types and relationships among the data. The organization of the data makes it
easy to search the data and retrieve what you need.
Ability to handle multiple users: When many users store or access data in a single file, such as a
file containing names and addresses, a database ensures that users take their turn with the file
to avoid overwriting each others data.

174

Using Flat Files


Flat files are also called text files. Using a flat file requires three steps:
Open the file.
Write data into the file or retrieve data from the file.
Close the file.
The first step, before you can write information into or read information from a file, is to open the file.
The following is the general format for the statement that opens a file:
$fh = fopen(filename,mode)
The variable, $fh, referred to as a file handle, is used in the statements that write data to or read data
from the open file so that PHP knows which file to write into or read from. $fh contains the information
that identifies the location of the open file.
mode can be one of the values in the table
Mode
what it means

what happens when file does not exist

read only

If the file does not exist, a warning message is displayed.

r+

reading and writing

If the file does not exist, a warning message is displayed.

write only

w+

reading and writing

append data at the end of file

If the file does not exist, PHP attempts to create it. If the
file exists, PHP overwrites it.
If the file does not exist, PHP attempts to create it. If the
file exists, PHP overwrites it.
If the file does not exist, PHP attempts to create it.

a+

reading and appending

If the file does not exist, PHP attempts to create it.

Table 6.9 file opening modes


You can open the file grade.txt to read the information in the file with the following statement:
$fh = fopen(grade.txt,r);
Based on this statement, PHP looks for grade.txt in the current directory, which is the directory where
your PHP script is located. If the file cant be found, a warning message is displayed.
A warning condition does not stop the script. The script continues to run, but the file doesnt open, so
any later statements that read or write to the file arent executed. You probably want the script to stop
if the file cant be opened. You can do this with a die statement, as follows:
$fh = fopen(file1.txt,r) or die(Cant open file);
Opening files in write mode

175

You can open a file in a specified directory to store information by using the following type of statement:
$fh = fopen(c:/testdir/happy.txt,w);
If the file does not exist, it is created in the indicated directory. However, if the directory doesnt exist,
the directory is not created, and a warning is displayed.
You can also open a file on another Web site by using a statement such as the following:
$fh = fopen(http://janet.valade.com/index.html,r);
You can use a URL only with a read mode, not with a write mode.
To close a file after you have finished reading or writing it, use the following statement:
fclose($fh);
In this statement, $fh is the file handle variable you created when you opened the file.
Reading from file
You can read from a file by line by line using the fgets statement, which has the following general
format:
$line = fgets($fh)
Sometimes you want to read strings of a certain size from a file. You can tell fgets to read a certain
number of characters by using the following format:
$line = fgets($fh, n)
This statement tells PHP to read a string that is n-1 characters long until it reaches the end of the line or
the end of the file.
Example: a program that reads file line by line until end_of_file and displays it
<?php
$fh = fopen("test.txt", "r") or die("Can't open file");
while(!feof($fh)) {
$line = fgets($fh);
print ("\n$line");
}
fclose($fh);
?>
Another option for file processing is to read a single character at a time from a file. You can do this using
the fgetc() function. We can replace the while loop in our original script with one that uses fgetc():
while (!feof($fp)) {
$char = fgetc($fp);
echo ($char);

176

}
This code reads a single character from the file at a time using fgetc() and stores it in $char, until the end
of the file is reached.
Instead of reading from a file a line at a time, we can read the whole file in one go. This can be done
using readfile(). We can replace the entire script we wrote previously with one line:
readfile(test.txt);
A call to the readfile() function opens the file, echoes the content to standard output (the browser), and
then closes the file. The prototype for readfile() is
int readfile(string filename, int [use_include_path]);
The optional second parameter specifies whether PHP should look for the file in the include_path.
The final way we can read from a file is using the fread() function to read an arbitrary number of bytes
from the file. This function has the following prototype:
string fread(int fp, int length);
The way it works is to read up to length bytes or to the end of file, whichever comes first.
Writing to a File
Writing to a file in PHP is relatively simple. You can use either of the functions fwrite() or fputs(); fputs()
is an alias to fwrite(). We call fwrite() in the following:
fwrite($fp, $outputstring);
This tells PHP to write the string stored in $outputstring to the file pointed to by $fp. Well discuss
fwrite() in more detail before we talk about the contents of $outputstring.
The function fwrite() actually takes three parameters but the third one is optional. The prototype for
fwrite() is:
int fwrite(int fp, string str, int [length]);
The third parameter, length, is the maximum number of bytes to write. If this parameter is supplied,
fwrite() will write string to the file pointed to by fp until it reaches the end of string or has written length
bytes, whichever comes first.
Example: write data to file
<?php
$fh = fopen(test.txt,a);
$data = This content is written to file \n;
$data = $data . This line is also written;
fwrite($fh, $data);
fclose($fh);
?>

177

The other way to write to file is to use fputs function. The syntax is:
Int fputs($fh, String str, [int length]);
This writes text to a file, an alias for fwrite. It returns the number of bytes written to the file or FALSE if
the function fails.
Seeking in File
The function fseek() can be used to set the file pointer to some point within the file. It moves the file
pointer, depending on the parameters. The syntax is:
fseek($fh, int offset, mode);
The value specified in offset is the character location to move the pointer to. You can set mode to:
SEEK_SET (moves to char in position offset),
SEEK_CUR (moves offset characters forward from current position), or
SEEK_END (moves offset characters back from the last character).
The rewind() function is equivalent to calling the fseek() function with an offset of zero. For example,
you can use fseek() to find the middle record in a file or to perform a binary search.
Getting information about files
Often you want to know information about a file. PHP has functions that allow you to find out file
information about the files from within a script.
You can find out whether a file exists with the file_exists statement, as follows:
$result = file_exists(filename);
After this statement, $result contains either TRUE or FALSE. The function is often used in a conditional
statement, such as the following:
if(!file_exists(stuff.txt))
{
echo File not found!\n;
}
Other functions are:
Function
is_file(stuff.txt)

What It Does

Output

is_dir(stuff.txt)

Tests whether the file is a regular file, rather TRUE or FALSE


than a directory or other special type of file
Tests whether the file is a directory
TRUE or FALSE

is_executable(do.txt)

Tests whether the file is executable

TRUE or FALSE

is_writable(stuff.txt)

Tests whether you can write to the file

TRUE or FALSE

is_readable(stuff.txt)

Tests whether you can read the file

TRUE or FALSE

filesize(stuff.txt)

Returns the file size in bytes

Integer or FALSE

178

basename(/t1/do.txt)

Returns the filename from the path

do.txt

dirname(/t1/do.txt)

Returns the directory name from the path

/t1

copy(oldfile, newfile)

Copy an existing file into a new file

TRUE or FALSE

rename(oldname,newname)

renames a file oldname to newname

TRUE or FALSE

unlink(badfile.txt)

deletes an unwanted file

TRUE or FALSE

Example:
if(!file_exists(book.txt))
copy(book.txt, library.txt);
else
echo File already exists!\n;

Working with Date and Time


PHP's time() function gives you all the information that you need about the current date and time. It
requires no arguments and returns an integer. For us humans, the returned number is a little hard on
the eyes, but it's extremely useful nonetheless.
echo time();
output:
1060751270
This represents August 12th, 2003 at 10:07PM
The integer returned by time() represents the number of seconds elapsed since midnight GMT on
January 1, 1970. This moment is known as the Unix epoch, and the number of seconds that have elapsed
since then is referred to as a timestamp. PHP offers excellent tools to convert a timestamp into a form
that humans are comfortable with. Even so, isn't a timestamp a needlessly convoluted way of storing a
date? In fact, the opposite is true. From just one number, you can extract enormous amounts of
information. Even better, a timestamp can make date arithmetic much easier than you might imagine.
The getdate() function optionally accepts a timestamp and returns an associative array containing
information about the date. If you omit the timestamp, getdate() works with the current timestamp as
returned by time(). The table lists the elements contained in the associative array returned by getdate().
Key
seconds
minutes
hours
mday
wday
mon
year

Description
Seconds past the minute (059)
Minutes past the hour (059)
Hours of the day (023)
Day of the month (131)
Day of the week (06)
Month of the year (112)
Year (4 digits)

Example
28
7
12
20
4
1
2000

179

yday
weekday
month
0

Day of year (0365)


Day of the week (name)
Month of the year (name)
Timestamp

19
Thursday
January
948370048

Example: Acquiring date information with getdate()


<?php
$date_array = getdate(); // no argument passed so today's date will be used
foreach ($date_array as $key => $val)
echo "$key = $val <br>";
?>
<hr>
<?php
echo "Today's date: ".$date_array['mon']."/".$date_array['mday']."/".$date_array['year'];
?>
The output is:
seconds = 53
minutes = 26
hours = 11
mday = 29
wday = 2
mon = 11
year = 2011
yday = 332
weekday = Tuesday
month = November
0 = 1322555213
Today's date: 11/29/2011
The main method to format a timestamp is using date($format...$formatn[, $timestamp]). You pass a
series of codes indicating your formatting preferences, plus an optional timestamp. For instance:
date(Y-m-d); //year-month-date
The formatting characters are listed in the table below:
Format
Description
a
am or pm (lowercase)
A
AM or PM (uppercase)
d
Day of month (number with leading zeroes)
D
Day of week (three letters)
F
Month name
h
Hour (12-hour formatleading zeroes)
H
Hour (24-hour formatleading zeroes)
g
Hour (12-hour formatno leading zeroes)
G
Hour (24-hour formatno leading zeroes)

180

Example
pm
PM
20
Thu
January
12
12
12
12

i
j
l
L
m
M
n
s
S
r

Minutes
Day of the month (no leading zeroes)
Day of the week (name)
Leap year (1 for yes, 0 for no)
Month of year (numberleading zeroes)
Month of year (three letters)
Month of year (numberno leading zeroes)
Seconds of hour
Ordinal suffix for the day of the month
Full date standardized to RFC 822

U
y
Y
z
Z

Timestamp
Year (two digits)
Year (four digits)
Day of year (0365)
Offset in seconds from GMT

47
20
Thursday
1
09
Sep
9
24
th
Mon, 15 Sep 2003
08:25:55 -0700
1063639555
00
2003
257
0

Example:
<html>
<head>
<title>Formatting a date with date()</title>
</head>
<body>
<?php
$time = time(); //stores the exact timestamp to use in this script
echo date("m/d/y G.i:s", $time);
echo "<br> Today is ";
echo date("j \of F Y, \a\\t g.i a", $time);
?>
</body>
</html>
Output:
11/29/11 11.26:53
Today is 29 of November 2011, at 11.26 am
You can get information about the current time, but you cannot yet work with arbitrary dates. mktime()
returns a timestamp that you can then use with date() or getdate(). mktime() accepts up to six integer
arguments in the following order: Hour, Minute, Seconds, Month, Day of month, Year. The format is
$importantDate = mktime(hour, minute, seconds, month, date, year);
For example, you would store the date January 15, 2003, by using the following statement:
$birthdate = mktime(0, 0, 0, 1, 15, 2010);

181

Example:
<?php
// make a timestamp for Aug 23 2003 at 4.15 am
$ts = mktime(4, 15, 0, 8, 23, 2003);
echo date("m/d/y G.i:s", $ts);
echo "<br>";
echo "The date is ";
echo date("j of F Y, \a\\t g.i a", $ts );
?>
Output:
08/23/03 4.15:00

The date is 23 of August 2003, at 4.15 am


You might need to accept date information from user input. Before you work with a user-entered date
or store it in a database, you should check that the date is valid. This can be done using checkdate() that
accepts three integers: month, day, and year. checkdate() returns true if the month is between 1 and 12,
the day is acceptable for the given month and year (accounting for leap years), and the year is between
0 and 32767.
Be careful, though a date might be valid, it may not be acceptable to other date functions. For example,
the following line returns true:
checkdate(4, 4, 1066);
If you were to attempt to build a date with mktime() using these values, you'd end up with a timestamp
of -1. As a rule of thumb, don't use mktime() with years before 1902, and be cautious of using date
functions with any date before 1970, as negative numbers are not valid dates. Because the epoch began
January 1, 1970, anything before that is an invalid (negative) timestamp.

Practice 6.7
1. Write a program that accepts comments from users using HTML form and save it in a file on the
server.
2. Write a program that reads contents of a file and display in your web page.
3. Write a program that declares a class called car that has car related attributes like speed,
consumption, etc. It should also have a method called calculatePetrolLeft() that calculates the
amount petrol left after driving for hours. This depends on consumption pers second which is
constatnt. Also add a method called timeTaken() that calculates how long it would take to drive
the given distance in kilometers. e.g. how long to cover 330Km distance given contant speed.

182

3.3 Cookies and Sessions


3.3.1 Cookies
A cookie is a small amount of data stored by the user's browser in compliance with a request from a
server or script. A host can request that up to 20 cookies be stored by a user's browser. Each cookie
consists of a name, value, and expiry date, as well as host and path information. An individual cookie is
limited to 4KB.
After a cookie is set, only the originating host can read the data, ensuring that the user's privacy is
respected. Furthermore, the user can configure the browser to notify him/her of all cookies set, or even
to refuse all cookie requests. For this reason, cookies should be used in moderation and should not be
relied on as an essential element of an environment design without first warning the user
You can store information in cookies and then retrieve it. You store cookies by using the setcookie
function. The general format is as follows:
setcookie(variable, value);
The variable is the variable name, but you do not include the dollar sign ($).This statement stores the
information only until the user leaves your Web site.
For example, the following statement stores the pair city=Jimma in the cookie file on the users
computer:
setcookie(city, Jimma);
When the user moves to the next page, the cookie information is available in the built-in array called
$_COOKIE. The next Web page can display the information from the cookie by using the following
statement.
echo Your home city is .$_COOKIE[city];
The output from this statement is as follows:
Your home city is Jimma
Setting expiration dates
If you want the information stored in a cookie to remain in a file on the users computer after the user
leaves your Web site, set your cookie with an expiration time, as follows:
setcookie(variable,value,expiretime);
The expiretime value sets the time when the cookie expires. The value for expiretime is usually set by
using either the time or mktime function as follows:
time: This function returns the current time in a format the computer can understand. You use
the time function plus a number of seconds to set the expiration time of the cookie, as shown in
the following statements:
setcookie(state,CA,time()+3600); #expires in one hour

183

setcookie(Name,$Name,time()+(3*86400)) #expires 3 days

mktime: This function returns a date and time in a format that the computer can understand.
You must provide the desired date and time in the following order: hour, minute, second,
month, day, and year. If any value is not included, the current value is used. You use the mktime
function to set the expiration time of the cookie
This is shown in the following statements:
setcookie(state,CA,mktime(3,0,0,4,1,2003)); #expires at 3:00 AM on April 1, 2003
setcookie(state,CA,mktime(13,0,0,,,)); #expires at 1:00 PM today

Deleting a Cookie
Officially, to delete a cookie, you should call setcookie() with the name argument only:
setcookie("vegetable");
This approach does not always work well, and hence should not be relied on.
It is safest to set the cookie with a date you are sure has already expired:
setcookie("vegetable", "", time()-60);

3.3.2 Session
A session is the time that a user spends at your Web site. Users may view many Web pages between the
time they enter your site and leave it. Often you want information to be available for a complete
session. Beginning with version 4.0, PHP provides a way to do this.
Understanding how PHP sessions work PHP allows you to set up a session and store session variables.
After you create a session, the session variables are available for your use on any other Web page. To
make session information available, PHP does the following:
1. PHP assigns a session ID number.
The number is a really long nonsense number that is unique for the user and that no one could
possibly guess. The session ID is stored in a PHP system variable named PHPSESSID.
2. PHP stores the variables that you want saved for the session in a file on the server.
The file is named with the session ID number. Its stored in a directory specified by
session.save_path in the php.ini file. The session directory must exist before session files can be
saved in it.
3. PHP passes the session ID number to every page.
If the user has cookies turned on, PHP passes the session ID by using cookies. If the user has cookies
turned off, PHP behavior depends on whether trans-sid is turned on in php.ini.
4. PHP gets the variables from the session file for each new session page.
Whenever a user opens a new page that is part of the session, PHP gets the variables from the file
by using the session ID number that was passed from the previous page. The variables are available
in the $_SESSION array.

184

Opening and closing sessions


You should open a session at the beginning of each Web page. Open the session with the session_start
function, as follows:
session_start();
The function first checks for an existing session ID number. If it finds one, it sets up the session variables.
If it doesnt find one, it starts a new session by creating a new session ID number.
Because sessions use cookies, if the user has them turned on, session_start is subject to the same
limitation as cookies. That is, to avoid an error, the session_start function must be called before any
output is sent. This means that it is must be the first line code in your program.
You may want to restrict your site to users with a valid user ID and password. For restricted sessions that
users log into, you often want users to log out when theyre finished. To close a session, use the
following statement wherever to want to close the session:
session_destroy();
Using PHP session variables
To save a variable in a session so that its available on later Web pages, store the value in the $_SESSION
array, as follows:
$_SESSION[varname] = John Smith;
When you open a session on any subsequent Web page, the values stored in the $_SESSION array are
available.
If you want to stop storing any variable at any time, you can unset the variable by using the following
statement:
unset($_SESSION[varname]);
The following two scripts show how to use sessions to pass information from one page to the next.
<?php
/* Script name: sessionTest1.php
* Description: Starts a session. Saves a session variable.
*/
session_start();
$_SESSION[fullName] = David John Antony;
?>
<html>
<head><title>Testing Sessions page 1</title></head>
<body>
<p>This is a test of the sessions feature.
<form action=sessionTest2.php method=POST>

185

<input type=text name=form_var value=testing>


<input type=submit value=Go to Next Page>
</form>
</body>
</html>
In this script, a session is started and one session variable called fullName is stored. A form is also
displayed with one text field where the user can enter some text. When the submit button from this
form, labeled Go to Next Page is clicked, the sessionTest2.php script runs.
<?php
/* Script name: sessionTest2.php
* Description: Gets a variable from an existing session.
*/
session_start();
?>
<html>
<head><title>Testing Sessions page 2</title></head>
<body>
<?php
$session_var = $_SESSION[fullName];
$form_var = $_POST[form_var];
echo session_var = $session_var<br>\n;
echo form_var = $form_var<br>\n;
?>
</body>
</html>
output:
session_var = David John Antony;
form_var = testing

Mathematical Functions
PHP has built-in mathematical constants, and trigonometric, logarithmic, and base conversion functions.
PHP constants are:
Constant
M_PI
M_PI_2
M_PI_4
M_1_PI
M_2_PI
M_2_SQRTPI

Description
Pi
pi/2
pi/4
1/pi
2/pi
2/sqrt(pi)

Constant
M_SQRT2
M_SQRT1_2
M_LOG2E
M_LOG10E
M_LN2
M_LN10

186

Description
sqrt(2)
1/sqrt(2)
log2(e)
log10(e)
loge(2)
loge(10)

M_E

the constant e

Some of mathematical PHP functions are the following:


Function Behavior
pow()
Takes two numerical arguments and returns the first argument raised to the power of the
second. The value of pow($x, $y) is xy.
exp()
Takes a single argument and raises e to that power. The value of exp($x) is ex.
log()
The natural log function. Takes a single argument and returns its base e logarithm. If ey =
x, then the value of log($x) is y.
log10()
Takes a single argument and returns its base-10 logarithm. If 10y = x, then the value of
log10($x) is y.
pi()
Takes no arguments and returns an approximation of pi (3.1415926535898). Can be used
interchangeably with the constant M_PI.
Sin()
Takes a numerical argument in radians and returns the sine of the argument as a double.
Cos()
Takes a numerical argument in radians and returns the cosine of the argument as a
double.
Tan()
Takes a numerical argument in radians and returns the tangent of the argument as a
double.
Asin()
Takes a numerical argument and returns the arcsine of the argument in radians. Inputs must
be between 1.0 and 1.0 [inputs outside that range will return a result of NAN (for not a
number)]. Results are in the range pi / 2 to pi / 2.
Acos()
Takes a numerical argument and returns the arccosine of the argument in radians. Inputs
must be between 1.0 and 1.0 [inputs outside that range will return a result of NAN (for
not a number)]. Results are in the range 0 to pi.
Atan()
Takes a numerical argument and returns the arctangent of the argument in radians.
Results are in the range pi / 2 to pi / 2.
Atan2()
A variant of atan() that takes two arguments. Atan($y, $x) is identical to atan($y/$x) when
$x is positive, but the quadrant of atan2s result depends on the signs of both $y and $x.
Range of the result is from pi to pi.
Base conversion functions are also there:
Function
Behavior
BinDec()
Takes a single string argument representing a binary (base 2) integer, and returns a
string representation of that number in base 10.
DecBin()
Like BinDec(), but converts from base 10 to base 2.
OctDec()
Like BinDec(), but converts from base 8 to base 10.
DecOct()
Like BinDec(), but converts from base 10 to base 8.
HexDec()
Like BinDec(), but converts from base 16 to base 10.
DecHex()
Like BinDec(), but converts from base 10 to base 16.
base_convert() Takes a string argument (the integer to be converted) and two integer arguments (the
original base, and the desired base). Returns a string representing the converted

187

numberdigits higher than 9 (from 10 to 35) are represented by the letters az. Both
the original and desired bases must be in the range 236.
Example:
function display_bases($val, $first_base)
{
for ($new_base = 2; $new_base <= 9; $new_base++)
{
$converted = base_convert($val, $first_base, $new_base);
print($val in base $first_base is $converted in base $new_base<BR>);
}
}
display_bases(150, 10);
Output:
150 in base 10 is 10010110 in base 2
150 in base 10 is 12120 in base 3
150 in base 10 is 2112 in base 4
150 in base 10 is 1100 in base 5
150 in base 10 is 410 in base 6
150 in base 10 is 303 in base 7
150 in base 10 is 226 in base 8
150 in base 10 is 176 in base 9
floor(), ceil(), and round() convert doubles to integers, min() and max() take the minimum and maximum
of their numerical arguments, and abs() is the absolute value function.

Practice 6.8
1. Write a PHP code that uses session to store the persons who logged into your web page. It
should store user name and password of the person logged in.
2. Can you handle log out? It is done by removing the session. Allow users to log out.

188

Unit Seven: Advanced Internet Programming


7.1 Java Applets
An applet is just a Java class that runs in a Web Browser. An applet is a special kind of Java program that
a browser enabled with Java technology can download from the internet and run. An applet is typically
embedded inside a web-page and runs in the context of the browser.
An applet must be a subclass of the java.applet.Applet class, which provides the standard interface
between the applet and the browser environment. Swing provides a special subclass of Applet, called
javax.swing.JApplet, which should be used for all applets that use Swing components to construct their
GUIs.
Applets inherit a great deal of functionality from the Applet or JApplet class, including abilities to
communicate with the browser and present a graphical user interface (GUI) to the user. An applet which
will be using GUI components from Swing GUI should extend the javax.swing.JApplet base class, which
provides the best integration with Swing's GUI facilities.
The syntax of defining Java applet is as follows:
import java.applet.*;
public class classname extends Applet
{
//variables
//methods
}
If you use swing GUI components, it should extend JApplet instead of just Applet:
import javax.swing.JApplet.*;
public class Hclassname extends JApplet
{
//variables
//methods
}
Since applets are downloaded from the internet, by default they have to run in a restricted security
environment, called the "sandbox", to ensure they don't perform any destructive operations on the
user's computer, such as reading/writing to the filesystem.
The predominant difference between a Java applet and a Java application is that an applet runs in the
context of a web browser, being typically embedded within an html page, while a Java application runs
standalone, outside the browser. Thus, applets are particularly well suited for providing functions in a
web page which require more interactivity or animation than HTML can provide, such as a graphical
game, complex editing, or interactive data visualization. The end user is able to access the functionality
without leaving the browser.

189

Adding Applet to HTML


The APPLET tag is used to include an applet an HTML document. The newer OBJECT tag also works for
APPLET. Web browsers allow many applets on a single page. The syntax for the standard APPLET tag is
shown here. Bracketed items are optional.
< APPLET [CODEBASE = URL] CODE = appletFile [ALT = alternateText] [NAME = appletName] WIDTH =
pixels HEIGHT = pixels [ALIGN = alignment] [VSPACE = pixels] [HSPACE = pixels] >
[< PARAM NAME = AttributeName VALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
...
[HTML Displayed in the absence of Java]
</APPLET>
CODEBASE - CODEBASE is an optional attribute that specifies the base URL of the applet code, which is
the directory that will be searched for the applets executable class file specified by the CODE tag. The
HTML documents URL directory is used as the CODEBASE if this attribute is not specified. The
CODEBASE does not have to be on the host from which the HTML document was read.
CODE - CODE is a required attribute that gives the name of the file containing your applets compiled
.class file. This file is relative to the code base URL of the applet, which is the directory that the HTML
file was in or the directory indicated by CODEBASE if set.
ALT - The ALT attribute is used to specify a short text message that should be displayed if the browser
understands the APPLET tag but cant currently run Java applets. This is distinct from the alternate HTML
you provide for browsers that dont support applets.
NAME - NAME is an optional attribute used to specify a name for the applet instance. Applets must be
named in order for other applets on the same page to find them by name and communicate with them.
To obtain an applet by name, use getApplet( ), which is defined by the AppletContext interface.
WIDTH and HEIGHT - WIDTH and HEIGHT are required attributes that give the size (in pixels) of the
applet display area.
ALIGN - ALIGN is an optional attribute that specifies the alignment of the applet. This attribute is treated
the same as the HTML IMG tag with these possible values: LEFT, RIGHT, TOP, BOTTOM, MIDDLE,
BASELINE, TEXTTOP, ABSMIDDLE, and ABSBOTTOM.
VSPACE and HSPACE - These attributes are optional. VSPACE specifies the space, in pixels, above and
below the applet. HSPACE specifies the space, in pixels, on each side of the applet. Theyre treated the
same as the IMG tags VSPACE and HSPACE attributes.
PARAM NAME and VALUE - The PARAM tag allows you to specify appletspecific arguments in an HTML
page. Applets access their attributes with the getParameter( ) method.
Example:
<applet code="Sample.class" width=200 height=40>
If you were driving a Java powered browser, you'd see &quote;A Sample Applet&quote;

190

here.
</applet>

Passing Parameters to Applets


The APPLET tag in HTML allows you to pass parameters to your applet. To retrieve a parameter, use the
getParameter( ) method. It returns the value of the specified parameter in the form of a String object.
Thus, for numeric and Boolean values, you will need to convert their string representations into their
internal formats.
This is done using <param> tag which has the following structure:
<param name=parametername value=parametervalue>

Here is an example that demonstrates passing parameters:


<applet code="ParamDemo" width=300 height=80>
<param name=fontName value=Courier>
<param name=fontSize value=14>
<param name=leading value=2>
<param name=accountEnabled value=true>
</applet>
Example:
import java.awt.*;
import java.applet.*;
public class ParamDemo extends Applet
{
String fontName;
int fontSize;
float leading;
boolean active;
public void start() {
String param;
fontName = getParameter("fontName");
if(fontName == null)
fontName = "Not Found";
param = getParameter("fontSize");
try
{
if(param != null) // if not found
fontSize = Integer.parseInt(param);
else
fontSize = 0;
}
catch(NumberFormatException e) { fontSize = -1; }
param = getParameter("leading");
try
{

191

if(param != null) // if not found


leading = Float.valueOf(param).floatValue();
else
leading = 0;
}
catch(NumberFormatException e) { leading = -1; }
param = getParameter("accountEnabled");
if(param != null)
active = Boolean.valueOf(param).booleanValue();
}
//Display parameters.
public void paint(Graphics g)
{
g.drawString("Font name: " + fontName, 0, 10);
g.drawString("Font size: " + fontSize, 0, 26);
g.drawString("Leading: " + leading, 0, 42);
g.drawString("Account Active: " + active, 0, 58);
}
}

Life Cycle of Applet


When a Java Applet fires up in a Web Browser, it automatically looks to execute three methods in this
order:
init()
start()
paint
When an applet is terminated, the following sequence of method calls takes place:
stop( )
destroy( )
The init( ) method is the first method to be called. This is where you should initialize variables. This
method is called only once during the run time of your applet.
The start( ) method is called after init( ). It is also called to restart an applet after it has been stopped.
Whereas init( ) is called once the first time an applet is loaded start( ) is called each time an applets
HTML document is displayed onscreen. So, if a user leaves a web page and comes back, when the user of
the browser returns to the HTML page on which the applet resides, the applet resumes execution at
start( ).
The paint( ) method is called each time your applets output must be redrawn. This situation can occur
for several reasons. For example, the window in which the applet is running may be overwritten by
another window and then uncovered. Or the applet window may be minimized and then restored.
paint() is also called when the applet begins execution. Whatever the cause, whenever the applet must
redraw its output, paint( ) is called.

192

The paint() method is called after the init method has completed and after the start() method has begun
most importantly, code in the paint() method is guaranteed to run each time the window needs to be
re-drawn i.e. after the browser has been minimized, covered, the HTML page has changed, etc.
The paint( ) method has one parameter of type Graphics. This parameter will contain the graphics
context, which describes the graphics environment in which the applet is running. This context is used
whenever output to the applet is required.
The structure of paint method is:
public void paint(Graphics g)
{
//code
}
The code in the paint() method is used to draw the window that will be displayed in the Web Browser. To
do that we use the drawString() method of the Graphics object, supplying the text that we wish to
appear in the window and it's dimensions.
g.drawString("I love Java", 20, 20);
The stop( ) method is called when a web browser leaves the HTML document containing the applet
when it goes to another page, for example. When stop( ) is called, the applet is probably running. You
should use stop( ) to suspend threads that dont need to run when the applet is not visible. You can
restart them when start( ) is called if the user returns to the page.
The destroy( ) method is called when the environment determines that your applet needs to be
removed completely from memory. At this point, you should free up any resources the applet may be
using. The stop( ) method is always called before destroy( ).
// An Applet skeleton.
import java.awt.*;
import java.applet.*;
public class AppletSkel extends Applet
{
public void init() {
// initialization
}
public void start() {
// start or resume execution
}
public void stop() {
// suspends execution
}
public void destroy() {
// perform shutdown activities
}
public void paint(Graphics g) {
// redisplay contents of window

193

}
}
Example: A simple applet that sets the foreground and background colors and outputs a string
import java.awt.*;
import java.applet.*;
public class Sample extends Applet
{
String msg;
//set the foreground and background colors.
public void init()
{
setBackground(Color.cyan);
setForeground(Color.red);
msg = "Inside init( ) --";
}
// Initialize the string to be displayed.
public void start()
{
msg += " Inside start( ) --";
}
// Display msg in applet window.
public void paint(Graphics g)
{
msg += " Inside paint( ).";
g.drawString(msg, 10, 30);
}
}

The Graphics Class


The paint method has graphics class as its parameter. The graphics class has many methods to draw
graphics of different type:
void drawString(String message, int x, int y)
void setBackground(Color newColor)
void setForeground(Color newColor)
Color can be specified as follows:
Color.black
Color.magenta
Color.blue
Color.orange
Color.cyan

Color.pink
Color.darkGray
Color.red
Color.gray
Color.white

Color.green
Color.yellow
Color.lightGray

There are many more methods in Graphics classs of the paint() method:
void drawArc(int x, int y, int width, int height, int degreesstart,int degreesend)

194

boolean drawImage(Image img, int x, int y, ImageObserver io)


void drawLine(int x0, int y0, int x1, int y1)
void drawOval(int x, int y, int width, int height)
void drawPolygon(int x[], int y[], int n)
void drawPolyline(int x[], int y[], int n)
void drawRect(int x, int y, int width, int height)
void drawString(String str, int x, int y)
void fillArc(int x, int y, int width, int height, int degreesstart, int degreesend)
void fillOval(int x ,int y, int width, int height)
void fillPolygon(int x[], int y[], int n)
void fillRect(int x, int y, int width, int height)
FontMetrics getFontMetrics()
void setColor(Color c)
void setFont(Font f)
Color getColor()
Font getFont()
Example: an applet that draws some geometric shapes
import java.awt.*;
import java.applet.*;
public class DrawExample extends Applet
{
Font bigFont; //the font variable
//the colors you will use
Color redColor;
Color weirdColor;
Color bgColor;
public void init()
{
bigFont = new Font("Arial",Font.BOLD,16);
redColor = Color.red; // Standard colors can be named like this
weirdColor = new Color(60, 60,122); // lesser known colors can be made with RGB.
bgColor = Color.blue;
setBackground(bgColor); //this will set the backgroundcolor of the applet
}
public void stop()
{
}
// now lets draw things on screen
public void paint(Graphics g)
{
g.setFont(bigFont); // tell g to use your font
g.drawString("Shapes and Colors",80,20);
g.setColor(redColor); // Now we tell g to change the color
g.drawRect(100,100,100,100); // This will draw a rectangle (xco,yco,xwidth,height);

195

g.fillRect(110,110,80,80); // This will fill a rectangle


g.setColor(weirdColor);
g.fillArc(120, 120, 60, 60, 0, 90);
g.setColor(Color.yellow);
g.drawLine(140,140,160,160); // Draw a line (int x1, int y1, int x2, int y2)
g.drawOval(120, 120, 60, 60); //ovals are also possible this way.
// reset the color to the standard color for the next time the applets paints
g.setColor(Color.black);
}
}
To include this in your HTML, you can do something like this:
<html>
<head>
<title>Java Applets</title>
</head>
<body>
Applet can draw different geometric shapes. <br>
<applet code="DrawImage.class" width=300 height=100 vspace=10 >
</applet>
</body>
</html>

Creating GUI
GUI can be created in two different ways: using AWT or swing. Swing is the latest technology in Java GUI
development and is recommended than AWT.
Swing supplies the following UI components (the class that implements each component is listed in
parentheses):
Buttons (javax.swing.JButton)
Checkboxes (javax.swing.JCheckBox)
Single-line text fields (javax.swing.JTextField)
Larger text display and editing areas (javax.swing.JTextArea)
Labels (javax.swing.JLabel)
Lists (javax.swing.JList)
Pop-ups (javax.swing.Popup)
Scrollbars (javax.swing.JScrollBar)
Sliders (javax.swing.JSlider)
Drawing areas (java.awt.Canvas)
Menus (javax.swing.JMenu,javax.swing.JMenuBar javax.swing.JMenuItem,
javax.swing.JCheckBoxMenuItem)
Containers (javax.swing.JPanel, javax.swing.JWindow and its subclasses)

196

GUI components are built as objects in Java. Hence, to create instance of them, we use the new
keyword. To include GUI components in applet, you have to define them first, then instantiate with new
keyword, and finally add to applet.
For example, button can be created like this:
JButton bok; //define Button
bok = new Jbutton(); //instantitate button
add(bok); //add button to Applet
For text boxes:
JTextField tname = new JTextField(15);
add(tname);
GUI components have properties and methods through which you can control and use them. For
example, a JTextField has getText() and setText() methods to read content of the text box, or set the
content.
Because the JApplet class inherits from the AWT Container class, it's easy to add components to applets
and to use layout managers to control the components' onscreen positions. Here are some of the
Container methods an applet can use:
add(componentname) - Adds the specified Component to applet.
remove(componentname) - Removes the specified Component.
setLayout(layoutname) - Sets the layout manager.
Example: a simple applet GUI
import javax.swing.*;
import java.applet.*;
public class SwingGUIExample extends JApplet
{
JButton okButton;
// A Button to click
JTextField nameField;
// A textField to get text input
ButtonGroup radioGroup; //A group of radio buttons
JRadioButton radio1;
JRadioButton radio2;
JCheckBox option;
//An independant check box
public void init()
{
setLayout(null);
//Tell the applet not to use a layout manager.
okButton = new JButton("A button");
//initialze the button and give it a text.
nameField = new JTextField("A TextField", 100); //text and length of the field
radioGroup = new ButtonGroup();
//initialize the radio buttons group
radio1 = new JRadioButton("Happy", true);

197

radio2 = new JRadioButton("Sad", false);


radioGroup.add(radio1);
radioGroup.add(radio2);
option = new JCheckBox("Option", false);

//Label and state of the checkbox

//Specify position of GUI components by specifying the x and y coordinate and width and height.
okButton.setBounds(20,
Bounds(20, 20, 100, 30);
nameField.setBounds(20, 70, 100, 40);
radio1.setBounds(20, 120, 100, 30);
radio2.setBounds(140, 120,100, 30);
option.setBounds(20, 170, 100, 30);
add(okButton);
add(nameField);
add(radio1);
add(radio2);
add(option);
}
}
This produces a GUI that looks like the following:

Example: a program that accepts two numbers and adds them together when button is clicked
import javax.swing.JApplet.*;
import javax.swing.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Adder extends Applet implements ActionListener
{
JButton add, clear;
JTextField fnum, snum, result;
JLabel first, second, third;
double outcome = 0;

198

public void init()


{
makeGUI();
}
public void makeGUI()
{
add = new JButton("Add");
clear = new JButton("Clear");
fnum = new JTextField(10);
snum = new JTextField(10);
result = new JTextField(10);
first = new JLabel("First number", JLabel.RIGHT);
second = new JLabel("Second number", JLabel.RIGHT);
third = new JLabel("Result", JLabel.RIGHT);
add.addActionListener(this);
clear.addActionListener(this);
setLayout(new GridLayout(0, 2));
add(first);
add(fnum);
add(second);
add(snum);
add(third);
add(result);
add(add);
add(clear);
}
public void actionPerformed(ActionEvent ev) //handles button click event
{
if(ev.getSource()==add)
{
outcome = Double.parseDouble(fnum.getText()) + Double.parseDouble(snum.getText());
result.setText("" + outcome);
}
else if(ev.getSource() == clear)
{
fnum.setText("");
snum.setText("");
result.setText("");
}
}
}
The HTML that contains the above number Adder GUI is as follows:
<html>
<head>

199

<title>Photo Album in Java Applets </title>


</head>
<body>
Enjoy our photo album. <br>
<applet code="Adder.class" width=300 height=200> </applet>
</body>
</html>

Loading and Drawing Images


The typical way to load images in Applets is via the getImage() method.
Image getImage(URL) // Absolute URL
Image getImage(URL, String) // Relative URL
Example:
Image img = getImage("test.gif");
There are two methods that return the path of the image, sound, etc you are opening.
URL getCodeBase( ) - Returns the URL associated with the invoking applet.
URL getDocumentBase( ) - Returns the URL of the HTML document that invokes the applet.
Example
Image img = getImage(getDocumentBase(), "test.gif");
After the image is loaded, you would typically render it to the screen in the Applet's paint method using
the Graphics method.
Example:
g.drawImage(img, 0, 0, this); // img is the image that is drawn on the screen in the 0, 0 position.
Example: an applet that loads and draws an image
import java.awt.*;
import java.applet.*;
public class LoadImage extends Applet
{
Image img;
public void init() {
img = getImage(getDocumentBase(), "Test.gif");
}
public void paint(Graphics g) {
int x = (int)(Math.random() * size().width);
int y = (int)(Math.random() * size().height);
g.drawImage(img, x, y, this);
}
}

200

Using applet, you can create photo album that you can navigate through using buttons.
//file: PhotoAlbum.java
import java.awt.*;
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.*;
public class PhotoAlbum extends Applet implements ActionListener
{
//create buttons and picture display area
JButton previous = new JButton("Previous"), first = new JButton("First");
JButton last = new JButton("Last"), next = new JButton("Next");
Canvas imageCanvas = new Canvas();
final int total = 6;
int i = 0;

// total no of images
// this is value of currently displayed image

Image Pictures[] = new Image[total];


public void init()
{
makeGUI();
// get all the images
for (int p=0; p < total; p++)
{
Pictures[p] = getImage(getCodeBase(), "Photos/Image"+p+".JPG");
prepareImage(Pictures[p], this);
}
}
private void displayImage(int n)
{
// Display the nth image on the canvas
Graphics g = imageCanvas.getGraphics();
g.clearRect(10, 10, 700, 700);
g.drawImage(Pictures[n], 30, 10, this);
g.drawString("Image: "+(n+1)+"/"+total, 30, 500);
}
public void drawFirst()
{
displayImage(0);
}
public void drawLast()
{
displayImage(total-1);
}
public void drawPrevious()
{
i = i - 1;

201

if (i <= -1)
i = total - 1;
displayImage(i);
}
public void drawNext()
{
i = i + 1;
if (i == total)
i = 0;
displayImage(i);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == previous)
drawPrevious();
else if (e.getSource() == first)
drawFirst();
else if (e.getSource() == last)
drawLast();
else if (e.getSource() == next)
drawNext();
}
public void paint(Graphics g)
{
drawFirst();
i = 0;
}
private void makeGUI()
{
setBackground(Color.black);
setForeground(Color.white);
setLayout(new BorderLayout());
Panel p1 = new Panel();
p1.add(previous);
p1.add(first);
p1.add(next);
p1.add(last);
add(BorderLayout.NORTH, p1);
add(BorderLayout.CENTER, imageCanvas);
previous.addActionListener(this);
first.addActionListener(this);
last.addActionListener(this);
next.addActionListener(this);
}
}

202

The HTML that contains the above photo album applet is as follows:
<html>
<head>
<title>Photo Album in Java Applets </title>
</head>
<body>
Enjoy our photo album. <br>
<applet code="PhotoAlbum.class" width=600 height=500> </applet>
</body>
</html>

Playing Audio
AudioClip is an interface for playing audio file. It has methods that help you load and play audio files. To
load audio, we use getAudioClip() method.
AudioClip getAudioClip(URL url) - returns an AudioClip object that encapsulates the audio clip found at
the location specified by url.
The AudioClip interface has the following methods that enable you to control the play of the audio:
void loop(); //repeatedly plays the audio when it finishes
void play(); //palys the audio
void stop(); //stop playing audio
After you have loaded an audio clip using getAudioClip( ), you can use these methods to play it.
Example
AudioClip onceClip;
onceClip = applet.getAudioClip(getCodeBase(), "train.au");
onceClip.play(); //Play it once.
onceClip.stop(); //Stop the sound.
Since an applet that continues to make noise after you've left its page could be annoying, you can make
the applet stop playing the continuously looping sound when the user leaves the page, and resumes
playing it when the user comes back. It does this by implementing its stop and start methods as follows:
public void stop()
{
if (playing) {
onceClip.stop(); //stop the sound
}
}
public void start()
{

203

if (!playing) {
onceClip.play(); //play the sound
}
}
Example: an applet that plays sound/audio
//file: Player.java
import javax.swing.*;
import java.applet.*;
import java.awt.event.*;
public class Player extends Applet implements ActionListener
{
JButton play, stop, loop;
AudioClip mySong;
public void init()
{
play = new JButton("Play");
add(play);
play.addActionListener(this);
stop = new JButton("Stop");
add(stop);
stop.addActionListener(this);
loop = new JButton("Loop");
add(loop);
loop.addActionListener(this);
// Load the audio file
mySong = getAudioClip(getDocumentBase(), "Songs/song.au");
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == play)
mySong.play();
if (e.getSource() == stop)
mySong.stop();
if (e.getSource() == loop)
mySong.loop();
}
}
You can also play sound/audio using the paly method:
void play(URL url) - If an audio clip is found at the location specified by url, the clip is played.

204

void play(URL url, String clipName) - If an audio clip is found at the location specified by url with
the name specified by clipName, the clip is played.

7.2 The Extensible Markup Language(XML)


XML stands for the eXtensible Markup Language. It is a new markup language, developed by the W3C
(World Wide Web Consortium), mainly to overcome limitations in HTML. The W3C is the organization in
charge of the development and maintenance of most Web standards, most notably HTML.
XML exists because HTML was successful. Therefore, XML incorporates many successful features of
HTML. XML also exists because HTML could not live up to new demands. Therefore, XML breaks new
ground where it is appropriate.
However, XML is unlikely to replace HTML in the near or medium-term. XML does not threaten the Web
but introduces new possibilities. Work is already under way to combine XML and HTML in XHTML, an
XML version of HTML. It is expected that XHTML will soon be adopted by the W3C.
It is important to remember that, like HTML, XML is a Markup Language. What do we mean by markup
language? The term markup is used to identify anything put within a document which either adds or
provides special meaning (e.g., italicized text).
A markup language is the set of rules. It declares what constitutes markup in a document, and defines
exactly what the markup means. It also provides a description of document layout and logical structure.
There are three types of markup:
Stylistic: How a document is presented (e.g., the HTML tags <I> for italics, <B> for bold, and <U>
for underline)
Structural: How the document is to be structured (e.g., the HTML tags <P> for paragraph,
<SPAN> for creating ad hoc styles in a document, and <DIV> for grouping structures aligned in
the same way.
Semantic: Tells about the content of the data (e.g., the HTML tags <TITLE> for page title,
<HEAD> for page header information, and <SCRIPT>to indicate a JavaScript in a page)
In XML, the only type of markup that we are concerned with is structural.
The idea behind XML is deceptively simple. It aims at answering the conflicting demands that arrive at
the W3C for the future of HTML. On one hand, people need more tags. And these new tags are
increasingly specialized. For example, mathematicians want tags for formulas. Chemists also want tags
for formulas but they are not the same.
On the other hand, authors and developers want fewer tags. HTML is already so complex! As handheld
devices gain in popularity, the need for a simpler markup language also is apparent because small
devices, like the PalmPilot, are not powerful enough to process HMTL pages. How can you have both
more tags and fewer tags in a single language?
To resolve this dilemma, XML makes essentially two changes to HTML:
It predefines no tags.
It is stricter.

205

Because there are no predefined tags in XML, you, the author, can create the tags that you need. Do you
need a tag for price? Do you need a tag for a bold hyperlink that floats on the right side of the screen?
Then make them:
<price currency=usd>499.00</price>
<toc xlink:href=/newsletter>Pineapplesoft Link</toc>
HTML has a very forgiving syntax. This is great for authors who can be as lazy as they want, but it also
makes Web browsers more complex. According to some estimates, more than 50% of the code in a
browser handles errors or sloppiness on the authors part. Hence, it was decided that XML would adopt
a very strict syntax. A strict syntax results in smaller, faster, and lighter browsers.
When creating an XML document, you must begin with the XML declaration statement. This statement
alerts the browser or other processing tools that this document contains XML tags. The declaration looks
like this:
<?xml version=1.0?>
This is the first line of your document.

7.3 Java Server Page (JSP)


To understand JavaServer Pages, its necessary to understand their underlying technologyJava
servlets. Servlets are Java classes that extend the functionality of a Web server by dynamically
generating Web pages. A run-time environment known as a servlet engine manages servlet loading and
unloading, and works with the Web server to direct requests to servlets and to send output back to Web
clients.

Java Servlet
In the early days of the Web, a server could dynamically construct a page by creating a separate process
to handle each client request. The process would open connections to one or more databases in order
to obtain the necessary information. It communicated with the Web server via the Common Gateway
Interface (CGI).
CGI allowed the separate process to read data from the HTTP request and write data to the HTTP
response. However, CGI suffered serious performance problems. It was expensive in terms of processor
and memory resources to create a separate process for each client request. It was also expensive to
open and close database connections for each client request. In addition, the CGI programs were not
platform-independent. Therefore, other techniques were introduced, among these are servlets.
Servlets offer several advantages in comparison with CGI. First, performance is significantly better.
Servlets execute within the address space of a Web server. It is not necessary to create a separate
process to handle each client request. Second, servlets are platform-independent because they are
written in Java. A number of Web servers from different vendors offer the Servlet API. Programs

206

developed for this API can be moved to any of these environments without recompilation. Third, the
Java security manager on the server enforces a set of restrictions to protect the resources on a server.
Servlets are programs that run on a Web server or application server and act as a middle layer between
a request coming from a Web browser or other HTTP client and databases or applications on the HTTP
server.

The job of the servlet is to perform the following tasks:


1. Read the explicit data sent by the client.
The end user normally enters data in an HTML form on a Web page. However, the data could also come
from an applet or a custom HTTP client program.
2. Read the implicit HTTP request data sent by the browser.
There are really two varieties of data that goes from client to web server: the explicit data the end user
enters in a form and the behind-the-scenes HTTP information. Both types of data are critical to effective
development. The HTTP information includes cookies, media types and compression schemes the
browser understands, and so forth.
3. Generate the results.
This process may require talking to a database, executing an RMI or CORBA call, invoking a Web service,
or computing the response directly. Your real data may be in a relational database. But your database
probably doesnt speak HTTP or return results in HTML, so the Web browser cant talk directly to the
database. The same argument applies to most other applications. You need the Web middle layer to
extract the incoming data from the HTTP stream, talk to the application, and embed the results inside a
document.
4. Send the explicit data to the client.
This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images),
Excel, or even a compressed format like gzip that is layered on top of some other underlying format.
5. Send the implicit HTTP response data.
There are really two varieties of data sent from server to client: the document itself and the behind-thescenes HTTP information. Both types of data are critical to effective development. Sending HTTP

207

response data involves telling the browser or other client what type of document is being returned (e.g.,
HTML), setting cookies and caching parameters, and other such tasks.
Because servlets are written in the Java programming language, they have access to the full set of Java
APIs. This makes them ideal for implementing complex business application logic and especially for
accessing data in the enterprise. The Java Database Connectivity (JDBC) API, which allows Java programs
to access relational databases , is one example. Because there are no graphics associated with servlets,
access to the GUI Java APIs (the AWT) is not relevant.

Writing Servlets
The Java Servlet API is a set of classes that define a standard interface between a Web client and a Web
servlet. In essence, the API encases requests as objects so the server can pass them to the servlet; the
responses are similarly encapsulated so the server can pass them back to a client.
The Java Servlet API has two packages. javax.servlet contains classes to support generic protocolindependent servlets, and javax.servlet.http includes specific support for the HTTP protocol.
The Servlet interface class is the central abstraction of the Java Servlet API. This class defines the
methods that manage the servlet and its communications with clients.
To write an HTTP servlet for use on the Web, use the HttpServlet class.
A client request to a servlet is represented by an HttpServletRequest object. This object
encapsulates the communication from the client to the server. It can contain information about
the client environment and any data to be sent to the servlet from the client.

The response from the servlet back to the client is represented by an HttpServletResponse
object. This is often the dynamically generated response, such as an HTML page, and is built
with data from the request and from other sources accessed by the servlet.

Most servlets need access to at least three packages javax.servlet, javax.servlet.http, and java.io. As a
result, you usually start with these import statements:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Depending on what other processing your servlet does, you may need additional import statements.
Get request is made when you do not specify form submission METHOD or specifies METHOD="GET".
Servlets can also handle POST requests, which are generated when someone submits an HTML form that
specifies METHOD="POST". HTTP POST request is handled by doPost() method, whereas GET requests
are handled by doGet().
Example: Hello world servlet

208

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}
Both doGet and doPost take two arguments: an HttpServletRequest and an HttpServletResponse. The
HttpServletRequest lets you get all of the incoming data. This class has methods by which you can find
out about information such as form data, HTTP request headers, and the clients hostname. The
HttpServletResponse lets you specify outgoing information such as HTTP status codes and response
headers (Content-Type, Set-Cookie, etc.).
Most importantly, HttpServletResponse lets you obtain a PrintWriter that you use to send document
content back to the client. For simple servlets, most of the effort is spent in println statements that
generate the desired page.
Both doGet and doPost throw two exceptions: ServletException and IOException. Hence, you are
required to include them in the method declaration. You must import classes in java.io for PrintWriter,
javax.servlet for HttpServlet, and javax.servlet.http for HttpServletRequest and HttpServletResponse.

The Servlet Life Cycle


The servlet life cycle tells us how servlets are created and destroyed, and how and when the various
methods are invoked. Servlets follow a three-phase life: initialization, service, and destruction, with
initialization and destruction typically performed once, and service performed many times.

209

Fig servlet life cycle

I.

The init Method

Suppose you want to perform complex setup tasks when the servlet is first loaded, but not repeat those
tasks for each request. The init method is designed for this case; it is called when the servlet is first
created, and not called again for each user request. So, it is used for one-time initializations. The servlet
is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify
that the servlet be loaded when the server is first started.
When the servlet is first created, its init method is invoked, so init is where you put one-time setup code.
The init method definition looks like this:
public void init() throws ServletException
{
// Initialization code...
}

II.

The service Method

Each time the server receives a request for a servlet, the server spawns a new thread and calls service
method. The service method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls
doGet, doPost, doPut, doDelete, etc., as appropriate. A GET request results from a normal request for a
URL or from an HTML form that has no METHOD specified. A POST request results from an HTML form
that specifically lists POST as the METHOD. Other HTTP requests are generated only by custom clients.
Multiple concurrent requests normally result in multiple threads calling service simultaneously, although
your servlet can implement a special interface (SingleThreadModel) that stipulates that only a single
thread is permitted to run at any one time. The service method then calls doGet, doPost, or another
doXxx method, depending on the type of HTTP request it received.

210

void service( ServletRequest request, ServletResponse response) throws ServletException, IOException


{
//code for service
}

III.

The destroy Method

The destruction phase of the Servlet life cycle represents when a Servlet is being removed from use by a
container. The Servlet interface defines the destroy() method to correspond to the destruction life cycle
phase. Each time a Servlet is about to be removed from use, a container calls the destroy() method,
allowing the Servlet to gracefully terminate and tidy up any resources it might have created.
public void destroy()
{
//releasing resources
}
During initialization a Servlet loads everything it needs to use for servicing requests. The resources are
then readily used during the service phase and can then be cleaned up in the destruction phase.
The general skeleton of servlets looks like this:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Database extends HttpServlet
{
public void init()
{
//code for initialization
}
public void destroy()
{
//code for releasing resource
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
//process GET request
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
//process POST request

211

}
}

Http Servlet Request and Response


The Servlet API makes manipulating an HTTP request and response pair relatively simple through use of
the HttpServletRequest and HttpServletResponse objects. Both of these objects encapsulate a lot of
functionality.
I.
HttpServletResponse
The HttpServletResponse object is responsible for sending information back to a client. Sending back
custom content requires using either the getWriter() or getOutputStream() method to obtain an output
stream for writing content. These two methods return suitable objects for sending either text and binary
content to a client, respectively. Only one of the two methods may be used with a given
HttpServletResponse object. Attempting to call both methods causes an exception to be thrown.
With the HelloWorld Servlet example, the getWriter() method was used to get an output stream for
sending the HTML markup.
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hello World!</title>");
Using an instance of a PrintWriter object consists of providing a String object and calling either the
print(), println(), or write() methods.
The getOutputStream() method is used when more control is needed over what is sent to a client. The
returned OutputStream can be used for sending text, but is usually used for sending non-text-related
binary information such as images. The reason for this is because the getOutputStream() method
returns an instance of a javax.servlet.ServletOutputStream object, not a PrintWriter. The
ServletOutputStream object directly inherits from java.io.OutputStream and allows a developer to write
raw bytes. The PrintWriter objects lack this functionality because it always assumes you are writing text.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import com.sun.image.codec.jpeg.*;
public class DynamicImage extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)

212

throws ServletException, IOException


{
response.setContentType("image/jpeg");
// Create Image
int width = 200, height = 30;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D)image.getGraphics();
// Fill background
g.setColor(Color.gray);
g.fillRect(0, 0, width, height);
// Draw a string
g.setColor(Color.white);
g.setFont(new Font("Dialog", Font.PLAIN, 14));
g.drawString("http://www.jspbook.com",10,height/2+4);
// Draw a border
g.setColor(Color.black);
g.drawRect(0,0,width-1,height-1);
g.dispose();
// Send back image
ServletOutputStream sos = response.getOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
encoder.encode(image);
}
}
This is what you will see in the browser

II.

HttpServletRequest
213

A clients HTTP request is represented by an HttpServletRequest object. The HttpServletRequest object


is primarily used for getting request headers, parameters, and files or data sent by a client. However, the
Servlet specification enhances this object to also interact with a Web Application. Some of the most
helpful features include session management and forwarding of requests between Servlets.
Reading request headers from servlets can be done using HttpServletRequest object as follows:
CGI Variable
Servlet Equivalent
AUTH_TYPE

request.getAuthType()

CONTENT_LENGTH

request.getContentLength()

CONTENT_TYPE

request.getContentType()

DOCUMENT_ROOT

getServletContext().getRealPath("/")

HTTP_XXX_YYY

request.getHeader("Xxx-Yyy")

PATH_INFO

request.getPathInfo()

PATH_TRANSLATED

request.getPathTranslated()

QUERY_STRING

request.getQueryString()

REMOTE_ADDR

request.getRemoteAddr()

REMOTE_HOST

request.getRemoteHost()

REMOTE_USER

request.getRemoteUser()

REQUEST_METHOD

request.getMethod()

SCRIPT_NAME

request.getServletPath()

SERVER_NAME

request.getServerName()

SERVER_PORT

request.getServerPort()

SERVER_PROTOCOL

request.getProtocol()

SERVER_SOFTWARE

getServletContext().getServerInfo()

Example: a servlet that displays request information


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
/** Shows all the request headers sent on this request. */
public class ShowRequestHeaders extends HttpServlet
{

214

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Servlet Example: Showing Request Headers";
out.println(ServletUtilities.headWithTitle(title) +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" +
"<B>Request Method: </B>" + request.getMethod() + "<BR>\n" +
"<B>Request URI: </B>" + request.getRequestURI() + "<BR>\n" +
"<B>Request Protocol: </B>" + request.getProtocol() + "<BR><BR>\n" +
"\n</BODY></HTML>");
}
/* Let the same servlet handle both GET and POST. */
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response);
}
}
This produces the following output:

One of the nice features of servlets is that all the form data parsing is handled automatically. You simply
call the getParameter method of HttpServletRequest, supplying the parameter name as an argument.
You use getParameter exactly the same way when the data is sent by GET or by POST.
The servlet knows which request method was used and automatically does the right thing behind the
scenes. The return value is a String corresponding to the URL-decoded value of the first occurrence of
that parameter name. An empty String is returned if the parameter exists but has no value, and null is
returned if there is no such parameter in the request.
The general syntax is:
String request.getParameter(form input field name);

215

Parameter names are case sensitive. Hence, for example, request.getParameter("Param1") and
request.getParameter("param1") are not interchangeable.
Technically, it is legal for a single HTML form to use the same form element name twice, and in fact this
situation really occurs when you use SELECT elements that allow multiple selections. If the parameter
could potentially have more than one value, you should call getParameterValues which returns an array
of strings. The return value of getParameterValues is null for nonexistent parameter names and is a oneelement array when the parameter has only a single value.
Example: HTML form
<HTML>
<HEAD>
<TITLE>Adding Two Numbers</TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E6">
<H1 ALIGN="CENTER">Collecting Three Parameters</H1>
<FORM method=POST ACTION="/servlet/adder">
First number: <INPUT TYPE="TEXT" NAME="fnum"><BR>
Second number: <INPUT TYPE="TEXT" NAME="snum"><BR>
<CENTER><INPUT TYPE="SUBMIT"></CENTER>
</FORM>
</BODY>
</HTML>
// Simple servlet that reads two numbers from the form data.
package moreservlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ThreeParams extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading Three Request Parameters";
out.println(ServletUtilities.headWithTitle(title) +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" +

216

" <B>Number one</B>: " + request.getParameter("fnum") + "\n" +


" <B>Number two</B>: " + request.getParameter("snum") + "\n" +
" <B>Sum</B>: " + (Double.parseDouble(request.getParameter("fnum"))
Double.parseDouble(request.getParameter("snum"))) +
"</BODY></HTML>");

}
}

Methods for Processing HTTP Servlets


Your subclass of HttpServlet must override at least one method. Typically, servlets override the doGet or
doPost method to handle data submitted by GET method and POST method respectively. However, the
same servlet can handle both GET and POST by having doGet call doPost, or vice versa.
So, in servlets, the most commonly used methods include:
doGet, for HTTP GET requests
doPost, for HTTP POST requests
doPut, for HTTP PUT requests
doDelete, for HTTP DELETE requests
getServletInfo, which the servlet uses to provide information about itself
The HttpServlet objects implementation of the service()method, which is called during each service
request, calls one of seven different helper methods.These seven methods correspond directly to the
seven HTTP methods and are named as follows: doGet(), doPost(), doPut(), doHead(), doOptions(),
doDelete(), and doTrace(). The appropriate helper method is invoked to match the type of method on a
given HTTP request.

217

doGet is called by the server to allow a servlet to handle a GET request; doPost to handle a POST
request. The service method receives standard HTTP requests from the public service method and
dispatches them to the doXXX methods defined in the class.
doGet() method is called by the servlet engine to process an HTTP GET request. Input parameters, HTTP
headers, and the input data (if any) can be obtained from the request object, and response headers and
the output stream from the response object.
void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {}
doPost() method is called by the servlet engine to process an HTTP POST request. No different from
doGet() from the standpoint of obtaining parameters and input data or returning the response.
void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
doPut() method is called by the servlet engine to process an HTTP PUT request. The request URI in this
case indicates the destination of the file being uploaded.
void doPut(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
doPut() is called by the servlet engine to process an HTTP PUT request. The request URI in this case
indicates the destination of the file being uploaded.
void doPut(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
doDelete() is called by the servlet engine to process an HTTP DELETE request. The request URI indicates
the resource to be deleted.
void doDelete(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
Example: handling HTTP POST requests
<html>
<body>
<center>
<form name="colorchoice" method="post" action=" ColorPostServlet">
<B>Color:</B>
<select name="color" size="1">

218

<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
Servlet to process color choice by user
//file: ColorPostServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}

Accessing Database
Before you can use JDBC to access a database, you must first establish a connection to the database. The
first step to establishing a connection involves registering the driver class so the class is available. To do
that, you use the forName method of the Class class, specifying the package and class name of the
driver.
For example, to register the MySQL connector, use this statement:
Class.forName(com.mysql.jdbc.Driver);
To register the standard ODBC driver, use this statement instead:
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);

219

Note that the forName method throws ClassNotFoundException, so you have to enclose this statement
in a try/catch block that catches ClassNotFoundException.
For a JDBC driver to be used, it must first be registered with the driver manager. You can accomplish this
in several ways, but each involves calling DriverManager.registerDriver(). The most common approach
is simply to load the driver class:
try {
Class.forName("MyJdbcDriver");
}
catch (ClassNotFoundException e) {
// Report the exception
}
A driver class loaded in this fashion should create an instance of itself and register it with the driver
manager.
To use the JDBC-ODBC bridge in a Java application, a suitable ODBC data source must be configured. The
data source should be configured as a System DSN, not a User DSN. The driver class name is
sun.jdbc.odbc.JdbcOdbcDriver if the Sun JVM is being used.
The database URL used in the getConnection() statement is jdbc:odbc:dsn, where dsn is the data source
name. Microsoft supplies ODBC drivers for its Access database product, as well as dBase, Excel, FoxPro,
and a number of others, including a text driver that can use ordinary text files (.txt and .csv) as a simple
database system.

Connecting to a Database
After you register the driver class, you can call the static getConnection method of the DriverManager
class to open the connection. This method takes three String parameters: the database URL, the user
name, and a password.
Heres an example:
String url = jdbc:mysql://localhost:3306/teaching;
String user = root;
String pw = pw;
con = DriverManager.getConnection(url, user, pw);
DriverManager provides three different methods to get connection:
DriverManager.getConnection(String url)
DriverManager.getConnection(String url, String userID, String password)
DriverManager.getConnection(String url, Properties prop)
Internally, DriverManager uses the same private worker method to handle each of these methods. The
driver manager maintains a list of registered drivers. When its getConnection() method is invoked, it
interrogates each driver in turn to see if it will accept the specified URL. The driver manager does this by
calling the drivers connect() method, which returns either null if the driver cannot accept the URL or an
active Connection object if it can.

220

The key argument to DriverManager.getConnection() is a JDBC URL, which is a string with three
components separated by semicolons:
<protocol>:<subprotocol>:<subname>
where
protocol is always jdbc.
subprotocol is a vendor-specific string that identifies the driver to be used. The driver indicates
whether it can handle that subprotocol when asked by the driver manager. For example, the
JDBC-ODBC bridge uses the reserved value odbc as its subprotocol. This value is intended to be
unique across all driver vendors. Sun Microsystems acts as an informal registrar of JDBC
subprotocols.
subname identifies the specific database to connect to. This string contains whatever the driver
needs to identify the database. It may also contain connection parameters the database needs.
Examples of JDBC URLs are
jdbc:odbc:finance
This would indicate an ODBC data source named finance that is accessed by the JDBC-ODBC bridge
driver.
You can also specify like this
jdbc:idb:c:/path/database.prp
Example: connecting to Mysql server
private static Connection getConnection()
{
Connection con = null;
try
{
Class.forName(com.mysql.jdbc.Driver);
String url = jdbc:mysql://localhost:3306/teaching;
String user = root;
String pw = servletprogramming;
con = DriverManager.getConnection(url, user, pw);
}
catch (ClassNotFoundException e)
{
System.out.println(e.getMessage());
System.exit(0);
}
catch (SQLException e)
{
System.out.println(e.getMessage());
System.exit(0);
}
return con;
}

221

Querying a Database
After you establish a connection to a database, you can execute select statements to retrieve data. To
do so, you have to use several classes and interfaces:
Connection: The Connection class has two methods youre likely to use. The close() method
closes the connection, and the createStatement() method returns a Statement object, which you
then use to execute statements.

Statement: The Statement interface contains the methods necessary to send statements to the
database for execution and return the results. In particular, you use the executeQuery() method
to execute a select statement or the executeUpdate() method to execute an insert, update, or
delete statement.

ResultSet: The ResultSet interface represents rows returned from a query. It provides methods
you can use to move from row to row and to get the data for a column.

The following table shows methods of Connection and Statement classes.


Connection Class Methods
Description
void close()
Statement createStatement()

Closes the connection.


Creates a Statement object that can execute a SQL statement
on the database connected by the connection.

Statement createStatement (int type, Creates a Statement object that can execute an SQL statement
int concur)
on the database connected by the connection.
Statement Interface Methods
ResultSet executeQuery(String sql)
int executeUpdate(String sql)

Description
Executes the select statement contained in the string
parameter and returns the result data as a ResultSet object.
Executes the insert, update, or delete statements contained in
the string parameter and returns the result data as a ResultSet
object.

Statement createStatement (int type, int concur);


The first parameter of the createStatement method specifies the type of result set that is created, and
can be one of the following:

ResultSet.TYPE_FORWARD_ONLY - The result set cannot be scrolled; its cursor moves forward
only, from before the first row to after the last row.

ResultSet.TYPE_SCROLL_INSENSITIVE - The result can be scrolled; its cursor can move both
forward and backward relative to the current position, and it can move to an absolute position.
The result set is insensitive to changes made to the underlying data source while it is open. It
contains the rows that satisfy the query at either the time the query is executed or as the rows
are retrieved.

ResultSet.TYPE_SCROLL_SENSITIVE - The result can be scrolled; its cursor can move both forward
and backward relative to the current position, and it can move to an absolute position. The
result set reflects changes made to the underlying data source while the result set remains open.

222

The second parameter is the concurrency of a ResultSet object. The concurrency of a ResultSet object
determines what level of update functionality is supported. This indicates whether the result set is readonly or updatable, and can be one of the following:
ResultSet.CONCUR_READ_ONLY
ResultSet.CONCUR_UPDATABLE
Executing a select statement
The following snippet executes a select statement and puts the result in Resultset:
Connection con = null;
try
{
Class.forName(com.mysql.jdbc.Driver);
String url = jdbc:mysql://localhost:3306/teaching;
String user = root;
String pw = dbconn;
con = DriverManager.getConnection(url, user, pw);
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
System.exit(0);
}
Statement st = con.createStatement();
String select = Select title, year, price from movie order by year;
ResultSet rows = st.executeQuery(select);
Here, the result set is stored in the rows variable.
Navigating through the result set
The ResultSet object returned by the executeQuery statement contains all the rows that are retrieved by
the select statement. You can only access one of those rows at a time. The result set maintains a pointer
called a cursor to keep track of the current row. You can use the following methods to move the cursor
through a result set.

Navigation Methods of the ResultSet Interface


Method

Description

void close()

Closes the Resultset

boolean next()

Moves cursor to the next row

boolean previous()

Moves the cursor to the previous row in the ResultSet

boolean first()

Moves the cursor to the first row in the ResultSet

void last()

Moves the cursor to the last row.

223

void beforeFirst()

Moves the cursor to the front of this ResultSet object, just before the
first row.

void afterLast()

Moves the cursor to the end of the ResultSet object, just after the last
row

boolean absolute(int row)

Moves the cursor to the given row number in this ResultSet object.

boolean relative(int row)

Moves the cursor forward or backward the number of rows specified

int getRow()

Gets the current row number

boolean isBeforeFirst()

True if the cursor is before the first row

boolean isAfterLast()

True if the cursor is after the last row

boolean isFirst()

True if the cursor is positioned on the first row

boolean isLast()

True if the cursor is positioned on the last row

boolean absolute(int row)


If the row number is positive, the cursor moves to the given row number with respect to the beginning
of the result set. The first row is row 1, the second is row 2, and so on.
If the given row number is negative, the cursor moves to an absolute row position with respect to the
end of the result set. For example, calling the method absolute(-1) positions the cursor on the last row;
calling the method absolute(-2) moves the cursor to the next-to-last row, and so on.
An attempt to position the cursor beyond the first/last row in the result set leaves the cursor before the
first row or after the last row. Calling absolute(1) is the same as calling first(). Calling absolute(-1) is the
same as calling last().
Customer table used for examples below
name
sex
email

telephone

Aroun Moken

Male

aroun@yahoo.com

786958475

Lalise Tola

Female

lal@gmail.com

998374655

..

Example: the following code shows how you can process each row in a result set:
Connection con = null;
Statement statement = null;
ResultSet records = null;
String sql;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:customers", "", "");

224

sql = "select * from customer";


statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
records = statement.executeQuery(sql);
}
catch(SQLException xx) {
out.print(Error: " + xx.getMessage());
}
catch(Exception xx) {
out.print(Error: " + xx.getMessage());
}
while(records.next())
{
records.getString("name");
records.getString("sex");
records.getString("email");
records.getInt("telephone");
}
records.close();
con.close();
The data returned from the database can be accessed using column number/index or column names. To
access the columns of the database table from the ResultSet, we use the following methods:
Get Methods of the ResultSet Interface

Method

Description

BigDecimal getBigDecimal(String columnName)


BigDecimal getBigDecimal(int columnIndex)
boolean getBoolean(String columnName)
boolean getBoolean(int columnIndex)
Date getDate(String columnName)
Date getDate(int columnIndex)
double getDouble(String columnName)
double getDouble(int columnIndex)
float getFloat(String columnName)
float getFloat(int columnIndex)
int getInt(String columnName)
int getInt(int columnIndex)
long getLong(String columnName)
long getLong(int columnIndex)
short getShort(String columnName)
short getShort(int columnIndex)
String getString(String columnName)

Gets the value of the specified column as a


BigDecimal
Gets the value of the specified column as a boolean
Gets the value of the specified column as a Date
Gets the value of the specified column as a double
Gets the value of the specified column as a float
Gets the value of the specified column as a int
Gets the value of the specified column as a long
Gets the value of the specified column as a short
Gets the value of the specified column as a String

225

String getString(int columnIndex)


Example: databse connection
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Database extends HttpServlet
{
Connection con = null;
Statement statement = null;
ResultSet records = null;
String sql;
public void init() { }
public void destroy() { }
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:customers", "", "");
sql = "select * from customer";
statement = con.createStatement (ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
records = statement.executeQuery(sql);
records.next();
out.print("<html> \n <head> \n<title> Database Example</title> \n </head>");
out.print("<body>");
out.print("<table border='1'>");
while(records.next())
{
out.print("<tr>");
out.print("<td>" + records.getString("name") + "</td>");
out.print("<td>" + records.getString("sex") + "</td>");
out.print("<td>" +records.getString("email") + "</td>");
out.print("<td>" +records.getInt("telephone") + "</td>");
out.print("</tr>");
}

226

out.print("</table>");
records.close();
con.close();
out.print("</body> \n </html>");
}
catch(SQLException xx) {
out.print("Querying: " + xx.getMessage());
}
catch(Exception xx) {
out.print("Querying: " + xx.getMessage());
}
finally {
out.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
public String getServletInfo() {
return "Short description";
}
}
An HTML side that invokes the above Servlet
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h2 style="text-decoration: underline"> Database Access Using Servlet </h2>
<a href="Database">See Customer Table</a>
</body>
</html>

Updating Database
227

Methods for Updatable ResultSets


Method

Description

void cancelRowUpdates()

Cancels the updates made to the current row in this ResultSet object.

void deleteRow()

Deletes the current row from this ResultSet object and from the
underlying database.

void insertRow()

Inserts the contents of the insert row into this ResultSet object and into
the database.

void moveToCurrentRow()

Moves the cursor to the remembered cursor position, usually the current
row.

void moveToInsertRow()

Moves the cursor to the insert row.

void refreshRow()

Refreshes the current row with its most recent value in the database.

void updateRow()

Updates the underlying database with the new contents of the current
row of this ResultSet object.

Deleting Rows
Example: deleting a row
try
{
rs.absolute(3);
rs.deleteRow();
}
catch (SQLException e)
{
out.println(e.getMessage());
}

Updating Rows
For a result set to be updated, it must have been produced by a Statement object created with a
concurrency type of ResultSet.CONCUR_UPDATABLE. JDBC provides updateXXX() methods, where XXX is
the JDBC data type, similar to the existing getXXX() methods. These methods take a column number or
column name parameter, and a value parameter.
The following example illustrates this:
double mySalary = rs.getDouble(SALARY);
mySalary *= 2.0;
rs.updateDouble(SALARY, mySalary);
rs.updateString(HOME_PHONE, unlisted);
rs.updateRow();

Inserting New Rows

228

New rows can be added to the result set and the underlying table with insertRow(). This involves a
special cursor position known as the insert row. The following example illustrates how this works:
rs.moveToInsertRow();
rs.updateString(name, David Jacques);
rs.updateString(sex, Male);
rs.updateString(email, jacques@yahoo.com);
rs.updateInt(telephone, 8954578693567);
rs.insertRow();
rs.moveToCurrentRow(); // Return to where we were
Update Methods of the ResultSet Interface
Update by Column Name

Update by Column Index

void updateBoolean (String columnName, boolean


value)
void updateDate(String columnName, Date value)
void updateDouble (String columnName, double
value)
void updateFloat(String columnName, float value)
void updateInt(String columnName, int value)
void updateLong(String columnName, long value)
void updateShort(String columnName, short value)
void updateBigDecimal (String columnName,
BigDecimal value)
void updateString(String columnName, value)

void updateBoolean(int columnIndex, boolean


value)
void updateDate(int columnIndex, Date value)
void updateDouble(int columnIndex, double value)
void updateFloat(int columnIndex, float value)
void updateInt(int columnIndex, int value)
void updateLong(int columnIndex, long value)
void updateShort(int columnIndex, short value)
void updateBigDecimal(int columnIndex,
BigDecimal value)
void updateString(int String columnIndex, String
value)

The above update can be done by using SQL statements. Here is an example:
Class.forName(com.mysql.jdbc.Driver);
String url = jdbc:mysql://localhost:3306/teaching;
Connection con = DriverManager.getConnection(url, root, vertrigo);
try
{
Statement stmt = con.createStatement();
sql = insert into customers values(David Jacques, Male, jacques@yahoo.com, 8954578693567);
int i = stmt.executeUpdate(sql);
if (i == 1)
System.out.println(Loan recorded.);
else
System.out.println(Loan not recorded.);
}
catch (SQLException e)
{
System.out.println(e.getMessage());
System.exit(0);
}

229

Batch Updating
JDBC 2.0 introduced the capability to submit a group of update statements to be executed as a batch. In
some cases, this can represent a significant performance improvement. The methods used in connection
with batch updates are these:
clearBatch resets a batch to the empty state.
addBatch adds an update statement to the batch.
executeBatch submits the batch and collects update counts.
import java.io.*;
import java.sql.*;
import java.util.*;
public class TransactionExample
{
public void CreateTable() throws ClassNotFoundException, SQLException, IOException
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = null;
try
{
con = DriverManager.getConnection ("jdbc:odbc:teaching");
Statement stmt = con.createStatement();
stmt.executeUpdate(" CREATE TABLE Student (lastName VARCHAR(20), +
firstName VARCHAR(20), age INTEGER )");
// Set up for handling all-or-nothing transaction
con.setAutoCommit(false);
// Add insert statements to a batch
stmt.clearBatch();
stmt.addBatch("INSERT INTO Student VALUES ('Rodrigo','Joaquin',30)");
stmt.addBatch("INSERT INTO Student VALUES ('Gossec','Francois-Joseph',36)");
stmt.addBatch("INSERT INTO Student VALUES ('Ruggles','Carl',36)");
stmt.addBatch("INSERT INTO Student VALUES ('Widor','Charles,34)");
stmt.addBatch("INSERT INTO Student VALUES ('Sibelius','Jean',23)");
stmt.addBatch("INSERT INTO Student VALUES('Copland','Aaron',21)");
stmt.addBatch("INSERT INTO Student VALUES('Auber','Daniel Francois',30)");
stmt.addBatch("INSERT INTO Student VALUES('Stravinsky','Igor',40)");
// Execute the batch and check the update counts
int[] counts = stmt.executeBatch();
boolean allGood = true;
for (int i = 0; i < counts.length; i++)
if (counts[i] != 1)
allGood = false;

230

// Commit or roll back the transaction


if (allGood)
{
System.out.println("Transaction successful with " + counts.length + " statements");
con.commit();
}
else
{
System.out.println("Transaction failed");
con.rollback();
}
stmt.close();
}
finally
{
if (con != null)
con.close();
}
}
}

Using Cookies
Cookies can be created using the Cookie class. Create a cookie using the Cookie constructor with two
parameters: a name and a value. The value parameter represents the information that you want to
store. This value may include the users name or any arbitrary string value. To create a cookie, put the
following in your servlet:
Cookie myCookie = new Cookie("Cookiename", "value");
The cookie is added to the Set-Cookie response header by means of the addCookie method of
HttpServletResponse. Here's an example:
Cookie userCookie = new Cookie("user", "uid1234");
response.addCookie(userCookie);
The values stored in cookies can only be strings. Therefore, you should text-encode all data that you
store in a cookie. Once you add a cookie to your response object, WebLogic Server automatically places
it in the client browser. The client browser stores the cookie to the local computer disk for future
requests.
When WebLogic Server invokes a servlet, the cookies sent by the browser are included in the
HttpServletRequest object. These cookies are retrieved as an array of cookie objects using the following
code:
Cookie[] cookies = request.getCookies();

231

Once you have the cookie objects, you can search for your specific cookie. You can use the getName()
method to look at each cookies name:
// assign the name of the first cookie in the array to string foo
String foo = Cookies[0].getName();
If the users browser does not accept cookies it does not include cookies in subsequent requests. In this
case, the result of request.getCookies() returns null (or an array without the cookie you added). In
general, the servlet author has no way to determine in advance whether a particular client will accept
cookies.
You can manipulate all aspects of a cookie using familiar Java methods. The Cookie object has the
following methods:
getComment(): The getComment() method returns the comment describing the purpose of this
cookie, or null if the cookie has no comment.
setComment(String purpose): The setComment() method is used to specify a comment that
describes a cookies purpose.
getMaxAge(): The getMaxAge() method returns an int value representing the maximum age of
the cookie, specified in seconds.A value of 1 indicates the cookie will persist until browser
shutdown.
setMaxAge(int expiry): The setMaxAge() method sets the maximum age of the cookie in
seconds.
getName(): The getName() method returns a String object representing the name of the cookie.
setName(String name): sets the name of the cookie. The name and the value are the two things
you always care about in cookies. Since the getCookies method of HttpServletRequest returns an
array of Cookie objects, it is common to loop down this array until you have a particular name,
then check the value with getValue.
getSecure(): The getSecure() method returns a boolean value that is true if the browser is
sending cookies only over a secure protocol, or false if the browser can send cookies using any
protocol. HTTP is an insecure protocol. Secure protocols such as SSL and TLS.
setSecure(boolean flag): Indicates to the browser whether the cookie should only be sent using
a secure protocol, such as HTTPS or SSL.
getValue(): The getValue() method returns a String object representing the value of the cookie.
setValue(String newValue): The setValue() method assigns a new value to a cookie after the
cookie is created. The default value of a cookie is specified when calling the constructor.
setDomain(String pattern): The setDomain() method specifies the domain within which this
cookie should be presented.
Example: using cookie
<html>
<body>
<center>
<form name="cookie" method="post" action=" AddCookieServlet">

232

<B>Enter your full name:</B>


<input type=textbox name="data" size=25>
<input type=submit value="Submit">
</form>
</body>
</html>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String data = request.getParameter("data");
// Create cookie.
Cookie cookie = new Cookie("name", data);
// Add cookie to HTTP response.
response.addCookie(cookie);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Cookie has been set to");
pw.println(data);
pw.close();
}
}
To read the cookies that come back from the client, you call getCookies on the HttpServletRequest. This
returns an array of Cookie objects corresponding to the values that came in on the HTTP request header.
Once you have this array, you loop down it, calling getName on each Cookie until you find one matching
the name you have in mind. You then call getValue on the matching Cookie, doing some processing
specific to the resultant value.
Reading content of cookie
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookiesServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException

233

{
// Get cookies from header of HTTP request.
Cookie[] cookies = request.getCookies();
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>");
for(int i = 0; i < cookies.length; i++)
{
String name = cookies[i].getName();
String value = cookies[i].getValue();
pw.println("name = " + name + ", value = " + value);
}
pw.close();
}
}

Using Sessions
A servlet indicates it wants to use a session by calling the getSession() or getSession(boolean create)
methods in HttpServletRequest, as shown here:
HttpSession session = request.getSession(true);
The servlet specification defines four methods that you can use to access the values in the HttpSession
object:
Object getAttribute (String name)Returns the object bound with the specified name in this
session, or null if no object is bound under the name.
void setAttribute (String name, Object attribute)Binds an object to this session using the
name specified.
Enumeration getAttributeNames()Returns an Enumeration of string objects containing the
names of all the objects bound to this session.
void removeAttribute(String name)Removes the object bound with the specified name from
this session.
Here is a summary of important methods available through HttpSession object:
Method
Description
getAttribute(String name)

Enumeration getAttributeNames()

long getCreationTime()

String getId()

This method returns the object bound with the specified


name in this session, or null if no object is bound under the
name.
This method returns an Enumeration of String objects
containing the names of all the objects bound to this
session.
This method returns the time when this session was
created, measured in milliseconds since midnight January 1,
1970 GMT.
This method returns a string containing the unique

234

long getLastAccessedTime()

int getMaxInactiveInterval()

void invalidate()
boolean isNew()

void removeAttribute(String name)

identifier assigned to this session.


This method returns the last time the client sent a request
associated with this session, as the number of milliseconds
since midnight January 1, 1970 GMT.
This method returns the maximum time interval, in
seconds, that the servlet container will keep this session
open between client accesses.
This method invalidates this session and unbinds any
objects bound to it.
This method returns true if the client does not yet know
about the session or if the client chooses not to join the
session.
This method removes the object bound with the specified
name from this session.

void setAttribute(String name,


Object value)

This method binds an object to this session, using the name


specified.

void setMaxInactiveInterval(int
interval)

This method specifies the time, in seconds, between client


requests before the servlet container will invalidate this
session.

Example:
HttpSession session = request.getSession (true);
// check to see if the session is new
if (session.isNew()) {
//we send a redirect to login page
responseObj.sendRedirect("http://www.learnweblogic.com/login");
}
Use sessions to mark login status. Create a new session only on login and look for a session to confirm
login status. When the user logs out, invalidate the session. Use filters to apply security checks
consistently throughout your Web application.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Session extends HttpServlet
{
int cntr;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
HttpSession session = req.getSession(true);
res.setContentType("text/html");

235

PrintWriter out = res.getWriter();


out.println("<HEAD><TITLE>SessionServlet Output</TITLE></HEAD><BODY>");
out.println("<h1 style='text-decoration:underline'>SessionServlet Output</h1>");
// Retrieve the count value from the session
try
{
cntr = Integer.parseInt((session.getAttribute("counter")).toString());
if (cntr != 0)
cntr++;
session.setAttribute("counter", cntr);
}
catch(Exception xx) //no session created yet, so initialize the session & store it
{
cntr = 1;
session.setAttribute("counter", cntr);
}
// And print out number of times the user has hit this page:
out.println("You have hit this page <b>" + cntr +"</b> times.<p>");
out.println("Click <a href=" + res.encodeURL("/ServletSession/Session") + ">here</a>");
out.println(" to ensure that session tracking is working even if cookies aren't supported.<br>");
// demonstrate some of the more common methods in the HttpSession object
out.println("<h3>Request and Session Data:</h3>");
out.println("<h3>Session Data:</h3>");
out.println("New Session: " + session.isNew());
out.println("<br>Session ID: " + session.getId());
out.println("<br>Creation Time: " + new Date(session.getCreationTime()));
out.println("<br>Last Accessed Time: " + new Date(session.getLastAccessedTime()));
out.println("</BODY>");
}
}
Web Server automatically generates temporary cookies to store the session ID, but what if a client does
not accept cookies? URL rewriting provides a way to deal with these clients. URL rewriting works by
modifying the HTML code sent to the client. WebLogic Server adds a session ID to the end of each URL
on links back to your application. Web Server can use this session ID in place of cookies to match the
request to the right session.

236

URL rewriting requires that the servlet call an encoding method in the servlet response object for URLs
in the generated HTML page. For URL rewriting to work reliably, all servlets in a Web application must
use rewriting on all URLs. The methods to rewrite URLs take two forms:
String encodeURL(String url)Includes the logic required to encode the session information in
the returned URL. WebLogic Server automatically determines whether the session ID needs to
be encoded in the URL. If the browser supports cookies, or if session tracking is turned off, URL
encoding is unnecessary. To encode the URL, add the following code to your servlet:
//Add the Session Information Via URL Encoding
myHttpServletResponse.encodeURL(thisURL);
So, if your original URL was
<a href="foo.jsp">bar</a>
you would use the encodeURL() method on that URL:
out.println("<a href=\"" +response.encodeURL("foo.jsp">) + "\">bar</a>");

String encodeRedirectURL(String url)Performs the same task as the previous method, except
it is specially geared to redirects in the response object. For redirection, you should have the
following in your servlet:
// Sending a Redirect with URL Encoded session ID
response.sendRedirect(response.encodeRedirectUrl(anotherURL);

Java Server Pages(JSP)


AJavaServer page (JSP) is a template for a Web page that uses Java code to generate an HTML document
dynamically. JSPs are run in a server-side component known as a JSP container, which translates them
into equivalent Java servlets.
For this reason, servlets and JSP pages are intimately related. Whats possible in one is, in large part, also
possible in another, although each technology has its individual strengths. Because they are servlets, JSP
pages have all the advantages of servlets:
They have better performance and scalability than CGI scripts because they are persistent in
memory and multithreaded.
No special client setup is required.
They have built-in support for HTTP sessions, which makes application programming possible.
They have full access to Java technologynetwork awareness, threads, and database
connectivitywithout the limitations of client-side applets.
But, in addition, JSP pages have advantages of their own:
They are automatically recompiled when necessary.
Because they exist in the ordinary Web server document space, addressing JSP pages is simpler
than addressing servlets.
Because JSP pages are HTML-like, they have greater compatibility with Web development tools.

237

Components of a JSP Page


A .jsp file can contain JSP elements, fixed template data, or any combination of the two. JSP elements
are instructions to the JSP container about what code to generate and how it should operate. These
elements have specific start and end tags that identify them to the JSP compiler. Template data is
everything else that is not recognized by the JSP container. Template data (usually HTML) is passed
through unmodified, so the HTML that is ultimately generated contains the template data exactly as it
was coded in the JSP file.
Three types of JSP elements exist:
Directives
Scripting elements, including expressions, scriptlets, and declarations
Actions
Directives
Directives are messages to a JSP container. They do not send output to a client, but are used to define
page attributes, which custom tag libraries use and which other pages include. They are instructions to
the JSP container that describe what code should be generated. They have the general form:
<%@ directive-name [attribute="value" attribute="value" ...] %>
Zero or more spaces, tabs, and newline characters can be after the opening <%@ and before the ending
%>, and one or more whitespace characters can be after the directive name and between
attributes/value pairs.
The JSP describes three standard directives available in all compliant JSP environments:
page

238

include
taglib

The page directive


The page directive provides page-specific information to a JSP container. This information includes
settings such as the type of content the JSP is to produce, the default scripting language of the page, and
code libraries to import for use.
The syntax is:
<%@ page %>
Multiple page directives may be used on a single JSP or pages included via JSP as long as no specific
attribute, except import, occurs more than once. Attributes for the page directive are as follows.
The include Directive
The include directive merges the contents of another file at translation time into the .jsp source input
stream. The syntax is
<%@ include file="filename" %>
where filename is an absolute or relative pathname interpreted according to the current servlet context.
Examples would be:
<%@ include file="/header.html" %>
<%@ include file="/doc/legal/disclaimer.html" %>
The above directive is useful for including common pages that are shared and is included at compile
time. To include a page at run time, you should use dynamic JSP includes:
<jsp:include page=URL flush=true/>
As an example take the following two files, header.jsp and footer.jsp. The header.jsp file ncludes
information that is to appear at the top of a page. It includes site navigation and other miscellaneous
information. This header also tracks how many people have visited the site since the last time the Web
Application was reloaded.
Example: header.jsp
<%!
int pageCount = 0;
void addCount() {
pageCount++;
}
%>
<% addCount(); %>
<html>
<head>
<title>Header/Footer Example</title>
</head>
<body>
<center>
<h2>Servlets and JSP Web Tier</h2>

239

<a href="http://www.jsp.com">JSP Books</a> <a href="http://www.jsp.com/source">JSP Source code</a><br>


This site has been visited <%= pageCount %> times.
</center>
<br><br>
The footer.jsp file includes information that is to appear at the very bottom of a page. It includes
copyright information, disclaimers, and any other miscellaneous information.
Example: footer.jsp
<br><br>
<center>
Copyright &copy; 2003
</center>
</body>
</html>
By themselves header.jsp and footer.jsp do not do much, but when combined with some content, a full
page can be generated:
<%@ include file="header.jsp" %>
Only the content of a page is unique. The same header and footer are reused from header.jsp and
footer.jsp by means of the include directive
<%@ include file="footer.jsp" %>
So what is the advantage of this approach over combining header.jsp, content.jsp, and footer.jsp all in
one file in the first place? As the files are set up now, many more content pages can be created that
reuse the header and footer. The header and footer can also be changed at any given time, and the
changes are easily reflected across all of the JSP.
The taglib Directive
Custom actions, also called custom tag libraries, allow a JSP developer to link bits of markup to
customized Java code. The taglib directive informs a container what bits of markup on the page should
be conssidered custom code and what code the markup links to.
The taglib directive always follows the same syntax:
<%@tagliburi="uri" prefix="prefixOfTag" %>
where the uri attribute value resolves to a location the container understands and the prefix attribute
informs a container what bits of markup are custom actions.
<%@ taglib uri=/web-inf/taglib.tld prefix=tagPrefix %>
<tagPrefix:tagName attributeName=attributeValue>
JSP content
</tagPrefix:tagName>
<tagPrefix:tagName attributeName=attributeValue/>
In addition to the pre-defined JSP actions, developers may add their own custom actions using the JSP
Tag Extension API. Developers write a Java class that implements one of the Tag interfaces and provide a
tag library XML description file that specifies the tags and the java classes that implement the tags.

240

Consider the following JSP.


<%@ taglib uri="mytaglib.tld" prefix="myprefix" %>
...
<myprefix:myaction> <%-- the start tag %>
...
</myprefix:myaction> <%-- the end tag %>
...
The JSP compiler will load the mytaglib.tld XML file and see that the tag 'myaction' is implemented by
the java class 'MyActionTag'. The first time the tag is used in the file, it will create an instance of
'MyActionTag'. Then (and each additional time that the tag is used), it will invoke the method
doStartTag() when it encounters the starting tag. It looks at the result of the start tag, and determines
how to process the body of the tag. The body is the text between the start tag and the end tag.
The doStartTag() method may return one of the following:
SKIP_BODY - the body between the tag is not processed
EVAL_BODY_INCLUDE - evaluate the body of the tag
EVAL_BODY_TAG - evaluate the body of the tag and push the result onto stream (stored in the
body content property of the tag).
If tag extends the BodyTagSupport class, the method doAfterBody() will be called when the body has
been processed just prior to calling the doEndTag(). This method is used to implement looping
constructs.
When it encounters the end tag, it invokes the doEndTag() method. The method may return one of two
values:
EVAL_PAGE - this indicates that the rest of the JSP file should be processed.
SKIP_PAGE - this indicates that no further processing should be done. Control leaves the JSP
page. This is what is used for the forwarding action.
The myaction tag above would have an implementation class that looked like something below:
public class MyActionTag extends TagSupport
{
//Releases all instance variables.
public void release() {...}
public MyActionTag() { ... }
//called for the start tag
public int doStartTag() { ... }
//called at the end tag
public int doEndTag(){ ... }
}

241

Scriptlets
Scriptlets provide a method for directly inserting bits of Java code between chunks of template text. A
scriptlet is defined with a start, <%, an end, %>, with code between. Using Java, the script is identical to
normal Java code but without needing a class declaration or any methods. Scriptlets are great for
providing lowlevel functionality such as iteration, loops, and conditional statements, but they also
provide a method for embedding complex chunks of code within a JSP.
The syntax for scriptlet is:
<%
code goes here
%>
Example: loop.jsp
<html>
<head>
<title>Loop Example</title>
</head>
<body>
<% for (int i=0; i<5; i++) { %>
Repeated 5 Times.<br>
<% } %>
</body>
</html>

Comments
The JSP specification provides two means of including comments in a JSP page: one for hidden
comments only visible in the JSP page itself and one for comments included in the HTML or XML output
generated by the page. The syntax is:
<%- - This is a hidden JSP comment - -%>
When the JSP compiler encounters the start tag <%- - of a JSP comment, it ignores everything from that
point in the file until it finds the matching end tag - -%>.
The other comment type uses the normal HTML or XML comment tag. Comments of this type are passed
through unaltered to the response output stream and are included in the generated HTML. They are
invisible in the browser window, but can be seen by invoking the View Source menu option.
<!- - This is included in the generated HTML - ->

Expressions
JSP provides a simple means for accessing the value of a Java variable or other expression and merging
that value with the HTML in the page. The syntax is
<%= exp %>
where exp is any valid Java expression.
The expression can have any data value, as long as it can be converted to a string. This conversion is
usually done simply by generating an out.print() statement. For example, the JSP code:
The current time is <%= new java.util.Date() %>

242

This may generate the servlet code:


out.write("The current time is ");
out.print( new java.util.Date() );
out.write("\r\n");
Example:
<html>
<head>
<title>Iteration Example</title>
</head>
<body>
<%
String[] strings = new String[4];
strings[0] = "Alpha";
strings[1] = "Beta";
strings[2] = "Gamma";
strings[3] = "Omega";
for (int i=0; i<strings.length;i++) {
%>
String[<%= i %>] = <%= strings[i] %><br>
<% } %>
</body>
</html>

Declarations
Like scriptlets, declarations contain Java language statements, but with one big difference: scriptlet code
becomes part of the _jspService() method, whereas declaration code is incorporated into the generated
source file outside the _jspService() method.
This tag allows the developer to declare variables or methods. Code placed in this tag must end with
semicolon (;). Declarations do not generate output, they are used with JSP expressions or scriptlets.
The syntax of a declaration section is
<%!
statement;
[statement; ...]
%>

Declaration sections can be used to declare class or instance variables, methods, or inner classes. Unlike
scriptlets, they have no access to the implicit objects described in the next section. If you use a
declaration section to declare a method that needs to use the request object, for example, you need to
pass the object as a parameter to the method.
<%!
int pageCount = 0;
void addCount() {
pageCount++;
}

243

%>
Example: using JSP scripting elements and directives
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h3><u>Checking Java Server Pages</u> <br> </h3>
<form name="info" action="ServerInfo.jsp" method="get">
Name: <input type="text" name="name"> <br><br>
Country: <input type="text" name="country"> <br><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="submit" value="Submit">
</form>
</body>
</html>
//file: ServerInfo.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<HTML>
<HEAD>
<TITLE>Using Java Server Pages</TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E0" TEXT="#000000" LINK="#0000EE" VLINK="#551A8B" ALINK="#FF0000">
<H3 style="text-decoration: underline"> Using Java Server Pages </H3>
Some dynamic content created using various JSP mechanisms:
<UL>
<LI><B>Expression.</B><BR>
Your host name: <%= request.getRemoteHost() %>.
<LI><B>Scriptlet.</B><BR>
<% out.println("Attached GET data: " + request.getQueryString()); %>
<LI><B>Declaration (plus expression).</B><BR>
<%! private int accessCount = 0; %>
Accesses to page since server reboot: <%= ++accessCount %>
<LI><B>Directive (plus expression).</B><BR>
<%@ page import = "java.util.*" %>
Current date: <%= new Date() %>
</UL>
</BODY>
</HTML>

244

Predefined Variables
To simplify code in JSP expressions and scriptlets, you are supplied with eight automatically defined
variables, sometimes called implicit objects. The available variables are request, response, out, session,
application, config, pageContext, and page.

I. request
This is the HttpServletRequest associated with the request, and lets you look at the request parameters
via getParameter, the request type (GET, POST, HEAD, etc.), and the incoming HTTP headers (cookies,
Referer, etc.). Strictly speaking, request is allowed to be a subclass of ServletRequest other than
HttpServletRequest, if the protocol in the request is something other than HTTP. This is almost never
done in practice.

II. response
This is the HttpServletResponse associated with the response to the client. Note that, since the output
stream is buffered, it is legal to set HTTP status codes and response headers, even though this is not
permitted in regular servlets once any output has been sent to the client.

III. out
This is the PrintWriter used to send output to the client. However, in order to make the response object
useful, this is a buffered version of PrintWriter called JspWriter. Note that you can adjust the buffer size,
or even turn buffering off, through use of the buffer attribute of the page directive. Also note that out is
used almost exclusively in scriptlets, since JSP expressions automatically get placed in the output stream,
and thus rarely need to refer to out explicitly.

IV. session
This is the HttpSession object associated with the request. Recall that sessions are created automatically,
so this variable is bound even if there was no incoming session reference. The one exception is if you use
the session attribute of the page directive to turn sessions off, in which case attempts to reference the
session variable cause errors at the time the JSP page is translated into a servlet.

V. application
245

This is the ServletContext as obtained via getServletConfig().getContext().

VI. config
This is the ServletConfig object for this page.

VII. pageContext
JSP introduced a new class called PageContext to encapsulate use of server-specific features like higher
performance JspWriters. The idea is that, if you access them through this class rather than directly, your
code will still run on "regular" servlet/JSP engines.

VIII. page
This is simply a synonym for this, and is not very useful in Java. It was created as a placeholder for the
time when the scripting language could be something other than Java.

Actions
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can
dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate
HTML for the Java plugin. Available actions include:
jsp:include - include a file at the time the page is requested.
jsp:useBean - find or instantiate a JavaBean.
jsp:setProperty - set the property of a JavaBean.
jsp:getProperty - insert the property of a JavaBean into the output.
jsp:forward - forward the requester to a new page.
jsp:plugin - generate browser-specific code that makes an OBJECT or EMBED tag for the Java
plugin.
Remember that, as with XML in general, the element and attribute names are case sensitive.
The jsp:include Action
This action lets you insert files into the page being generated. The syntax looks like this:
<jsp:include page="relative URL" flush="true" />
Unlike the include directive, which inserts the file at the time the JSP page is translated into a servlet,
this action inserts the file at the time the page is requested. This pays a small penalty in efficiency, and
precludes the included page from containing general JSP code (it cannot set HTTP headers, for example),
but it gains significantly in flexibility.
For example, here is a JSP page that inserts four different snippets into a "What's New?" Web page. Each
time the headlines change, authors only need to update the four files, but can leave the main JSP page
unchanged.
<!--file: WhatsNew.jsp-->
<HTML>
<HEAD>
<TITLE>What's New</TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E6" TEXT="#000000" LINK="#0000EE" VLINK="#551A8B" ALINK="#FF0000">

246

<CENTER> What's New at JspNews.com </CENTER>


Here is a summary of our four most recent news stories:
<OL>
<LI><jsp:include page="news/Item1.html" flush="true"/>
<LI><jsp:include page="news/Item2.html" flush="true"/>
<LI><jsp:include page="news/Item3.html" flush="true"/>
<LI><jsp:include page="news/Item4.html" flush="true"/>
</OL>
</BODY>
</HTML>
The jsp:forward Action
This action lets you forward the request to another page. It has a single attribute, page, which should
consist of a relative URL. This could be a static value, or could be computed at request time, as in the two
examples below.
<jsp:forward page="/utils/errorReporter.jsp" />
<jsp:forward page="<%= someJavaExpression %>" />

Connecting to Database
Before you can use JDBC to access a SQL database, you must first establish a connection to the
database. The first step to establishing a connection involves registering the driver class so the class is
available. To do that, you use the forName method of the Class class, specifying the package and class
name of the driver.
For example, to register the MySQL connector, use this statement:
Class.forName(com.mysql.jdbc.Driver);
To register the standard ODBC driver, use this statement instead:
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
Note that the forName method throws ClassNotFoundException, so you have to enclose this statement
in a try/catch block that catches ClassNotFoundException.

Registering a Driver
For a JDBC driver to be used, it must first be registered with the driver manager. You can accomplish this
in several ways, but each involves calling DriverManager.registerDriver(). The most common approach
is simply to load the driver class:
try {
Class.forName("MyJdbcDriver");
}
catch (ClassNotFoundException e) {
// Report the exception
}
A driver class loaded in this fashion should create an instance of itself and register it with the driver
manager, using logic similar to the following:

247

static {
PrintStream log = DriverManager.getLogStream();
if (log != null)
log.println("MyJdbcDriver class loaded");
MyJdbcDriver driver = new MyJdbcDriver();
try {
DriverManager.registerDriver(driver);
}
catch (SQLException e) {
if (log != null)
log.println("Unable to register driver");
}
}
To use the JDBC-ODBC bridge in a Java application, a suitable ODBC data source must be configured. The
data source should be configured as a System DSN, not a User DSN. The driver class name is
sun.jdbc.odbc.JdbcOdbcDriver if the Sun JVM is being used or com.ms.jdbc.odbc.JdbcOdbcDriver for the
Microsoft virtual machine.
The database URL used in the getConnection() statement is jdbc:odbc:dsn, where dsn is the data source
name. Microsoft supplies ODBC drivers for its Access database product, as well as dBase, Excel, FoxPro,
and a number of others, including a text driver that can use ordinary text files (.txt and .csv) as a simple
database system.

Connecting to a Database
After you register the driver class, you can call the static getConnection method of the DriverManager
class to open the connection. This method takes three String parameters: the database URL, the user
name, and a password.
Heres an example:
String url = jdbc:mysql://localhost/Movies;
String user = root;
String pw = pw;
con = DriverManager.getConnection(url, user, pw);
DriverManager provides three different methods to get connection:
DriverManager.getConnection(String url)
DriverManager.getConnection(String url, String userID, String password)
DriverManager.getConnection(String url, Properties prop)
Internally, DriverManager uses the same private worker method to handle each of these methods. The
driver manager maintains a list of registered drivers. When its getConnection() method is invoked, it
interrogates each driver in turn to see if it will accept the specified URL. The driver manager does this by
calling the drivers connect() method, which returns either null if the driver cannot accept the URL or an
active Connection object if it can.
The key argument to DriverManager.getConnection() is a JDBC URL, which is a string with three
components separated by semicolons:

248

<protocol>:<subprotocol>:<subname>
where
protocol is always jdbc.
subprotocol is a vendor-specific string that identifies the driver to be used. The driver indicates
whether it can handle that subprotocol when asked by the driver manager. For example, the
JDBC-ODBC bridge uses the reserved value odbc as its subprotocol. This value is intended to be
unique across all driver vendors. Sun Microsystems acts as an informal registrar of JDBC
subprotocols.
subname identifies the specific database to connect to. This string contains whatever the driver
needs to identify the database. It may also contain connection parameters the database needs.
Examples of JDBC URLs are
jdbc:odbc:finance
This would indicate an ODBC data source named finance that is accessed by the JDBC-ODBC bridge
driver.
jdbc:idb:c:/path/database.prp
Example: connecting to Mysql server
private static Connection getConnection()
{
Connection con = null;
try
{
Class.forName(com.mysql.jdbc.Driver);
String url = jdbc:mysql://localhost/Movies;
String user = root;
String pw = NuttMutt;
con = DriverManager.getConnection(url, user, pw);
}
catch (ClassNotFoundException e)
{
System.out.println(e.getMessage());
System.exit(0);
}
catch (SQLException e)
{
System.out.println(e.getMessage());
System.exit(0);
}
return con;
}
Querying a Database
After you establish a connection to a database, you can execute select statements to retrieve data. To
do so, you have to use several classes and interfaces:

249

Connection: The Connection class has two methods youre likely to use. The close() method
closes the connection, and the createStatement() method returns a Statement object, which you
then use to execute statements.

Statement: The Statement interface contains the methods necessary to send statements to the
database for execution and return the results. In particular, you use the executeQuery() method
to execute a select statement or the executeUpdate() method to execute an insert, update, or
delete statement.

ResultSet: The ResultSet interface represents rows returned from a query. It provides methods
you can use to move from row to row and to get the data for a column.

The following table shows methods of Connection and Statement classes.


Connection Class Methods
void close()
Statement createStatement()

Description
Closes the connection.
Creates a Statement object that can execute a SQL statement
on the database connected by the connection.

Statement createStatement (int type, Creates a Statement object that can execute an SQL statement
int concur)
on the database connected by the connection.
Statement Interface Methods
ResultSet executeQuery(String sql)
int executeUpdate(String sql)

Description
Executes the select statement contained in the string
parameter and returns the result data as a ResultSet object.
Executes the insert, update, or delete statements contained in
the string parameter and returns the result data as a ResultSet
object.

Statement createStatement (int type, int concur);


The first parameter of the createStatement method specifies the type of result set that is created, and
can be one of the following:
ResultSet.TYPE_FORWARD_ONLY
ResultSet.TYPE_SCROLL_INSENSITIVE
ResultSet.TYPE_SCROLL_SENSITIVE
The second parameter indicates whether the result set is read-only or updatable, and can be one of the
following:
ResultSet.CONCUR_READ_ONLY
ResultSet.CONSUR_UPDATABLE
Executing a select statement
The following snippet executes a select statement and gets the result set:
Connection con = null;
try
{
Class.forName(com.mysql.jdbc.Driver);
String url = jdbc:mysql://localhost/Movies;

250

String user = root;


String pw = dbconn;
con = DriverManager.getConnection(url, user, pw);
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
System.exit(0);
}
Statement st = con.createStatement();
String select = Select title, year, price from movie order by year;
ResultSet rows = st.executeQuery(select);
Here, the result set is stored in the rows variable.
Navigating through the result set
The ResultSet object returned by the executeQuery statement contains all the rows that are retrieved by
the select statement. You can only access one of those rows at a time. The result set maintains a pointer
called a cursor to keep track of the current row. You can use the methods to move the cursor through a
result set.

Navigation Methods of the ResultSet Interface


Method

Description

void close()

Closes the Resultset

boolean next()

Moves cursor to the next row

boolean previous()

Moves the cursor to the previous row in the ResultSet

boolean first()

Moves the cursor to the first row in the ResultSet

void last()

Moves the cursor to the last row.

void beforeFirst()

Moves the cursor to the front of this ResultSet object, just before the
first row.

void afterLast()

Moves the cursor to the end of the ResultSet object, just after the last
row

boolean absolute(int row)

Moves the cursor to the given row number in this ResultSet object.

boolean relative(int row)

Moves the cursor forward or backward the number of rows specified

int getRow()

Gets the current row number

boolean isBeforeFirst()

True if the cursor is before the first row

boolean isAfterLast()

True if the cursor is after the last row

boolean isFirst()

True if the cursor is positioned on the first row

251

boolean isLast()

True if the cursor is positioned on the last row

boolean absolute(int row)


If the row number is positive, the cursor moves to the given row number with respect to the beginning
of the result set. The first row is row 1, the second is row 2, and so on.
If the given row number is negative, the cursor moves to an absolute row position with respect to the
end of the result set. For example, calling the method absolute(-1) positions the cursor on the last row;
calling the method absolute(-2) moves the cursor to the next-to-last row, and so on.
An attempt to position the cursor beyond the first/last row in the result set leaves the cursor before the
first row or after the last row. Calling absolute(1) is the same as calling first(). Calling absolute(-1) is the
same as calling last().
Customer table used for examples below
name
sex
email

telephone

Aroun Moken

Male

aroun@yahoo.com

786958475

Lalise Tola

Female

lal@gmail.com

998374655

..

Example: the following code shows how you can process each row in a result set:
Connection con = null;
Statement statement = null;
ResultSet records = null;
String sql;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:customers", "", "");
sql = "select * from customer";
statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
records = statement.executeQuery(sql);
records.next();
}
catch(SQLException xx) {
JOptionPane.showMessageDialog(null, "Querying: " + xx.getMessage());
}
catch(Exception xx) {
JOptionPane.showMessageDialog(null, "1: " + xx.getMessage());
}
while(records.next())
{

252

records.getString("name");
records.getString("sex");
records.getString("email");
records.getInt("telephone");
}
records.close();
con.close();
Get Methods of the ResultSet Interface

Method

Description

BigDecimal getBigDecimal(String columnName)


BigDecimal getBigDecimal(int columnIndex)
boolean getBoolean(String columnName)
boolean getBoolean(int columnIndex)
Date getDate(String columnName)
Date getDate(int columnIndex)
double getDouble(String columnName)
double getDouble(int columnIndex)
float getFloat(String columnName)
float getFloat(int columnIndex)
int getInt(String columnName)
int getInt(int columnIndex)
long getLong(String columnName)
long getLong(int columnIndex)
short getShort(String columnName)
short getShort(int columnIndex)
String getString(String columnName)
String getString(int columnIndex)

Gets the value of the specified column as a


BigDecimal
Gets the value of the specified column as a boolean
Gets the value of the specified column as a Date
Gets the value of the specified column as a double
Gets the value of the specified column as a float
Gets the value of the specified column as a int
Gets the value of the specified column as a long
Gets the value of the specified column as a short
Gets the value of the specified column as a String

Example: databse connection


<%@ page import="java.sql.*" %>
<%@ page import="java.text.*" %>
<%!
public static final DecimalFormat PRICE_FMT = new DecimalFormat("$#,###.00");
%>
<HTML>
<HEAD>
<TITLE>Scrollable Example</TITLE>
</HEAD>
<BODY>
<IMG SRC="images/lyric_note.png" BORDER=0><P>

253

<HR COLOR="#000000">
<%
// Get driver name and database URL from configuration parameters stored in web.xml
String DRIVER = application.getInitParameter("jdbc.driver");
String URL = application.getInitParameter("jdbc.url");
// Load the driver
Class.forName(DRIVER);
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Connect to the database
con = DriverManager.getConnection(URL);
// Open a statement that supports scrollable result sets
stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
// Execute the query
rs = stmt.executeQuery(" SELECT itemcode, price, description FROM products
+ WHERE prodtype = 'IN' ORDER BY description");
// Calculate number of rows
rs.last();
int nRows = rs.getRow();
// Back up ten rows
rs.relative(-10);
// Now print last page of result set
%>
<H3>
Musical Instruments - Items <%= rs.getRow() + 1 %> through <%= nRows %>
</H3>
<TABLE BORDER=1 CELLPADDING=3 CELLSPACING=0>
<TR><TH>Item</TH><TH>Price</TH><TH>Description</TH></TR>
<%
while (rs.next())
{
String itemcode = rs.getString(1);
double price = rs.getLong(2) / 100.0;
String description = rs.getString(3);

254

%>
<TR>
<TD> <%= itemcode %> </TD>
<TD ALIGN="RIGHT"><%= PRICE_FMT.format(price) %></TD>
<TD><%= description %></TD>
</TR>
<%
}
}
finally {
if (rs != null) { rs.close(); rs = null; }
if (stmt != null) { stmt.close(); stmt = null; }
if (con != null) { con.close(); con = null; }
}
%>
</TABLE>
</BODY>
</HTML>

Updating Database
Methods for Updatable ResultSets
Method

Description

void cancelRowUpdates()

Cancels the updates made to the current row in this ResultSet object.

void deleteRow()

Deletes the current row from this ResultSet object and from the
underlying database.

void insertRow()

Inserts the contents of the insert row into this ResultSet object and into
the database.

void moveToCurrentRow()

Moves the cursor to the remembered cursor position, usually the


current row.

void moveToInsertRow()

Moves the cursor to the insert row.

void refreshRow()

Refreshes the current row with its most recent value in the database.

void updateRow()

Updates the underlying database with the new contents


of the current row of this ResultSet object.

Deleting Rows
Example: deleting a row
try
{
rs.absolute(3);
rs.deleteRow();

255

}
catch (SQLException e)
{
out.println(e.getMessage());
}

Updating Rows
For a result set to be updated, it must have been produced by a Statement object created with a
concurrency type of ResultSet.CONCUR_UPDATABLE. JDBC provides updateXXX() methods, where XXX is
the JDBC data type, similar to the existing getXXX() methods. These methods take a column number or
column name parameter, and a value parameter.
The following example illustrates this:
double mySalary = rs.getDouble(SALARY);
mySalary *= 2.0;
rs.updateDouble(SALARY, mySalary);
rs.updateString(HOME_PHONE, unlisted);
rs.updateRow();

Inserting New Rows


New rows can be added to the result set and the underlying table with insertRow(). This involves a
special cursor position known as the insert row. The following example illustrates how this works:
rs.moveToInsertRow();
rs.updateString(employeeid, M1205);
rs.updateString(firstName, Maria);
rs.updateString(lastName, Alicia);
rs.insertRow();
rs.moveToCurrentRow(); // Return to where we were
Update Methods of the ResultSet Interface
Update by Column Name

Update by Column Index

void updateBoolean (String columnName, boolean


value)
void updateDate(String columnName, Date value)
void updateDouble (String columnName, double
value)
void updateFloat(String columnName, float value)
void updateInt(String columnName, int value)
void updateLong(String columnName, long value)
void updateShort(String columnName, short value)
void updateBigDecimal (String columnName,
BigDecimal value)

void updateBoolean(int columnIndex, boolean


value)
void updateDate(int columnIndex, Date value)
void updateDouble(int columnIndex, double value)
void updateFloat(int columnIndex, float value)
void updateInt(int columnIndex, int value)
void updateLong(int columnIndex, long value)
void updateShort(int columnIndex, short value)
void updateBigDecimal(int columnIndex,
BigDecimal value)

256

void updateString(String columnName, value)

void updateString(int String columnIndex, String


value)

257

You might also like