Web Engineering
Web Engineering
Web Engineering
BE CSE – IV
Sem - VII
By
Unit – I
Introduction to HTML
HTML stands for Hyper Text Markup Language, which is the most widely used language on
Web to develop web pages. HTML was created by Berners-Lee in late 1991 but "HTML 2.0" was
the first standard HTML specification which was published in 1995. HTML 4.01 was a major
version of HTML and it was published in late 1999. Though HTML 4.01 version is widely used but
currently we are having HTML-5 version which is an extension to HTML 4.01, and this version
was published in 2012.
HTML is the standard markup language for creating Web pages.
HTML stands for Hyper Text Markup Language
HTML describes the structure of a Web page
HTML consists of a series of elements
HTML elements tell the browser how to display the content
HTML elements are represented by tags
HTML tags label pieces of content such as "heading", "paragraph", "table", and so on
Browsers do not display the HTML tags, but use them to render the content of the page
Learn other languages - Once you understands the basic of HTML then other related
technologies like javascript, php, or angular are become easier to understand.
Features of HTML
1. HTML uses a set of tags that is used to create document and then it can be published on the
World Wide Web.
2. HTML is platform independent. It is supported by all types of operating system and browser.
3. HTML lets user jump from topic to topic or page by page rather than finding and reading
information linearly by means of hyperlink.
4. Documents prepared in HTML include reference graphics and formatting tags.
5. It helps in creating or building Table either symmetrical or Asymmetrical shape.
6. HTML supports the concept of Frames, Image and Animating effects.
7. It contains powerful Formatting facilities for Text, Images.
8. It is used to improve the appearance of web pages.
9. It supports various types of appearance of web pages.
10. HTML supports form which make it possible to create document that collect and process user
input.
11. It tells how to make a document interactive through special hypertext links etc.
Advantages of HTML
1. For creating HTML document, only text editor is needed. No special software is required. For
example, in Windows Notepad editor is sufficient for creating HTML document.
2. HTML contains powerful formatting facilities by means of various formatting tags.
3. Linking to various pages and thus one can navigate all the web pages.
4. It is used to learn and master high level programming language.
Disadvantages of HTML
1. HTML does not offer programming language features and capabilities.
2. Any simple calculation cannot be done in HTML.
3. HTML lacks structure.
4. It can not be used to display even date and time.
5. The interactive web pages can not be built in HTML.
6. The web pages developed in HTML cannot behave like an application.
7. The web pages developed in HTML do not have their own interface.
8. HTML lacks syntactic checking i.e. you can not validate HTML code and required special types
of software like scripting languages.
HTML Editors
HTML documents are basically plain text and known as ASCII text editor. There are various types of
editors for different platforms. Aprt from basic text editor some operating system supports
WYSIWYG (What You Seen Is What You Get) editors.
Steps to Create and View HTML Document
1. Open a Text Editor ex. Notepad.
2. Write the appropriate HTML code line by line.
3. Save the HTML code in the file having extension .HTML.
4. Open the Browser (ex. Internet Explorer).
5. Browse the file or type in the appropriate address of the HTML file in the address bar to view the
HTML page and press OK button.
6. Now web page will be displayed on the screen.
Actual Document
</BODY>
</HTML>
Hello World using HTML.
Just to give you a little excitement about HTML, I'm going to give you a small conventional HTML
Hello World program.
<!DOCTYPE html>
<html>
<head>
<title>This is document title</title>
</head>
<body>
<h1>This is a heading</h1>
<p>Hello World!</p>
</body>
</html>
Example Explained
The <!DOCTYPE html> declaration defines this document to be HTML5
The <html> element is the root element of an HTML page
The <head> element contains meta information about the document
The <title> element specifies a title for the document
The <body> element contains the visible page content
The <h1> element defines a large heading
The <p> element defines a paragraph
Applications of HTML
As mentioned before, HTML is one of the most widely used language over the web. I'm going to
list few of them here:
Web pages development - HTML is used to create pages which are rendered over the web.
Almost every page of web is having html tags in it to render its details in browser.
Internet Navigation - HTML provides tags which are used to navigate from one page to
another and is heavily used in internet navigation.
Responsive UI - HTML pages now-a-days works well on all platform, mobile, tabs, desktop
or laptops owing to responsive design strategy.
Offline support HTML pages once loaded can be made available offline on the machine
without any need of internet.
Game development- HTML5 has native support for rich experience and is now useful in
gaming developent arena as well.
a. Start Tags
b. End Tags
Start tags are used to begin an effect and end tags are used to end that effect. Name of end tag is
same as the start tag but the name of end tags preceded by a forward slash (/). Tags that include
pair ags are called container tags, as they hold or contain the text and other HTML elements
between the two tags.
Syntax:
<TAG> CONTENTS </TAG>
Example:
<B>Hello World</B>
<B> is bold tag. The text written between start <B> and end tag </B> will be displayed in bold.
2. Singular Tags
This kind of tag consists of only start tags and does not need to end with end tags and known as
standalone ta. This tags does not contain any contents and hence known as Empty Tags.
Example: <BR> which helps to break current line.
Tag Attribute
Attributes are the properties/elements/parameters of the tag. It is placed within tags. It modifies the
effect of a tag. A general syntax is:
<Tag Attribute1 = “value” Attribute2 = “value”, …. AttributeN = “value”>
An attribute value must be enclosed either within single or double quotes but if value itself contains
double quotes then one must enclose entire value within single quotes. Attributes within tag are
separated by single space.
Some important features of tags are:
Some tags have no attributes. For example: <BR>
One may specify multiple attributes with a single tag and they may appear in any order.
Eample:
<BODY BGCOLOR=“GREEN” BACKGROUND= “COMPUTER.GIF” TEXT= “RED”>
Attribute Values
All most all, the attributes used in tag have certain value. Note the following important points related
to attribute values.
1. Sometimes one must pick a value from a group of options say Align Attribute contains values
like Left, Center or Right.
2. Sime attribute does not have ay value for example; COMPACT attribute used in List or
NOSHADE in <HR> tag does not have any value.
3. Some attribute are stricter regarding the kind of value they accept for example SRC attribute of
<IMG> tag will accept only URLs.
4. Some attribute automatically take default value when value is not specified but attribute is
defined. For example, BORDER attribute in <TABLE> tag automatically take a default value 2
pixels.
5. Some attributes automatically pick up the value among many. For example FACE attribute of
<FONT> tag. One may specify more than one values to this attribute, browser will select
automatically matching font.
Demo of HTML
</TITLE>
</HEAD>
</HTML>
3. TITLE Tag
The content of this tag is displayed is the Title bar of any web browser window. It should be
unique and descriptive because it is used by search engines as a search criterion for any
information. In the absence of this tag, web browser displays the entire path of HTML file.
Example:
<HTML>
<HEAD>
<TITLE>
Demo of HTML
</TITLE>
</HEAD>
</HTML>
4. Main body of text using BODY Tag
This body tags is basically a block level tags that specify what the web browser should display in
the web browser window. Styles and formatting are applied to the content using tags, such as
heading tags, paragraph tags and font tags. Most of the tags are a part of the <BODY> tag. Some
examples of tag that are the part of the <BODY> tag are:
<H1> Heading Levels
<BR> Break Line
<HR> Horizontal Rule
<FORM> Insert Forms
<P> Paragraph
Various attributes of Body tag are:
1 BGCOLOR Changes the background color that is specified within tag. For
Example: <BODY BGCOLOR = “GREEN”>
2 BACKGROUND Change the background of web page with specific image. For
example: <BODY BACKGROUND = “COMPUTER.GIF”
3 TEXT It helps you display the contents of text with a specific color. For
example: <BODY TEXT = “READ”>
4 LINK Will set the color for the normal blue colored hyperlinks that you
see on web page by default. It will only change the color of the
unvisited hyperlink.
5 VLINK Will set the color of visited hyperlinks. By default Purple Color.
6 ALINK Will set the activated link color. This is the color that you see
when the mouse is pressed on a link but not released. By default
Red color.
7 STYLE Recent browser software uses this attribute to specify background
image. URL reference is enclosed within in the URL() keyword.
2. Layout Tags
These tags add white spaces to web page to display contents in a better look or design and it I
equivalent to <Ente> key in word processing documents. It supports following features:
Helps in displaying the contents of web pages into logical section.
It affects the structure, spacing and layout of a web page.
Layout tags consist of following tags:
1. Break Tag
2. Paragraph Tag
<BR> Tag (Line Break)
The <BR> tag inserts a line break into a text flow. When the text needs to starts from a new lines
and not continue on the same line, the <BR> tag should be used. It has no ending tag.
Example:
Write a program for illustration of 'Line Break tag'.
<HTML>
<HEAD>
<TITLE>
DEMONSTRATION OF ATTRIBUTES
</TITLE>
</HEAD>
<BODY TEXT="NAVY"LINK="BLUE"ALINK="RED"VLINK="BLUE" BGCOLOR="GREEN">
<P>THIS IS THE DEMO TEXT </P>
<BR>
<BR>
<A HREF="E:\BCAFINAL\HTM\PRG1.HTML">SHOW</A>
</BODY>
</HTML>
Example:
Write a program for illustration of 'Paragraph Tag'.
<HTML>
<HEAD>
<TITLE>
DEMONSTRATION OF ATTRIBUTES
</TITLE>
</HEAD>
<BODY>
<P ALIGN="RIGHT">
It is called the relative address because it is "relative to our present location" which in the above
example.
</P>
<!--Illustration of comment-->
</BODY
</HTML>
The logical styles inform the browser what kind of text to present. The browser takes care of how
to present it. For example consider the <em> tag. This tag tells that emphasis must be given. The
browser takes care of how to present it so that it gets the emphasis required. Lists of the logical
style tags are given below:
<CITE>---</CITE> This tag is used for citation or references to other sources or
writing information regarding the authorship. This element
can be used for writing short quotations. Internet Explorer
rendered text within these elements in Italics.
<CODE>--</CODE> Used for source code example. Internet Explorer renders this
text in small font. It is normally used for writing source code
example.
2. Physical Styles
The physical styles format tags implicitly informs the browser how the characters must be shown
bold, italic, etc. Physical style tags are given below with its meaning.
<B> …. </B> The <B> tag Boldfaces of characters or segments of text i.e.
enclosed between the tag </B> and its corresponding </B>
end tag.
<BIG>---</BIG> <BIG> Tag: It renders tags between it and its </BIG> tag one
Boldface
A physical tag <B> i.e. Boldface is used to specify that the selected text, within a container tag,
to be displayed in boldface. For example,
<BODY>
Today there is an <B> Important Meeting </B> at 4.00 P.M.
</BODY>
Output: Today there is an Important Meeting at 4.00 P.M.
Italics
A physical tag <I> i.e. italic tag is used to specify that the selected text, within a container tag, to
be displayed in italic. For example,
<BODY>
Venue of Metting <I> Subhedar Hall</I>
</BODY>
Output: Venue of Meeting Subhedar Hall
Underline
A physical tag <U> i.e. Underline tag is used to specify that the selected text, within a container
tag, to be displayed with an underline. For example,
<BODY>
Bring <U> an Important Document </U> for Meeting
</BODY>
<BODY>
A<SUP>2</SUB>b
</BODY>
Output: a2b
TYPEWRITER
A physical container tag <TT> is used to display text or word in mono-typewriter font style,
<BODY>
<TT> The text appears in small type writer font</TT>
</BODY>
Difference between Logical and Physical Style
Sr.No. Physical Style Logical Style
1 Physical style tags mark the specific It is used for showing importance.
appearance of a section of text.
2 Supported by all Browsers Some Browser doesn’t support any effect
of this style.
3 A physical character tag controls how It do not specify format and leave the
to format the text. rendering of the style up to the browser
either in its default or configurable
settings.
4 A physical style would not convey any Logical style would be used to convey
meaning. some meaning.
5 All browsers will display the Some browser will display the logical tag
formatting with same effect. effect in different way.
6 Browser independent. Browser dependent.
7 Ex. This<B> Bold <?B> output. Ex. This <EM> Emphasis </EM> output.
Pre-Format Text
The <PRE> tag and its required </PRE> defines a segment inside which the browser render a
block of text without any formatting. This displays the text in exactly same format as the
character and line spacing format define in source HTML document.
Address
The address element is used to display an address in HTML. In address you can specify different
types of information such as Signature of developer or name of organization who created the web
page within <ADDRESS> and </ADDRESS>. This tag automatically indents the text and
formats it in italic.
Example:
<HTML>
<BODY>
<ADDRESS>
R.T.M. Nagpur University, Nagpur<BR>
Opposite MaharajBag <BR>
Sitabuldi, Nagpur – 442401(M.S.)
</ADDRESS>
</BODY>
</HTML>
FONT Tag
Using this tag you can control the font, font size and color of the text using attribute FACE,
SIZES and COLOR.
Font Face
This tag is used to change the whole face of the text. Using the <font face> tag you can specify
the font name between quotation marks. When the browser encounters a page with <font fact> it
searches the system for the given font names and then displays the text in that font. You must
also remember that fonts have different names on different system. So if you are using this tag
then it is safe to give two or three font names as in case the browser fails to find the first one, it
will display the text in another font.
Syntax : <FONT FACE = “value1” [“value2”], [“value3”]…..>
<FONT FACE= “Arial”, “Times New Roman”, “Helvetica”, “Comic same ms”> this is the font
face section </FONT>
Font Size
Just as you can change the font face, you can also manipulate font sizes. You can use the <font
size> tag on one word or a whole paragraph.
Syntax: <FONT SIZE=N>Text</FONT>
The value for size can be from 1 to 7 where number 3 is the default font size. Font size is also
defined by using the relative value to the default size of 3. This is done by using the + or –
symbol.
Syntax: <FONT SIZE = +VALUE>
Changing font size using the relative value.
Example: <FONT SIZE=+3>. If current font is suppose 3 then the text that it follows will be
displayed in the font size 7(=4+3).
<HTML>
<BODY>
<P><FONT FACE= “TIMES NEW ROMAN SIZE=1>Keyboard</FONT></P>
<P><FONT SIZE=2>Mouse</FONT></P>
<P><FONT SIZE=3>Light Pen</FONT></P>
<P><FONT SIZE=4>Optical Mark Reader</FONT></P>
<P><FONT SIZE=5>Scanner</FONT></P>
<P><FONT SIZE=+3>Printer</FONT></P>
<P><FONT SIZE=7>Plotter</FONT></P>
</BODY>
</HTML>
Font Color
User can use the Color Attribute to specify the color of the enclosed text. Syntax to represent
Color attribute is “
<FONT COLOR= “VALUE”>
One can specify the name of color such as RED, GREEN, BLUE, YELLOW, WHITE, LIME etc or
can specify the color using a hexadecimal value that is basically a combination of three primary
colors called Red, Green and Blue in the format #RRGGBB. For example, #000000 represent Black,
#FFFFFF represent white. Thus 00 and FF indicate the decimal value 0 to 255 respectively. Thus we
can specify 256 colors.
Example:
Example:
<FONT COLOR = “RED”>HELLO </FONT>
OR
<FONT COLOR = “FF0000”>HELLO </FONT>
Lists
List is collection of similar items or sequence you steps. In general, when you visit the restaurant,
waiter shows you a menu which shows list of items available in different way or format. HTML
offers authors several mechanism for specifying lists of information. All list must contain one or
more list elements. Inside a list item you can put text, line breaks, images, links other formatting tags
for better appearance and presentation. Lists are created using either <UL>, <OL> or <DL> tags.
Types of lists supported by HTML are:
Unordered Information List
Ordered Information Lists
Definition Lists
Unordered List:
Unordered list are a type of list where the points are not numbered. Instead there are three types of
bullets that can be used. The <UL> tag is used to mark the beginning of unordered list. The list is
closed by using </UL> tag. The points in the list are indicated using the <LI> tag. It is not
compulsory to close the <LI>tag but it always better to closed it using the </LI>. <UL> tag has
following attribute.
The use of TYPE attribute will allow you to change the bullet to be displayed. The TYPE attribute
text the following three values circle, square, disk.
Ordered List:
Ordered list are a numbered list and can have numbers instead of bullets that unordered list has. The
tag used to mark the beginning of ordered list is <OL>. The tag used to mark the end of it is </OL>.
It can have attributes: TYPE and START
TYPE:
This attribute can take the following values 1, a, A, i, I. If the value assign to type is '1', then the
ordered list has no. starting from 1. If 'a' is assigned then the list is ordered as a, b, c,..., z . Similarly
'A' is numbers list as A, B, C,..., Z. 'I' or 'i' uses roman numerical to number the list.
START:
This attribute of <OL> tag decides where the numbering will start from. By default it starts from '1'.
This can be changed through the START attribute. The numbering will start from number which is
assigned to start attribute. Even if the type is '0' or 'I' etc, the START attribute will always accept an
integer value. If the type is 'A' and if you want numbering to start from'0' then you have to set value
of start to 4.
The <LI> tag can have following attribute:
TYPE:
It has same values as the type attribute mentioned above it is used to change the type of current list
item.
VALUE:
This attribute is used to change the type of not only current list item but also list item following it.
<HTML>
<HEAD>
<TITLE>
Ordered List
</TITLE>
</HEAD>
<BODY>
<OL>
<LI>NAGPUR UNIVERSITY</LI>
<OL TYPE="A">
<LI VALUE=1>SCIENCE</LI>
<OL TYPE="i">
<LI>C.J.PATELCOLLEGE, TIRRORA</LI>
<LI>J.M.PATELCOLLEGE, BHANDARA</LI>
<LI>M.M.PATELCOLLEGE, SAKOLI</LI>
<LI>D.B.SCIENCE COLLEGE, GONDIA</LI>
</OL>
<LI>COMMERCE</LI>
<OL TYPE="i">
<LI>C.J.PATELCOLLEGE, TIRRORA</LI>
<LI>J.M.PATELCOLLEGE, BHANDARA</LI>
<LI>M.M.PATELCOLLEGE, SAKOLI</LI>
<LI>N.M.D COLLEGE, GONDIA</LI>
</OL>
<LI>ARTS</LI>
<OL TYPE="i">
<LI>C.J.PATELCOLLEGE, TIRRORA</LI>
<LI>J.M.PATELCOLLEGE, BHANDARA</LI>
<LI>M.M.PATELCOLLEGE, SAKOLI</LI>
<LI>N.M.D COLLEGE, GONDIA</LI>
</OL>
</OL>
<LI > AMARAWATI UNIVERSITY</LI>
<LI> PUNE UNIVERSITY</LI>
</OL>
</BODY>
</HTML>
<BODY>
<UL>
<LI>NAGPUR UNIVERSITY</LI>
<UL TYPE=square>
<LI>SCIENCE</LI>
<UL TYPE=circle>
<LI>C.J.PATELCOLLEGE, TIRRORA</LI>
<LI>J.M.PATELCOLLEGE, BHANDARA</LI>
<LI>M.M.PATELCOLLEGE, SAKOLI</LI>
<LI>D.B.SCIENCE COLLEGE, GONDIA</LI>
</UL>
<LI>COMMERCE</LI>
<UL TYPE=circle>
<LI>C.J.PATELCOLLEGE, TIRRORA</LI>
<LI>J.M.PATELCOLLEGE, BHANDARA</LI>
<LI>M.M.PATELCOLLEGE, SAKOLI</LI>
<LI>N.M.D COLLEGE, GONDIA</LI>
</UL>
<LI>ARTS</LI>
<UL TYPE=circle>
<LI>C.J.PATELCOLLEGE, TIRRORA</LI>
<LI>J.M.PATELCOLLEGE, BHANDARA</LI>
<LI>M.M.PATELCOLLEGE, SAKOLI</LI>
<LI>N.M.D COLLEGE, GONDIA</LI>
</UL>
<LI> AMARAWATI UNIVERSITY</LI>
<LI> PUNE UNIVERSITY</LI>
</UL>
</BODY>
</HTML>
Definition List
It consists of term and followed by its definition. It is also referred as Glossary list of Dictionary list.
An definition list created by using the <DL>…</DL> tags followed by the <DT> (Definition Terms)
tag and the <DD> (Definition Description) tag. Here <DT> and <DD> tag pair indicates a term and
its definition and must appear in the same order. Definition lists are unordered list. Here
The <DL> tag is a pair tag.
<DT> and <DD> is a singular tag.
Example:
<HTML>
<HEAD><TITLE>Demo of Definition List</TITLE></HEAD>
<BODY>
<H3>Computer Toy</H3>
<DL>
<DT>Lower Cost
<DD>Product costs significantly less compare to any other company
product
Special Characters:
There are times when you have to display certain special characters on the screen like ©, ® etc.
These characters are not available on the keyboard. So how will they be printed on the screen and
also any space in the HTML code are reduced to one. So how do we show more than one space in
the web page? These were UNICODE come into the picture. Here is a list of a few of UNICODES.
Linking
Instead of creating single documents web page with lot of information one can breakup this
information into parts and store them in a separated documents and access them by means of link.
Thus linking can be defined as “A mechanism to connect related web page file”. It can be
achieved by means of formatting a given text (hypertext) and which helps to link another web page.
This process is known as hyperlink. Thus hyperlink is a process of linking source web page with that
of target web page. One must specify the Path or URL of target web page in source web page. A
hyperlink can be created in HTML using anchor tag <A>…</A>.
Advantages of Linking to other Document
1. Reuse the web page with other HTM documents.
2. Reduce the time and cost for creating web page which already exists.
3. Navigating various web pages.
4. Linking can be made bidirectional.
Appearance of Hyperlink
Browser distinguishes hyperlinks from normal text by following features.
1. By default every hyperlinks appear in Blue color.
2. Hyperlink Text/Image is underlined.
3. When the mouse is placed over hypertext the mouse shape is changed to hand.
Images can be made as a hyperlink by including <IMG> tag within anchor pair tags called <A>
and </A>.
Pathname (URLs)
Pathnames refer to the URL (Uniform Resource Locator) which is written in the text field of the web
browser running on a client machine. These URLs are of two types.
1. Relative
2. Absolute
Relative URLs
Relative URLs are relatve to their base element i.e. relative to current page. If the current page is
visible during browsing then the web browser will know that hyperlink files are also stored in that
director.
Example:
<A HREF = “table.html”> View Next Table </A>
If the current page says file table1.html visible in the browser as http://www/web.com/table1.html
then the browser will know that the hyperlink in this HTML points to
http://www/web.com/table2.html.
Absolute URLs
This kind of pathnames does not rely on relative to anything. Here one must specify a page’s full
web address. For example,
http://www.spcollegechandrapur.com/mca.html. It refers to the mca.htm page in the mca directory of
the www.spcollegechandrapur.com server.
Difference between Absolute and Relative Path
Generic Paths/ Absolute Paths Relative Paths
It is referred to as Absolute paths because they Relative paths change depending upon what
refer to the very specific location. page the links are located on.
One must also specify the domain name. Not necessary to specify domain name.
Absolute paths are usually used while It is generally used in referering user web
referencing web site. document stored in a folder.
The absolute path is the “full path”. Absolute The relative path is the “partial path”.
path contains the exact path.
Absolute path always begins with a / (slash). It specifies location relative to your current
working directory i.e. relative path do not
begin with /.
An absolute path contains full path, contains the Relative path contains only the path relatively
root directory and all other sub directories. to a certain folder. The path may appear as
Absolute path may appear as images/sunset.jpg.
/home/user/picture/images/sunset.jpg.
Used for referring server side web page and Usually used for referring client side web page
known as Server Relative URLs. and known as Document Relative URLs.
They are shorter and saves lot of time while It is usually lengthy and hence more time to
writing. type.
If you move your web pages to another directory If you move your all web pages to another
all relative address will remain valid. directory all absolute path become invalid and
known as broken links. In short, one must
change all paths pointing to new directory.
<HTML>
<HEAD>
<TITLE>
JM Software
</TITLE>
</HEAD>
<BODY>
<UL>
<LI>Software Development</LI>
<LI>Marketing</LI>
<LI> <A HREF="Support.html">Customer Support</A></LI>
</UL>
</BODY>
</HTML>
<HTML>
<HEAD>
<TITLE>
LINKING TWO OR MORE WEB PAGES.
</TITLE>
</HEAD>
<BODY>
<P>
<H3> Master Software</H3>
<H3><A HREF="BCA2.HTML">CCI Software</A></H3>
</P>
</BODY>
</HTML>
<HTML>
<HEAD>
<TITLE>
SUB FILE
</TITLE>
</HEAD>
<BODY>
<P>
CCI Software Company NAGPUR</A></H3>
</P>
</BODY>
</HTML>
<LI>BCA1 11000</LI>
<LI>BSC 7000</LI>
</UL>
</P>
<P><A NAME="BCA">COURSE DETAILS </A></P>
<P>
WE OFFER SEVERAL COURCES AS PER STUDENT REQUIREMANTS <BR>
WE PROVIDE OTHER ACTIVITIES AS PER STUDENTS DEMANDS
</P>
</BODY>
</HTML>
index.html
http:///www.browsers.com/
Software Development
Marketing
Customer Support
TABLE
Basically, a table is a two dimensional matrix consisting of rows and columns. HTML helps you to
present the information in a tabular form i.e. in the form of rows and columns. The basic elements of
table is cell (intersection of Rows and Column) or the grid. In a table, cells are arranged from left to
right and from top to bottom. By default each cell in a table is spread across one row and one
column. One can use other HTML formatting tags with table to improve its appearance for better
presentation. One can create table in HTML using tag <TABLE>.
Table Usage
In following situation displaying data in a tabular format is useful:
Express Relationship: It is usually used to display the relationship among columns within
table. For example, Roll_no, Name and Address show that it constitutes student information.
Tabular Form: Tables enable the show or display information in a tabular form rather
simply a textual form.
Control Layout: It helps a web designer to control the layout of text and position a group of
images that is usually used in news-paper publication.
Features of HTML Tables
1. One can change the height and width of single cell.
2. Span table cells across rows.
3. Span table across columns.
4. All columns data are aligned properly.
5. Can provide the spaces between cells.
6. Inserting image within table cell.
7. Hyperlink table cell item.
8. Nesting Tables etc.
TABLE Tag
All table related tags are included between the pair tags <TABLE> … </TABLE>. Each row of the
table is described between the <TR> … </TR> tags while each column of a table is described
between pair tags <TD> … </TD>. Here,
<TR> tag specifies table row and is a non-empty or pair tag.
HTML - Forms
Forms are used to collect all the input information from the user for further processing. For
providing such input, the form are created using controls like textboxes, click buttons, radio buttons,
check boxes, list boxes etc for entering or selecting data via GUI (Graphical User Interface) controls.
A form is the physical carrier of data and information and it also carries the authority for action. One
may have more than one form in the document to collect related information from each form.
Generally form are classified as,
Registration forms
Subscription forms
Response forms
Ordered Entry forms
Complaint form etc.
After completion of data entry one must submit the data for further processing using say SUBMIT
button. This helps browser tosend the data to the web server to process using JavaScript. VbScript,
ASP, JSP, PERL, CGI program etc. At then end it must acknowledge user by means of some
response. Thus forms are useful for:
Interacting with user on the web to gather necessary data and hence known as user interface.
Upload this data from user to server i.e. data filled by user becomes database for web page
designer.
Principle guidelines for Form design
A form design is a highly intuitive human computer interaction method whereby data fields are
formatted in a manner similar to paper based forms. Form interaction is effective for both the input
and presentation of information and hence one should design it very effectively. The general
considerations of form design are given below:
1. Order of data items shuld be proper and must be in the same sequence as that of source
documents i.e. screen should simulate the paper document.
2. Forms title, Label title, commands button caption should be meaningful.
3. Ease of data entry.
4. Highlighting the important things by means of Bold, Blinking, Underline, etc.
5. Size of form should fit within window.
6. Use proper color, sound, menu (popup, pushdown, cascading, iconic, menu bars etc). Dialog
box, function keys and icons to different part of forms of the system according to requirement.
7. Balanced layout between screens and spacing among different fields or labels.
8. Easy navigation by showing how to move forward and backward.
9. Whenever there is a need of compromise then sacrifice decorations but retain the clarity.
The HTML <form> tag is used to create an HTML form and it has following syntax −
<form action = "Script URL" method = "GET|POST">
form elements like input, textarea etc.
</form>
Form Attributes
Apart from common attributes, following is a list of the most frequently used form attributes −
1 action
Backend script ready to process your passed data.
2 method
Method to be used to upload data. The most frequently used are GET and POST methods.
3 target
Specify the target window or frame where the result of the script will be displayed. It
takes values like _blank, _self, _parent etc.
4 enctype
You can use the enctype attribute to specify how the browser encodes the data before it
sends it to the server. Possible values are −
application/x-www-form-urlencoded − This is the standard method most forms use in
simple scenarios.
mutlipart/form-data − This is used when you want to upload binary data in the form of
files like image, word file etc.
Checkboxes Controls
Radio Box Controls
Select Box Controls
File Select boxes
Hidden Controls
Clickable Buttons
Submit and Reset Button
Text Input Controls
There are three types of text input used on forms −
Single-line text input controls − This control is used for items that require only one line of user
input, such as search boxes or names. They are created using HTML <input> tag.
Password input controls − This is also a single-line text input but it masks the character as soon
as a user enters it. They are also created using HTMl <input> tag.
Multi-line text input controls − This is used when the user is required to give details that may
be longer than a single sentence. Multi-line input controls are created using
1 Type
Indicates the type of input control and for text input control it will be set to text.
2 Name
Used to give a name to the control which is sent to the server to be recognized and get the
value.
3 Value
This can be used to provide an initial value inside the control.
4 Size
Allows to specify the width of the text-input control in terms of characters.
5 Maxlength
Allows to specify the maximum number of characters a user can enter into the text box.
Attributes
Following is the list of attributes for <input> tag for creating password field.
1 Type
Indicates the type of input control and for password input control it will be set
to password.
2 Name
Used to give a name to the control which is sent to the server to be recognized and get the
value.
3 Value
This can be used to provide an initial value inside the control.
4 Size
Allows to specify the width of the text-input control in terms of characters.
5 Maxlength
Allows to specify the maximum number of characters a user can enter into the text box.
Attributes
Following is the list of attributes for <textarea> tag.
1 name
Used to give a name to the control which is sent to the server to be recognized and get the
value.
2 rows
Indicates the number of rows of text area box.
3 cols
Indicates the number of columns of text area box
Checkbox Control
Checkboxes are used when more than one option is required to be selected. They are also created
using HTML <input> tag but type attribute is set to checkbox..
Example
Here is an example HTML code for a form with two checkboxes −
<html>
<head>
<title>Checkbox Control</title>
</head>
<body>
<form>
<input type = "checkbox" name = "maths" value = "on"> Maths
<input type = "checkbox" name = "physics" value = "on"> Physics
</form>
</body>
</html>
Attributes
Following is the list of attributes for <checkbox> tag.
1 type
Indicates the type of input control and for checkbox input control it will be set to checkbox..
2 name
Used to give a name to the control which is sent to the server to be recognized and get the
value.
3 value
The value that will be used if the checkbox is selected.
4 checked
Set to checked if you want to select it by default.
Attributes
Following is the list of attributes for radio button.
1 type
Indicates the type of input control and for checkbox input control it will be set to radio.
2 name
Used to give a name to the control which is sent to the server to be recognized and get the
value.
3 value
The value that will be used if the radio box is selected.
4 checked
Set to checked if you want to select it by default.
Attributes
Following is the list of important attributes of <select> tag −
1 name
Used to give a name to the control which is sent to the server to be recognized and get the
value.
2 size
This can be used to present a scrolling list box.
3 multiple
If set to "multiple" then allows a user to select multiple items from the menu.
No
1 value
The value that will be used if an option in the select box box is selected.
2 selected
Specifies that this option should be the initially selected value when the page loads.
3 label
An alternative way of labeling options
Attributes
Following is the list of important attributes of file upload box −
1 name
Used to give a name to the control which is sent to the server to be recognized and get the
value.
2 accept
Specifies the types of files that the server accepts.
Button Controls
There are various ways in HTML to create clickable buttons. You can also create a clickable button
using <input>tag by setting its type attribute to button. The type attribute can take the following
values −
1 submit
This creates a button that automatically submits a form.
2 reset
This creates a button that automatically resets form controls to their initial values.
3 button
This creates a button that is used to trigger a client-side script when the user clicks that
button.
4 image
This creates a clickable button but we can use an image as background of the button.
Example
<html>
<head>
<title>File Upload Box</title>
</head>
<body>
<form>
<input type = "submit" name = "submit" value = "Submit" />
<input type = "reset" name = "reset" value = "Reset" />
<input type = "button" name = "ok" value = "OK" />
<input type = "image" name = "imagebutton" src = "/html/images/logo.png" />
</form>
</body>
</html>
then the value of hidden control will be sent to the web server and there it will decide which page
will be displayed next based on the passed current page.
Example
<html>
<head>
<title>File Upload Box</title>
</head>
<body>
<form>
<p>This is page 10</p>
<input type = "hidden" name = "pagename" value = "10" />
<input type = "submit" name = "submit" value = "Submit" />
<input type = "reset" name = "reset" value = "Reset" />
</form>
</body>
</html>
Introduction to CSS
CSS stands for Cascading Style Sheet. CSS describes how HTML elements are to displayed on
screen, paper, or in other media. It saves a lot of work. It can control the layout of multiple web
pages all at once. CSS allows you to control the look and feel of several pages by changing a single
source. External style sheets are stored in CSS files.
CSS was developed by W3C in 1996 for a rather simple reason. HTML element was not designed to
have tags that would help format the page. You were only supposed to write the markup for the web
page.
Advantages
CSS saves time
You can write CSS once and reuse the same sheet in multiple HTML pages.
Easy Maintenance
To make a global change simply change the style, and all elements in all the web pages will be
updated automatically.
Search Engines
CSS is considered a clean coding technique, which means search engines won’t have to struggle
to “read” its content.
Superior styles to HTML
CSS have a much wider array of attributes that HTML, so you can give a far better look to your
HTML page in comparison to HTML attributes.
Offline Browsing
CSS can store web applications locally with the help of an offline cache. Using this we can view
offline websites.
Faster Page Speed
More code means slower page speed. And CSS enables you to use less code. CSS allows you to
use one CSS rule and apply it to all occurrences of a certain tag within an HTML document.
Better User Experience
CSS not only makes web pages easy on the eye, but it also allows for user-friendly formatting.
When buttons and text are in logical places and well organized, user experience improves.
Quicker Development Time
With CSS, you can apply specific formatting rules and styles to multiple pages with one string of
code. Once cascading style sheet can be replicated across several website pages. If, for instance,
you have product pages that should all have the same formatting, look, and feel, writing CSS
rules for one page will suffice for all pages of that same type.
Easy Formatting Changes
If you need to change the format of a specific set of pages, it’s easy to do so with CSS. There’s
no need to fix every individual page. Just edit the corresponding CSS stylesheet and you’ll see
changes applied to all the pages that are using that style sheet.
Compatibility across Devices
Responsive web design matters. In today’s day and age, web pages must be fully visible and
easily navigable on all devices. Whether mobile or tablets, desktop, or even smart TV, CSS
combines with HTML to make responsive design possible.
Overview of CSS
CSS stands for Cascading Styel Sheets. It is the language for describing the presentation of Web
pages, including colors, layout, and fonts, thus making our web pages presentable to the users.
CSS is designed to make style sheets for the web. It is independent of HTML and can be used with
any XML based markup language. Now let’s try to break the acronym”
Cascading: Falling of Styles
Style: Additing designs/|Styling our HTML tag.
Sheets: Writing our style in different documents.
CSS History
1994: First Proposed by HakonWium Lie on 10th October.
1996: CSS was published on 17th November with influencers Bert Bos. Later he became co-author of
the CSS.
1996: CSS became official, CSS was published in December.
1997: Created CSS level 2 on 4th November.
1998: Published on 12th May.
CSS Editors
Some of the popular editors that are best suited to write CSS code are as follows:
1. Atom
2. Visual Studio Code
3. Brackets
CSS Versions
Cascading Style Sheet (CSS) is a separate language with its syntax, which enables you to lay out web
pages exactly as you want them. As HTML grew, it came to encompass a wider variety of stylistic
capabilities to meet the demands of web programmers. By the end of 1996, Cascading Style Sheets
was ready to become official, and the CSS level 1 recommendation was published in December,
which is considered the first version of CSS. Each level of CSS builds upon the last, typically adding
new features and typically denoted as CSS level 1, CSS level 2, CSS level 3 and CSS level 4.
CSS Level 1
CSS Level 1 (CSS1) was officially released in 1996 and included properties for addition 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. Unfortunately, the lack of
dependable web browser support prevented the popularity of CSS Level 1 for several years.
CSS Level 2
CSS Level 2 (CSS2) specification was developed by W3C and published as a recommendation in
1998. Its most notably added properties for positioning that allowed CSS to be used for page layout.
It also introduced styles for other media types and more sophisticated methods for selecting elements
for styling.
CSS Level 3
The earlist CSS Level 3 (CSS3) drafts were published in 1999. CSS3 adds presentation style
properties, allowing you to effectively build presentations from Web documents. CSS Level 3 is
divided into several separate documents called modules. Due to modularization, different modules
have different stability and statuses.
CSS Level 4
There is no single CSS4 specification and there is no standard named CSS4. But a few levels 4
modules exist such as Image Values, Backgrounds & Borders, Selectors, etc. which build on the
functionality of a preceding level 3 module. The level 4 modules can collectively be referred to as
CSS level 4. There is only a CSS standard, and each module can level up independently.
Creation of CSS
CSS is one of three cornerstone technologies used on the web (the other two are HTML and
JavaScript).
CSS is used as a way of defining how HTML code is going to look on a website. Whereas HTML is
used to create content, including written text, CSS alters the way a web page will look.
So, depending on the data they want to display, a developer might choose to have a page with tabs
running across the top of the page or along the side. Or, another developer might choose to use
headings and subheading style to ensure that the words leap off the page or, change or revamp an
existing webpage entirely.
Why do we need CSS?
Firstly, using CSS ensures that your web pages are consistent. Imagine a website with 100s of pages,
now imagine having to input the code to define heading sizes, layout, and other display data and mix
that all in with the content each time you wanted to produce a new page. Also, imagine having a site
with 100s of pages and being able to change just one of them while keeping all the rest the same –
CSS also makes that a possibility. Using CSS delivers consistency where it is needed but is flexible
enough to enable you to make changes to individual pages or sections. Using CSS allows a user to
specify:
Fonts
Color of text and links
User colors in the text’s background
Where and how boxes within the content look and are placed.
CSS also improves user accessibility, efficiency, and flexibility and ensures browser
compatibility.
Who Invented CSS?
According to Wikipedia, the birth of CSS is largely credited to Norwegian HakonWium Lie, who
back in 1994 sought to create a universal standardized style sheet for the World Wide Web.
Maintenance of CSS
Cascading Styel Sheets, or CSS in short, is used when we need to apply styles to our websites. The
use of CSS makes it easier for us to make a website presentable. It separates the structure, which is
made up of an HTML document, from the presentation, which implies the part which the user sees
and interacts with.
CSS Syntax
A CSS Syntax rule consists of a selector, property, and its value. The selector points to the HTML
element where the CSS style is to be applied. The CSS property is separated by semicolons. It is a
combination of the selector name followed by the property:value pair that is defined for the specific
selector.
A CSS rule set consists of a selector and a declaration block.
The Selector indicates the HTML elements you want to style. The declaration block contains one or
more declarations separated by semicolons. Each declaration includes a CSS property name and a
value, separated by colon. A CSS declaration always ends with a semicolon, and declaration blocks
are surrounded by curly braces.
A Property is a type of attribute of HTML element. It could be color, border etc. Values are
assigned to CSS properties.
Example:
In this example all <p> elements will be center-aligned, with a red text color:
p{
color:red;
text-align:center;
}
Here p is a selector in CSS, color is a property, and red is the property value, text-align is a
property, and center is the property value.
Internal CSS
An internal CSS is used to define a style for a single HTML page. An internal CSS is defined in the
<head> section of an HTML page, within a <style> element.
Example:
<HTML>
<HEAD>
<TITLE>
Internal CSS
</TITLE>
<STYLE>
h1{color:red;}
p{color:green;}
</STYLE>
</HEAD>
<BODY>
<h1>This is Heading1</h1>
<p>This is Paragraph1</p>
<h1>This is Heading2</h1>
<p>This is Paragraph2</p>
</BODY>
</HTML>
Output:
External CSS
External style sheet is used to define the style for many HTML pages. With an external style sheet,
you can change the look of an entire web site, by changing one file.
To use an external style sheet, add a link to it in the <head> section of the HTML page:
Example: Prog004.html
<HTML>
<HEAD>
<TITLE>
External CSS
</TITLE>
<LINK rel="stylesheet" href="CSSProg1.css">
</HEAD>
<BODY>
<h1>This is External CSS Heading1</h1>
<p>This is External CSS Paragraph1</p>
<h1>This is External CSS Heading2</h1>
<p>This is External CSS Paragraph2</p>
</BODY>
</HTML>
Example: CSSProg1.css
h1{color:blue;}
p{color:red;}
Output:
Font Properties
Property Description Values Examples
Font-family Specifies the font Family-name, generic- P{font-family:Times
family for text. family, inherit New Roman}
Font-size Specifies the font size xx-small, x-small, P{font-size:15px}
of text. small, medium, large,
x-large, xx-large,
smaller, larger, length,
%, inherit.
Font-style Specifies the font style Normal, italic, oblique, P{font-style:normal}
for text. inherit
Font-variant Specifies whether or Normal, small-caps, P{font-variant:small-
not a text should be inherit caps}
displaed in a small
caps font.
Font-weight Specifies the weight of Normal, bold, bolder, P{font-
a font. lighter, 100, 200, 900 weight:normal}
</TITLE>
<STYLE>
H1{background-color:green; color:red; font-family:comic sans ms; }
P{color:blue}
</STYLE>
</HEAD>
<BODY>
<H1>Nagpur University</H1>
<P>The University was established before freedom. <br>This is one of the premier university
of India.</P>
</BODY>
</HTML>
Output:
Types of Selector
The CSS id Selector
The id selector uses the id attribute of an HTML element to select a specific element. The id of an
element is unique within a page, so the id selector is used to select one unique element. To select an
element with a specific id, write a hash (#) character, followed by the id of the element.
Example: The CSS rule below will be applied to the HTML element with id= “para”:
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>
Illustration of ID selector
</TITLE>
<STYLE>
#para{text-align:center;color:red;}
</STYLE>
</HEAD>
<BODY>
<h1 id="para">This is Heading 1</h1>
<h1>This is Heading 2</h1>
<p id="para">This is First Paragraph</p>
<p>This is Second Paragraph</p>
</BODY>
</HTML>
Output:
Output:
Example:
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>
Illustration of class selector specific
</TITLE>
<STYLE>
p.center{text-align:center;color:red;}
</STYLE>
</HEAD>
<BODY>
<h1 class="center">This is Heading 1</h1>
<h1>This is Heading 2</h1>
<p class="center">This is First Paragraph</p>
<p>This is Second Paragraph</p>
</BODY>
</HTML>
Output:
Grouping Selector
The grouping selector is used to select all the elements with the same style definitions. It is used to
minimize the code. Commas are used to separate each selector in grouping.
For example without group, the syntax will be:
b{color:blue;background-color:pink}
i{color:blue;background-color:pink}
u{ color:blue;background-color:pink}
It can be grouped as:
b,i,u{ color:blue;background-color:pink}
Above <b>, <i> and <u> tags will use the same style for formatting. In any of the selector is to be
given additional formatting that tag needs to be redefined.
Example:
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>
Illustration of Grouping Selector
</TITLE>
<STYLE>
b,i,u{color:blue;background-color:pink}
</STYLE>
</HEAD>
<BODY>
<b>This is First Line</b><br><br>
<i>This is Second Line</i><br><br>
<u>This is Third Line</u>
</BODY>
</HTML>
Output:
Descendant Selectors
Descendant Selector is one of the types of Combinators in CSS where the combinators combine two
selectors in such a way that if an ancestor element matches with the first selector, then the elements
matched by the second selector will be selected and these selectors use the descendant Combinator
are Descendant Selector. In simple words, the Descendant Selectors can be any selector having white
space in between the elements without using any combinators. Descendant is a manner to nest
anywhere within the DOM tree. This selector is used to select all the child elements of the specified
tag.
Syntax
first_selectorsecond_selector{
css properties: values;
}
The simple selector (first_selector) represents the ancestor element or parent element, and the second
simple selector (second_selector) represents the descendant element. We use white space between
these two to represent the descendant selector.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Descendant Selector
</title>
<style>
div p{
background-color:lightblue;
font-weight:bold;
}
</style>
</head>
<body>
<div>
This is Division 1
<p>This is the First Paragraph in the Division1</p>
Output:
Child Selectors
CSS Child Selector is defined as the CSS selector that selects only elements that are direct children
which is clearer than the contextual selector. This selector uses greater than the symbol “>” that
appears between two different selectors, and it is more specific than the descendant selector, which
helps to simplify the CSS style code. The second selector should be the immediate children of the
elements.
Syntax
Element1 > Element2 {
Style properties code…;
}
How does Child Selector work in CSS?
The working process is very simle. This child selector has two selectors to work with and is
separated by the “>” symbol. The first selector says that it is a parent element, and the second
selector says it is a child element with style properties.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Child Selector
</title>
<style>
div > p{
background-color:salmon;
color:azure;
font-size:10px;
padding:3px;
}
</style>
</head>
<body>
<div>
This is Division 1
<p>This is the First Paragraph in the Division1</p>
<p>This is the Second Paragraph in the Division1</p>
<div>
This is Division 2
<p>This is First Paragraph of Nested Division</p>
<p>This is Second Paragraph of Nested Division</p>
</div>
</div>
<p>This is Outside Paragraph</p>
</body>
</html>
Output:
Attribute Selectors
The CSS attribute selector is used when we want to style multiple HTML, elements that have the
same attribute or attribute values. It is a very convenient way to style multiple element by grouping
them based on simple attributes. The attribute selector selects all the elements that have a particular
attribute and sets the styling for all of them. The attribute selectors are by default case sensitive and
can be written in the square brackets [].
Types of Attribute Selectors
There are several types of attribute selectors, which are given below:
CSS [attribute] selector
CSS [attribute= “value”] selector
CSS [attribute ~= “value”]
CSS [attribute |= “value”]
CSS [attribute ^= “value”]
CSS [attribute $= “value”]
CSS [attribute *= “value”]
CSS [attributes] selector
The [attribute] selector selects all the elements that contain the name attribute and applies the CSS
properties to all of them at once. For example, the selector [class] will select and style all the
elements that have the same class name.
Syntax of [attributes] selector
HTML element[attribute]/[attribute] {
/*CSS properties */
}
Example: Applying [attribute] selector
In the given example, we have created four paragraphs using the <p> element. In the first and last
paragraph, we have specified the class attribute along with its value para then we have specified the
CSS properties using the CSS [attribute] selector for the <p> element using the class attribute.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Attribute Selector
</title>
<style>
[class]{
background-color: red;
color:black;
}
</style>
</head>
<body>
<p class="para">This is First Paragraph</p>
<p>This is Second Paragraph</p>
<p>This is Third Paragraph</p>
<p class="para">This is Fourth Paragraph</p>
</body>
</html>
Output:
Output:
Output:
Output:
Output:
Output:
Output:
Positioning in CSS
CSS helps to position the HTML elements. The position property defines how an element will be
positioned on a page. The element can be positioned using the top, bottom, left and right properties.
Syntax:
Selector{position:value;top:value;left:value;bottom:value;right:value}
Where values in positions are fixed, absolute, relative and values of top, bottom, left, right are in
pixels.
Positioning Methods
Positioning elements appropriately on the web pages is a necessity for a good layout design. There
are four types of positioning in CSS.
Static Positioning
A static positioned element is always positioned according to the normal flow of the page. HTML
elements are positioned static by default.
Static positioned elements are not affected by the top, bottom, left, right and z-index properties.
Example:
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>
Illustration of Static Positioning
</TITLE>
<STYLE>
div.static{
position:static;
border:3px solid#73Ad21;
}
</STYLE>
</HEAD>
<BODY>
<h2>Position Static</h2>
<p>A static positioned element is always positioned
according to the format flow of the page</p>
<div class="static">
This div element has position:static;
</div>
</BODY>
</HTML>
Output:
Relative Positioning
A relative positioned element is positioned relative to its normal position. In the relative positioning
scheme the elements box position is calculated according to the normal flow. Then the box is shifted
from this normal position according to the properties – top or bottom and/or left or right.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Relative Positioning
</title>
<style>
div.relative{
position:relative;
left:30px;
border:3px solid #73ad21;
}
</style>
</head>
<body>
<h2>Position Relative</h2>
<p>An element with position relative is positioned
Output:
Absolute Positioning
An absolute positioned element is positioned relative to the first parent element that has a position
other than static. If no such element is found, it will be positioned on a page relative to the ‘top-left’
of the browser window.
The box’s offsets further can be specified using one or more of the properties top, right, bottom, and
left.
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Absolute Positioning
</title>
<style>
div.relative{
position:relative;
width:400px;
height:200px;
border:3px solid #73ad21;
}
div.absolute{
position:absolute;
top:80px;
right:0;
width:200px;
height:100px;
border:3px solid #73AD21;
}
</style>
</head>
<body>
<h2>Position Absolute</h2>
<div class="relative">This div element has position
relative;
<div class="absolute">This div element has position
absolute.
</div>
</div>
</body>
</html>
Output
Fixed Positioning
Fixed positioning is a subcategory of absolute positioning. This property helps to put the text fixed
on the browser. The FIXED property forces an element into a fixed position relative to the browser
window. The fixed element does not move, even when the page is scrolled.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Fixed Positioning
</title>
<style>
div.fixed{
position:fixed;
bottom:0;
right:0;
width:300px;
border:3px solid #73ad21;
}
</style>
</head>
<body>
<h2>Position Fixed</h2>
<p>An element with position fixed is positioned
relative to the viewpoint</p>
<div class="fixed">This div element has position
fixed;
</div>
</body>
</html>
Output:
Float Property
Float is a CSS property written in CSS file or directly in the style of an element. This property
specifies how an element should float.
CSS Syntax
float:name[left|right]
Property Values
None The element doest not float. (will be displayed just where it occurs in the text).
This is default.
Left The element floats to the left of its container.
Right The element floats the right of its container.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Float Property
</title>
<style>
img{
float:left;
}
</style>
</head>
<body>
<h2>Float Property</h2>
<p><img src="Books.jpg" alt="Books" style="width:50px;height:50px;"></p>
<p>Fixed positioning is a subcategory of absolute positioning.
This property helps to put the text fixed on the browser.
The FIXED property forces an element into a fixed position
relative to the browser window. The fixed element does
not move, even when the page is scrolled.</p>
</body>
</html>
Output:
Display Property
The display property specifies the display behavior (the type of rendering box) of an element. This is
most important CSS property for controlling layout.
The display property specifies how an element is displayed. This property is used to define the
display of different parts of a web pages.
CSS Syntax
display:value;
Property Values
Values Description
Inline Displays an element as in inline element (like <span>). Any height and width
properties will have no effect.
Block Displays an element as a block element (line <p>). It starts on a new line, and
takes up the whole width of the browser window.
Inline-block Displays an element as an inline level block container. The element itself is
formatted as an inline element, but you can apply height and width.
None The element is completely removed.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Display Property
</title>
<style>
p{
display:inline;
}
</style>
</head>
<body>
<h2>Display Property</h2>
<p>Welcome to Nagpur University</p>
<p>Colleges</p>
<p>Gondia</p>
</body>
</html>
Output:
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Display Property
</title>
<style>
A{
display:block;background-color:pink;
}
</style>
</head>
<body>
<h2>Display Property</h2>
<p>Welcome to Nagpur University</p>
<p><A href="https://www.nmdcgondia.org">Visit to N.M.D. College, Gondia</A></p>
</body>
</html>
Output:
Question 2: Write a program using html5 with CSS to present school/college information.
Write name of the school/college with larger heading with blue color.
The color of remaining text should be red and background color pink.
Insert appropriate image related to the theme. Use float property to wrap the text aound it.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Solution of Problem Number 2
</title>
<style>
h1{
color:blue;
text-align:center;
}
body{
color:red;
background-color:pink;
}
</style>
</head>
<body>
<h1>N.M.D. College, Gondia</h1>
"Following is the reaming text."
<p><img src="College.jpg" alt="College Image" style="width:120px; height:100px;float:left">
Natwarlal Maniklal Dalal College, the pioneering
educational institution of Gondia Education
Society is committed to carry forward the
legacy bestowed upon us by the great visionary
late Shri Manoharbhai Patel. It visualizes to
impart quality education to the poorest of the
poor.
</p>
</body>
</html>
Output:
Question 5: Create Login screen using Html5 code and CSS as follows:
Create form which accepts username and password.
Give the heading with background color – Tomato. Heading should takes up the whole width
of the browser window. Also increases font size and set top morgin.
Make the provision to submit form data. Create button element of type “Submit” with
background color – black and text color – white. Also set the padding and increase font size.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Program for Solution of Problem Number 5
</title>
<style>
h2{
background-color: Tomato;
text-align:center;
display:block;
font-size:2.5Sem;
margin-top:0.8Sem;
}
.button{
color:white;
background-color:black;
padding:15px 100px;
font-size:20px;
}
</style>
</head>
<body>
<h2>Login Screen</h2>
<form>
User Name:<input type="text"><br><br>
Password :<input type="password"><br><br>
<center>
<button class="button">Submit</button>
</center>
</form>
</body>
</html>
Output:
Output:
Output:
<style>
body{
background-color: chocolate;
color:white;
}
</style>
</head>
<body>
<form>
User Name :<input type="text"><br><br>
Mode of Payment :<br><input type="radio" name="mop">COD<br>
<input type="radio" name="mop">Debit<br>
<input type="radio" name="mop">Credit<br>
<input type="radio" name="mop">PayTM<br><br>
<input type="submit"><input type="reset">
</form>
</body>
</html>
Output:
<html>
<head>
<title>
Solution of Problem Number 11
</title>
<style>
body{
background-color: chocolate;
color:white;
}
</style>
</head>
<body>
<form>
Customer Name :<input type="text"><br><br>
Milkshake :<select name="ms">
<option value="sb">Strawberry</option>
<option value="b">Banana</option>
<option value="mb">Mixed Berry</option>
</select><br><br>
<input type="submit"><input type="reset" value="Clear">
</form>
</body>
</html>
Output:
CSS Inclusion
There are the following four methods to use CSS stylesheet in HTML documents:
The internal style sheet – Embedded CSS
The external style sheet – External CSS
The inline style sheet – Inline CSS
The Imported CSS
In these methods, we use mostly External CSS and Inline CSS methods.
The Internal style sheet – Embedded CSS
The internal style sheet – Embedded CSS is written always in the HEAD element of the HTML
documents. The syntax in HTML document in written as follows:
<style type= “text/css” media= “all”>
Selector[property:value;]
</style>
Attribute:
Attributes associated with <style> elements are −
media Screen, tty, tv, projection, Specifies the device the document will be
Handheld, print, Braille, aural, displayed on. Default value is all. This is an
all optional attribute.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Embedded CSS Inclusion
</title>
<style type="text/css" media="all">
body{
background-color:linen;
}
h1{
color:maroon;
margin-left:40px;
}
</style>
</head>
<body>
<h1>This is Heading</h1>
<p>This is Paragraph</p>
</body>
</html>
Output:
Importing: The external style sheet, linked uses @import rules, here the @import keyword is used,
followed by the URL of the style sheet to which you want to import the style rules. The following
code shows an example of the @import rules.
<style type= “text/css”>
@import url[“new_stylesheet.css”]
H2{color:green;font-style:italic;}
</style>
Linking: The HTML link element is used to link a style sheet. This LINK element has the following
three attributes:
rel, href, type
<link rel= “stylesheet” href= “new_stylesheet.css” type= “text/css”>
Example:
CSS Program
h1,h2,h3{
color: #36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}
HTML Program
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of External CSS Inclusion
</title>
<link type="text/css" rel="stylesheet" href = "CSSProg2.css" media = "all">
</head>
<body>
<h1>This is Heading 1</h1>
<h2>This is Heading 2</h2>
<h3>This is Heading 3</h3>
<h4>This is Heading 4</h4>
</body>
</html>
Output:
Output:
Imported CSS
We can import additional CSS file inside another CSS declaration. The @import rule is used for this
purpose as it links a stylesheet in a document. This is generally used when one stylesheet is
dependent upond another. It is specified at the top of the document after @charset declaration inside
<head>.
Syntax: The syntax of the @import rule is as follows:
@import /*url or list of media queries */
The media queries can be compounded statements that may specify the behavior of the document in
different media.
Example:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
@import url(CSSProg1.css);
body{
background-color:honeydew;
}
</style>
</head>
<body>
<h1>This is Heading 1</h1>
<p>This is Demo Paragraph</p>
</body>
</html>
Output:
<html>
<head>
<title>
Illustration of Element CSS
</title>
<style>
div p{
background-color:green;
color:white;
}
</style>
</head>
<body>
<h2>Division 1</h2>
<div>
<p>This is Division 1 Paragraph</p>
</div>
<p>This is General Paragraph</p>
</body>
</html>
Output:
@Import Rule
CSS is the design backbone for the majority of web pages. It specifies how the items should be
shown on the screen. This is where the CSS @import at rule comes in.
The @import rule directs the CSS engine to import an external style sheet into another style sheet.
This enables the addition of style rules from one style sheet to another. This rule can be combined
with media queries to import a style sheet dependent on the type of device.
The @import style rule is useful since it can be used to avoid duplicating style rules and even import
specific styles dependent on the device that is accessed. The @import rule must be placed at the very
top of the style sheet.
@import “style.css”; /*using a string */
@import url(“example.css”); /*using a URL*/
where you have written the code then you can just override the style by using in-line CSS which has
the highest priority.
Order of Priority
inline stylesheet (highest) >><style>….</style>tags >> external style sheet(lowest)
Inline stylesheet: If you are using any Inline stylesheet, then it takes the highest priority, and
therefore, it will override any property defined in <style>…</style> tags or property defined in an
external style sheet file.
Style tag: If you are using any property defined in <style>…</style> tag, it will override the
property defined in any external style sheet file.
External CSS: If you are using any property defined in the external style sheet file then it takes the
lowest priority, and the property defined in this file will be applied only when the above two
properties are not applicable.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of CSS Rules Overriding
</title>
<link rel="stylesheet" href="CSSProg1.css">
</head>
<body>
<h1>This is Heading 1</h1>
<p>This is Paragraph 1</p>
<h1 style="color:green">This is Heading 2</h1>
<p style="color:yellow">This is Paragraph 2</p>
<h1>This is Heading 3</h1>
<p>This is Paragraph 3</p>
</body>
</html>
Output:
CSS Comments
It is a common practice to add comments in the code to enhance readability and add helpful notes
alongside the code. Like most languages, CSS allows the users to add comments in the stylesheet.
Comments in CSS can be added by using the /* tag, which is then closed off by using */. This
technique can be used to add both single and multi-line comments.
Single-line comments:
Single-line comments can be added as follows:
/* This is a single line comment */
Users may observe that the // tag can be used to add single line comments. However, this not the
standard practice in CSS and therefore should not be used.
Multi-Line comments:
Multi-line comments can be added using the same /* tag.
/* This is a
Multi-line comment
In CSS */
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of CSS Comments
</title>
<style>
h1{
/*background-color:azure;*/
color:black;
font-size:40px;
}
p{
background-color:lightcoral ;
color:blue;
/*font-size:25px;
font-family:Arial;*/
}
</style>
</head>
<body>
<h1>This is Heading 1</h1>
<p>This is Paragraph 1</p>
<h1>This is Heading 2</h1>
<p>This is Paragraph 2</p>
<h1>This is Heading 3</h1>
<p>This is Paragraph 3</p>
</body>
</html>
Output:
<!DOCTYPE html>
<html>
<head>
<title>Illustration of Absolute Units</title>
<style>
.absoluteUnits1{
font-size:20px;
}
.absoluteUnits2{
font-size:20pt;
}
.absoluteUnits3{
font-size:3pc;
}
.absoluteUnits4{
font-size:1cm;
}
</style>
</head>
<body>
<div class="absoluteUnits1">
<p>My First Dimensions are Absolute</p>
</div>
<div class="absoluteUnits2">
<p>My Second Dimensions are Absolute</p>
</div>
<div class="absoluteUnits3">
<p>My Third Dimensions are Absolute</p>
</div>
<div class="absoluteUnits4">
<p>My Fourth Dimensions are Absolute</p>
</div>
</body>
</html>
Output:
Relative Units
These units are relative to some other length property like the parent elements font size or the size of
the viewport.
In relative units, we talk in terms of the same property, like, if we are talking about the width of an
element in relative units then it is relative to the WIDTH of the parent element/viewport.we shall be
seeing this in the example section in a while.
Relative units, if used correctly, are suitable for making elements scale properly concerning other
things on the same page i.e. to make the element responsive. We shall see this in the example below.
CSS %: This is the percentage unit. The measurement of the element is relative to the dimensions of
the parent. Like if we set the width of an HTML element to be K% then its width is calculated as
follows:
Width of HTML element = (K/100) * width of parent element.
CSS em: em refers to the default size of the property. So precisely, em is equivalent to 100%. This is
mostly used to achieve the same values dynamically as is the case with % but applies specifically to
font size.
CSS rem: This unit counters the adding-up effect of units like % and em, rem rather stands for Root
em. This means the browser will ignore all the adjustments made to the parent elements and will
scale the HTML element, to which the property is applied, based on the root/default value for that
particular element.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Illustration of Relative Units</title>
<style>
.relativeUnits1{
font-size:400%;
}
.relativeUnits2{
font-size:5em;
}
.relativeUnits3{
font-size:4rem;
}
</style>
</head>
<body>
<div class="relativeUnits1">
<p>My First Dimensions are Relative</p>
</div>
<div class="relativeUnits2">
<p>My Second Dimensions are Relative</p>
</div>
<div class="relativeUnits3">
<p>My Third Dimensions are Relative</p>
</div>
</body>
</html>
Output:
CSS Colors
CSS Color property is used to set the color of HTML elements. This property is used to set font
color, background color, etc. The color of an element can be defined in the following ways:
1. Built-in Color
2. RGB Format
3. RGBA Format
4. Hexadecimal Notation
5. HSL
6. HSLA
1. Built-in Color
There are a set of predefined colors which are used by its name. For example, red, blue, green, etc.
Syntax:
H1{
color: color-name;
}
Example:
H1{
color: red;
}
2. RGB Format
The RGB (Red, Green, Blue) format is used to define the color of an HTML element by
specifying the R, G, and B values range between 0 to 255. For example, the RGB value of
redcolor is (255,0,0), Green color is (0,255,0), Blue color is (0,0,255), etc.
Syntax:
H1{
color: rgb(R,G,B);
}
Example:
H1{
color: rgb(0,153,0);
}
3. RGBA Format
The RGBA format is similar to the RGB, but the difference is RGBA contains A (Alpha) which
specifies the transparency of elements. The value of alpha lies between 0.0 to 1.0. Where 0.0
represents fully transparent and 1.0 represents not transparent.
Syntax:
H1{
Color:rgba(R,G,B,A);
}
Example:
H1{
color:rgba(0,153,0,0.5);
text-align:center;
}
4. Hexadecimal Notation
The hexadecimal notation begins with the # symbol followed by 6 characters each ranging from 0
to F. For example: Red #FF0000, Green #00FF00, Blue #0000FF etc.
Syntax:
H1{
Color:#(0-F)(0-F)(0-F)(0-F)(0-F)(0-F);
}
Example:
H1{
Color:#009900;
}
5. HSL
HSL stands for Hue, Saturation and Lightness respectively. This format uses the cylindrical
coordinate system.
Hue: Hue is the degree of the color wheel. Its value lies between 0 to 360 where 0 represents
red, 120 represents green and 240 represents blue color.
Saturation: It takes a percentage value, where 100% represents completely saturated, while
0% represents completely unsaturated (gray).
Lightness: It takes percentage value, where 100% represents white, while 0% represents
black
Syntax:
H1{
Color:hsl(H,S,L);
}
Example:
H1{
Color:hsla(0,153%,10%,0.5);
}
6. HSLA
The HSLA color property is similar to the HSL property, but the difference is HSLA contains A
(Alpha) which specifies the transparency of elements. The value of alpha lies between 0.0 to 1.0
where 0.0 represents fully transparent and 1.0 represents not transparent.
Syntax:
H1{
Color:hsla(H,S,LA);
}
Example:
H1{
Color:hsla(0,153%,10%,0.5);
}
#xx xx xx
Hex code byte values range from 00, which is the lowest intensity of a color, to FF which represents
the highest intensity. The color white, for example, is made by mixing each of three primary colors at
their full intensity, resulting in the Hex color code of #FFFFFF.
#FFFFFF
Black, the absence of any color on a screen display, is the complete opposite, with each color
displayed at their lowest possible intensity and a Hex color code of #000000.
#000000
Understanding the basics of Hex color code notation, we can create grayscale colors very easily since
they consist of equal intensities of each color:
#454545 #999999
The three primary colors, red, green and blue, are made by mixing the highest intensity of the desired
color with the lowest intensities of the other two:
Green #008000
Lime #00ff00 #0f0
Maroon #800000
Navy #000080
RGB Values
Generally, hex colors and rgbcolors are identical – they just use a different numeric system and
syntax (but the colors are the same). RGB is an acronym that stands for Red Green and Blue.
Instead of using six hexadecimal characters as we did for the hex color values, with RGB each
parameter pair defines the intensity and brightness of each color (red, green, and blue), with an
integer number ranging from 0-255 or a percentage ranging from (0% - 100%).
It expresses colors system in terms of the amount of red, green, and blue they are made up of and
uses a human counting system in comparison to hex colors that speak computer language. The
number is a code to represent how dark or bright the color is:
The minimum value of 0 represents that none of the colors is being shown, so it is at its darkest. On
the the other hand, the maximum value of 255 represents the full amount of color and the full
intensity is on display.
RGB Color Syntax:
The general look of an rgb declaration is rgb(red, green,blue).
The keyword rgb followed by a set of parentheses ().
Three numeric decimal values separated by commas inside the parentheses (which represent
the three colors).
And finally, it ends with a semicolon.
Taking again the cyan example, the equivalent rgb code is:
H2{
Color:rgb(0,255,255);
}
We are living in the 21st century and there are billions of users with mllions of computers platforms.
As a developer, we need to make sure that on all computer platforms, the color should be the same.
We don’t need that if we use other devices then the color of the site will change. So, it is highly
recommended to use browser-safe colors.
Browser-safe colors are a set of 216 colors that are commonly supported by web browsers and
operating systems, and they were selected to ensure that they would display consistently across
different devices and platforms.
While browser-safe colors are not as widely used today as in the past due to advance in technology,
they remain a useful tool for ensuring consistent color display across different platforms, particularly
in situations where color accuracy is critical.
CSS – Background
The CSS background properties are used to define the background effects for elements. There are
lots of properties to design the background. CSS background properties are as follows:
CSS Background-color Property: The background-color property in CSS is used to specify
the background color of an element.
CSS Background-image Property: The background-image property is used to set one or
more background images to an element.
CSS Background-repeat Property: The background-repeat property in CSS is used to
repeat the background image both horizontally and vertically.
CSS Background-attachment Property: The background attachment property in CSS is
used to specify the kind of attachment of the background image concerning its container.
CSS Background-positions Property: In CSS body position property is mainly used to set
an image at a certain position.
CSS Background-origin Property: The background-origin is a property defined in CSS
which helps in adjusting the background image of the webpage.
CSS Background-clip Property: The background-clip property in CSS is used to define
how to extend the background (color or image) within an element.
CSS Background-color Property: This property specifies the background color of an
element. A color name can also be given as: “green”, a Hex value as “#5570f0”, and an RGB
as “rgb(25,255,2)”.
Syntax:
Body{
Background-color: color-name;
}
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Background Property
</title>
<style>
body{
background-color:aqua;
}
h1{
background-color:blueviolet;
text-align:center;
}
</style>
</head>
<body>
<h1>BCCA Second Year</h1>
</body>
</html>
Output:
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Background Image
</title>
<style>
body{
background-image:url("Books.jpg");
background-repeat:no-repeat;
background-position:center;
}
h2{
color:red;
background-clip:content-box;
}
</style>
</head>
<body>
<h2>This is Demostration Heading</h2>
</body>
</html>
CSS Fonts
The CSS fonts module defines font-related properties and how font resources are loaded. It lets you
define the style of a font, such as its family, size and weight, line height, and the graph variants to
use when multiple are available for a single character.
CSS Font property is used to control the look of texts. By the use of CSS font property you can
change the text size, color, style and more. Here, you will also know how to resize your font using
percentage. These are some important font attributes.
1. CSS Font Color: This property is used to change the color of the text.
2. CSS Font Family: This property is used to change the face of the font.
3. CSS Font Size: This property is used to increase or decrease the size of the font.
4. CSS Font Style: This property is used to make the font bold, italic, or oblique.
5. CSS Font Variant: This property creates a small-caps effect.
6. CSS Font Weight: This property is used to increase or decrease the boldness and lightness of the
font.
CSS Font Color:
CSS font color is a standalone attribute in CSS although it seems that it is a part of CSS fonts. It is
used to change the color of the text. There are three different formats to define a color:
By a color name.
By hexadecimal value.
By RGB.
Example:
H1{color:red;}
H2{color:#9000A1;}
P{color:rgb(0,220,98);}
F F F
(Arial) (Monotype Corsiva) (Times New Roman)
Property Values
1. Normal: It is the default font-weight whose numeric value is 400.
2. Lighter: It considers the existing font-weight of the font family and makes the font-weight lighter
compared to the parent element.
3. Bolder: It considers the existing font-weight of the font family and makes the font-weight heavier
compared to the parent element.
4. Bold: As its name implies, it is used to define the bold font-weight, and its numeric value is 700.
5. Number: It is used to set the font-weight based on the specified number. Its range can be between
1 to 1000.
6. Initial: It is used to set the font-weight to its default value.
Example:
P{
Font-weight:bold;
Font-weight:lighter;
Font-weight:400;
}
CSS Font Stretch
The font-stretch property in CSS allows us to select a normal, expanded, or condensed face from the
font’s family. This property sets the text wider or narrower compared to the default width of the font.
It will not work on any font but only works on the font-family that has a width-variant face.
This CSS property only works for the fonts with additional faces like expanded and condensed faces;
otherwise, it will be affectless for the fonts that don’t have condensed or expanded faces.
The nine keyword values for choosing the width of the font face are given below:
Syntax:
Font-stretch: normal | semi-condensed | condensed | extra-condensed | ultra-condensed | semi-
expanded | expanded | extra-expanded | ultra-expanded
Border
Outline
Margin
Padding
List
Background
The CSS Background property is used to set the backgraound on a web page. The background can be
applied to any element like the body, h1, p, div, etc. There are many properties available with a
background such as color, image, position, etc. Some of them are used in the below code.
Background: #000 url(images/bg.png) no-repeat left top;
Example:
<!DOCTYPE html>
<html>
<head>
<title>Illustration of shorthand background</title>
<style>
body{
background:#000 url("Books.jpg") no-repeat center top;
}
</style>
</head>
<body></body>
</html>
Font
The CSS font property is used to apply different fonts to the text on the webpage. The various
attributes that can be set using the font are font family, font size, font weight, etc. Some of them are
used as follows:
Example:
<!DOCTYPE html>
<html>
<head>
<title>Illustration of shorthand font</title>
<style>
h1{
font:italic bold 30px/150% Arial, San-serif;
}
</style>
</head>
<body>
<h1>This is Heading Demo</h1>
</body>
</html>
Border
The CSS border property is used to apply a border to different elements of a web page. There are
many attributes of the border like width, style, color, etc.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Illustration of shorthand border</title>
<style>
h1{
border: 1px solid #000;
}
</style>
</head>
<body>
<h1>This is Heading Demo</h1>
</body>
</html>
Outline
The CSS outline property is used to apply an outline to various elements that are present on a web
page.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Illustration of shorthand outline</title>
<style>
h1{
outline: 10px solid #000;
}
</style>
</head>
<body>
<h1>This is Heading Outline Demo</h1>
</body>
</html>
Margin
The CSS margin properties are used to create space around elements, outside of any defined borders.
We can define the margin for all 4 sides i.e. top, bottom, left and right.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Illustration of shorthand margin</title>
<style>
h1{
margin: 100px 50px 100px 50px;
}
</style>
</head>
<body>
<h1>This is Heading Margin Demo</h1>
</body>
</html>
Padding
The CSS padding properties are used to generate space around an element’s content, inside of any
defined borders. Padding can also be applied as top, bottom, left and right padding.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Illustration of shorthand padding</title>
<style>
h1{
padding: 100px 50px 100px 50px;
}
</style>
</head>
<body>
<h1>This is Heading Padding Demo</h1>
</body>
</html>
List
There are mainly two types of lists in CSS: 1. Ordered list <ol> 2. Unordered list <ul>. Unordered
lists have bullet points while ordered lists have numbers.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Illustration of shorthand list</title>
<style>
li{
list-style: lower-alpha inside;
}
</style>
</head>
<body>
<li>BBA</li>
<li>BCCA</li>
</body>
</html>
CSS TextSetting
The CSS text formatting properties are used to format text, style the text and perform different types
of manipulations like word spacing, alignment, justification, and text transformation.
Syntax:
Selector {
Property-name: /* value */;
}
CSS Text Formatting Properties:
There are the following text formatting properties.
Text Color: This property is used to set the color of the text and the color can be set by using a
color name like ‘red”, hex value “#ff0000”, or by its RGB value “rgb(255,0,0)”.
Text-align: This property in CSS is used to specify the horizontal alignment of text in an element
inside a block element or table-cell box.
Text-align-last: It is used to set tha last line of the paragraph just before the line break. It sets the
alignment of all the last lines occurring in the element in which the text- align-last property is
applied.
Text-decoration: Text-decoration property is used to “decorate” the content of the text.
Text-decoration-color: It is used to set the color of the decorations (overlines, underlines, and
line-throughs) over the text.
Text-decoration-lines: It is used to set the various kinds of text decorations. This may include
many values such as underline, overline, line through, etc.
Text-decoration-style: This property is used to set the text-decoration of the element. it is the
combination of the text-decoration-line and text-decoration-color properties.
Text-indent: It is used to indent the first line of the paragraph and the size can be in px, cm, pt.
Text-justify: This property is used to set the text-align to justify. It spreads the words into
complete lines.
Text-overflow: The property of text formatting specifies that some text has overflow and is
hidden from the view.
Text-transform: It is used to control the capitalization of the text.
Text-shadow: It is used to add shadow to the text.
Letter-spacing: This property is used to specify the space between the characters of the text.
Line-height: It is used to set the space between the lines.
Direction: This property is used to set the direction of the text.
Word-spacing: It is used to specify the space between the words of the line.
Text Color
The color of the text is defined by the CSS color property. The style rules in the following example
will define the default text color for the page.
Body {
Color: #434343;
}
Although the color property seems like it would be a part of the CSS text, it is a standalone property
in CSS. The color property defines the text color of an element.
For instance, the color property specifies in the body selector defines the default text color for the
whole page.
Defining Color Values
Colors in CSS are most often specified in the following formats:
A color keyword – like “red”, “green”, “blue”, “transparent”, etc.
A HEX value – like “#ff0000”, “#00ff00”, etc.
An RGB value – like “rgb(255,0,0)”.
CSS has introduced several other color formats such as HSL, HSLA, and RGBA that also support
alpha transparency.
Color Keyword
CSS defines the few color keywords which lets you easily specify color values. These basic color
keywords are aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver,
teal, white, and yellow. The color names are case-insensitive.
H1{
Color:red;
}
Modern web browsers however practically support many more color names than what is defined in
the CSS standard, but to be on the safer side you should use hex color values instead.
Text Direction
The following example demonstrated how to set the direction of a text. Possible values are ltr and rtl.
Example:
<p style= “direction:rtl;”>
This text will be rendered from right to left.
</p>
Text Indent
The following example demonstrates how to indent the first line of a paragraph. Possible values are
% or a number specifying indent space.
Example:
<p style= “text-indent:1cm;”>
This text will have the first line indented by 1 cm and this line remains at its
actual position this is done by CSS text-indent property.
</p>
Text Alignment
The text-align property property is used to control how text is aligned within its containing content
box. The available values are listed below. They work in pretty much the same way as they do in a
regular word processor application.
Left: Left justifies the text.
Right: Right-justifies the text.
Center: Centers the text
Justify: Makes the text spread out, varying the gaps between the words so that all lines of text
are same width.
Example:
<p style= “text-align:right”>
This will be right aligned.
</p>
2. Word Spacing
The word-spacing property is used to specify the additional spacing between the words. This
property can accept a length value in pixel, ems, etc. Negative values are also allowed. Try out the
following example to understand how this property works:
p.normal{
word-spacing:20px;
}
p.justified{
word-spacing:20px;
text-align:justify;
}
Text Cases
The following example demonstrates how to set the cases for a text. Possible values are none,
capitalize, uppercase, and lowercase.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of text cases
</title>
</head>
<body>
<p style="text-transform:capitalize;">This will be capitalized</p>
<p style="text-transform:uppercase;">This will be uppercase</p>
<p style="text-transform:lowercase;">This will be lowercase</p>
</body>
</html>
Output:
Text Shadow
You can apply drop shadows to your text using the text-shadow property. This takes up to four
values, as shown in the example below:
text-shadow: 4px 4px 5px red;
The four properties are as follows:
1. The horizontal offset of the shadow from the original text – this can take most available CSS
length and size units, but you’ll most commonly use px; positive values move from the shadow
right, and negative values left. This value has to be included.
2. The vertical offset of the shadow from the original text. This behaves similarly to the horizontal
offset, except that it moves the shadow up/down, not left/right. This value has to be included.
3. The blur radius: a higher value means the shadow is dispersed more widely. If this value is not
included, it defaults to 0, which means no blur. This can take the most available CSS length and
size units.
4. The base color of the shadow, which can take any CSS color unit. If not included, it defaults to
currentcolor, i.e. the shadow’s color is taken from the element’s color property.
Multiple shadows:
You can apply multiple shadows to the same text by including multiple shadow values separated by
commas, for example:
H1{
Text-shadow: 1px 1px 1px red, 2px 2px 1px red;
}
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of text shadow
</title>
<style>
h1{
text-shadow: 1px 1px 1px red, 2px 2px 1px red;
}
</style>
</head>
<body>
<h1>Tommay the cat</h1>
<p>Well I remember it as though it were a mean ago...</p>
<p>Said Tommay the Cat as he reeled back to clear whatever foreign matter
may have.
nested the way into his mighty throat.
</p>
</body>
</html>
Output:
CSS Borders
CSS border properties allow us to set the style, color, and width of the border. Different properties
can be set for all the different borders i.e. top border, the right border, the bottom border, and the left
border. The CSS border is a shorthand property used to set the border on an element.
The border properties allow you to specify how the border of the box representing an element should
look. There are three properties of a border you can change.
1. The border-color specifies the color of a border.
2. The border-style specifies whether a border should be a solid, dashed line, double line, or one
other possible values.
3. The border width specifies the width of a border.
The Border Color Property
The border-color property allows you to changing the color of the border surrounding an element.
You can individually change the color of the bottom, left, top, and right sides of the element’s border
using the properties.
border-bottom-color changes the color of the bottom border.
border-top-color changes the color of the top border.
border-left-color changes the color of the left border.
border-right-color changes the color of the right border.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of border-color property
</title>
<style>
p.example1{
border:1px solid;
border-bottom-color:#009900;
border-top-color:#FF0000;
border-left-color:#330000;
border-right-color:#0000CC;
}
p.example2{
border: 1px solid;
border-color:#009900;
}
</style>
</head>
<body>
<p class="example1">
This example is showing all borders in different colors.
</p>
<p class="example2">
This example is showing all borders in green color only.
</p>
</body>
</html>
Output:
Output:
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of border width property
</title>
</head>
<body>
<p style="border-width:4px; border-style:solid">
This is solid border whose width is 4px
</p>
<p style="border-width:4pt; border-style:solid">
This is solid border whose width is 4pt
</p>
<p style="border-width:thin; border-style:solid">
This is solid border whose width is thin
</p>
<p style="border-width:medium; border-style:solid">
This is solid border whose width is medium
</p>
<p style="border-width:thick; border-style:solid">
This is solid border whose width is thick
</p>
<p style="border-bottom-width:8px; border-top-width:10px;
border-left-width:2px; border-right-width:15px;
border-style:solid">
This is a border with four different width
</p>
</body>
</html>
Output:
Output:
Unit – II
JAVA SCRIPT BASICS
Introduction
A program composed of commands from a particular language is referred to as a script. Script adds
life to the web page or intranet application. JavaScript was initially created to make webpage alive. It
can make a static page and interactive user and data aware page.
JavaScript is an interpreted scripting language. An interpreted language is a type of programming
language that executes its instructions directly and freely without compiling machine language
instructions in precious program.
What is JavaScript
JavaScript is object-based scripting language and it is light weighted. It was first implemented by
Netscape (with help from Sun Microsystems). JavaScript was created by Brendan Eich at Netscape
in 1995 for the purpose of allowing code in web-pages (performing logical operations on client side).
JavaScript is most commonly used as a client side scripting language. This means that JavaScript
code is written into an HTML page. When a user reqqquts an HTML page with JavaScript in it, the
script is sent to the browser and it’s up to the browser to do something with it.
JavaScript is not compiled but translated, JavaScript Translator is responsible to translate the
JavaScript code which is embedded in browser. It is supported by major browsers including NN, IE,
AOL, MOZILLA, and Opera.
Originally the JavaScript language was called Live Script, but when it was about to be released Java
had become immensely popular. At the last possible moment Netscape changed the name of its
scripting language to “JavaScript”.
Features of JavaScript
1. Light Weight: JavaScript is a lightweight scripting language because it is made for data
handling at the browser level only. Since it is not a general purpose language so it has a limited
set of libraries.
2. Achieves dynamic effects in web page: Using this feature available in JavaScript, the
designer can deciede to have dynamically placed text at run time.
3. React to events: A JavaScript can be set to execute when something happens, like when a
page has finished loading or when a user clicks on an HTML element.
4. Validate Data: A JavaScript can be used to validate form data before it is submitted to a
server. This saves the server from extra processing.
5. Object-Based Language: JavaScript is an object-based scripting language that provides built-
in objects like String, Math, Date, etc.
6. Saves Time: JavaScript also has the feature of validating data submitted at the client level.
This helps in saving the processing time of server because JavaScript initially creates the
validation on client side.
7. DOM: Client side JavaScript is embedded inside HTML. This embedded JavaScript is used
along with DOM (Document Object Model) for control over the browser by means of objects.
8. Interpreted Language: JavaScript is an interpreted language, meaning that it can be used or
execute with ease without pre-compilation.
9. Visual JavaScript: Visual JavaScript is a component-based visual development tool for the
Netscape Open Network Environment used by programmers who want to build cross-platform
web-based applications.
10. Create new functions: An important part of JavaScript is the ability to create new functions
within scripts. Declare a function in JavaScript using function keyword.
11. Platform Independent: JavaScript is platform independent scripting language. Any
JavaScript-enabled browser can understand and interpreted JavaScript code. Due to different
features, JavaScript is known as universal client side scripting language.
2. Generally client-side scripting is used for data entry validation such as checking values, ranges,
dates etc., whereas server-side scripting is used for heavy-duty processing at server such as
saving data to the database, accessing, modifying and deleting data from the database.
3. The client-side scripting language involves languages such as HTML5, JavaScript etc. In
contrast, programming languages such as PHP, ASP.net, Ruby, ColdFusion, Python, C# etc. are
server side scripting languages.
4. Server-side scripting is useful in customizing the web pages and implements the dynamic
changes in the websites. Conversely, the client-side scripts are generally used for validation
purpose and effectively minimize the load to the server.
5. Special software (web server) is required to execute server-side script, whereas client side scripts
requires web browser as an interface.
6. Client-side script and server-side scripts cannot interact with one another. The client-side scripts
are executed on the client, after the server-side scripts have finished processing completely.
History of JavaScript
In 1993, Mosaic, the first popular web browser, came into existence.
In 1994, Netscape was founded by Marc Adnreeseen. He realized that the web needed to
become more dynamic. Thus, a ‘glue language’ was belived to be provided to HTML to
make web designing easy for designers and part-time programmers.
Consequently, in 1995, the company recruited Brendam Eich intending to implement and
embed Scheme programming language into the browser.
But, before Brendan could start, the company merged with Sun Microsystems for adding Java
into its Navigator so that it could compete with Microsoft over web technologies and
platforms.
Now, two languages were there: Java and the scripting language. Further, Netscape decided
to give a similar name to the scripting language as Java. It led to ‘JavaScript’.
Finally, in May 1995, Marc Andreessen coined the first code of JavaScript named ‘Mocha’.
Later, the marketing team replaced the name with ‘LiveScript’.
But, due to trademark reasons and certain other reasons, in December 1995, the language was
finally renamed to ‘JavaScript’. From them, JavaScript came into existence.
Application of JavaScript
JavaScript is used to create interactive website. It is maily used for:
Web Development
Web Applications
Server Application
Games
Smartwatches
Art
Machine Learning
Mobile Appilcations
Web Development
Adding interactivity and behavior to static sites JavaScript was invented to do this in 1995. By
using AngularJS that can be achieved so easily.
Web Applications
With technology, browsers have improved to the extent that a language was required to create
robust web applications. When we explore a map in Google Maps then we only need to click
and drag the mouse. All detailed view is just a click away, and this is possible only because of
JavaScript. It uses Application Programming Interfaces (API) that provide extra power to the
code. The Electron and React are helpful in this department.
Server Application
With the help of NodeJs, JavaScript made its way from client to server and NodeJs is the most
powerful on the server side.
Games
Not only in websites, but JavaScript also helps in creating games for leisure. The combination of
JavaScript and HTML5 makes JavaScript popular in game development as well. It provides the
EaseJS library which provides solutions for working with rich graphics.
Smartwatches
JavaScript is being used in all possible devices and applications. It provides a library PebbleJS
which is used in smartwatch applications. This framework works for applications that require the
Internet for their functioning.
Art
Artists and designers can create whatever they want using JavaScript to draw on HTML5
canvas, and make the sound more effective also can be used P5JS library.
Machine Learning
This JavaScript ml5JS library can be used in web development by using machine learning.
Mobile Appilcations
JavaScript can also be used to build an application for non-web contexts. The features and uses
of JavaScript make it a powerful tool for creating mobile applications. This is a Framework for
building web and mobile apps using JavaScript. Using React Native, we can build mobile
applications for different operating systems. We do not requied to write code for different
systems. Write once use it anywhere!
Limitation of JavaScript
Security risks
Performance
Complexity
Weak error handling and type checking facilities
Security risks
JavaScript can be used to fetch data using AJAX or by manipulating tags that load data such as
<img>, <object>, <script>. These attacks are called cross-site script attacks. They inject JS that
is not part of the site into the visitor’s browser thus fetching the details.
Performance
JavaScript does not provide the same level of performance as offered by many tranditional
languages as a complex program written in JavaScript would be comparatively slow. But as
JavaScript is used to perform simple tasks in a browser, so performance is not considered a big
restriction in its use.
Complexity
To master a scripting language, programmers must have a thorough knowledge of all the
programming concepts, core languages objects, and client and server side objects otherwise it
would be difficult for them to write advanced scripts using JavaScript.
Weak error handling and type checking facilities
It is a weakly typed language as there is no need to specify the data type of the variable. So
wrong type checking is not performed by compile.
Internal JavaScript
Internal JavaScript code is a code that’s placed anywhere within the web page between the HTML
tags. Many web developers choose to place their JavaScript code before the tag. We can add
JavaScript directly to out HTML file by writing the code inside the <script> tag. The <script> tag
can either be placed inside the <head> or the <body> tag according to the requirement.
When JavaScript was written within the section using an element then it is called internal JavaScript.
Example:
<!doctype html>
<html lang= “en”>
<head>
<title>
Basic Example to Internal JavaScript
</title>
</head>
<body>
<!.. JavaScript code can be embedded inside head section or body section ..>
<script>
document.write(“Welcome to JavaScript”);
</script>
</body>
</html>
Advantages of Internal JavaScript
If the number of lines of JavaScript is relatively small, a web page with internal JavaScript loads
faster than pages that must reference external code. This is because, as the web browser loads the
page and encounters the reference to the external code, it must make a separate request to the web
server to fetch the code.
External JavaScript
We can create external JavaScript files and embed them in any html page. It provides code re-
usability because a single JavaScript file can be used in several html pages. An external JavaScript
file must be saved by the .js extension. It is recommended to embed all JavaScript files into a single
file. It increases the speed of the webpage.
Message.js
function msg() {
alert(“Hello JavaScript”);
}
Let’s include the JavaScript file in an html page. It calls the JavaScript function on button click.
Prog069.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="message.js"></script>
<title>Illustration of External JavaScript</title>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="Click" onclick="msg()">
</form>
</body>
</html>
Java is compiled programming language. That means before the program is run, the code
needs to be translated into machine code so the computer can understand it.
JavaScript is an interpreted language. In the browser, an interpreter will read the code and run
it without needing to compile it first.
Java is used as a server-side (backend) language whereas JavaScript is primarily used as a
client-side(frontend) language. But JavaScript can also be used to create backend web
applications with Node.js.
How do HTML, CSS and JavaScript work together on the web page?
Now that we have learned the history of JavaScript, we need to understand how it works on a
website. HTML renders the content, CSS style the page to make it look good, and JavaScript makes
the site interactive.
How do You Add JavaScript to a Website?
Adding JavaScript code to a web page is a pretty simple process (and a familiar one if you’ve done
any coding with HTML and CSS). JavaScript can be added directly to a page’s code using <script>
tags and giving them type attribute text/JavaScript. Honestly, JavaScript looks very similar to adding
CSS to a site. Here’s a side-by-side comparison:
CSS:
<style>
CSS goes here
</style>
JavaScript:
<script type= “text/JavaScript”>
JavaScript code goes here
</script>
page and also add behavior to the HTML elements. So, basically, Document Object Model is an API
(Application Programming Ineterface) that represents and interacts with HTML or XML documents.
Why DOM is required?
HTML is used to structure the web pages and JavaScript is used to add behavior to our web pages.
When an HTML file is loaded into the browser, the JavaScript cannot understand the HTML
document directly. So, a corresponding document is created (DOM). DOM is the representation of
the same HTML document but in a different format with the use of objects. JavaScript interprets
DOM easily i.e. JavaScript cannot understand the tags(<h1>H</h1>) in HTML document but can
understand object h1 in DOM. Now, JavaScript can access each of the object (h1, p, etc) by using
different functions.
Structure of DOM
DOM can be thought of as a Tree or Forest (more than one tree). The term structure model is
sometimes used to describe the tree-like representation of a document. Each branch of the tree ends
in a node, and each node contains object. Event lilsteners can be added to nodes and triggered on an
occurrence of a given event. One important property of DOM structure models is structural
isomorphism: if any two DOM implementations are used to create a representation of the same
document, they will create the same structure model, with precisely the same object and
relationships.
Why called an Object Model?
Docuements are modeled using objects and the model includes not only the structure of a document
but also the behavior of a document and the objects of which it is composed like tag elements with
attributes in HTML.
Properties of DOM
Let’s see the properties of the document object that can be accessed and modified by the document
object.
Window Objects
A Window Object is an object of the browser that is always at the top of the hierarchy. It is like
an API that is used to set and access all the properties and methods of the browser. It is
automatically created by the browser.
Document Object
When an HTML document is loaded into a window, it becomes a document object. The
‘document’ object has various properties that refer to other objects which allow access to and
modification of the content of the web page. If there is a need to access any element in an
HTML page, we always start with accessing the ‘document’ object. Document object is property
of window object.
Form Object
It is represented by form tags.
Link Object
It is represented by link tags.
Anchor Object
It is represented by a href tag.
Form Control Elements
Form can have many control elements such as text fields, buttons, radio buttons, checkboxes,
etc.
Methods of Document Object
write(“string”): Writes the given string on the document.
getElementById(): returns the element having the given id value.
getElementByName(): returns all the elements having the given name value.
getElementBytagName(): returns all the elements having the given tag name.
getElementByClassName(): returns all the elements having the given class name.
Variable Declaration
In JavaScript, we can declare a variable in different ways by using different keywords. Each
keyword holds some specific reason or feature in JavaScript. We can declare variable in three
different ways by using var, let and const keywords. variables Each keyword is used in some specific
conditions.
JavaScript var JavaScript let JavaScript const
Can be redeclared Cannot be redeclared Cannot be redeclared
Can be reassigned a value Can be reassigned a value Cannot be reassign the value
Only have global and function Can have a block scope Can have a block scope
scope
Variables are hosted on top and Variables must be initialized Variables must be initialized
can be used anywhere before use before use
Can be redeclared anywhere in Can be redeclared inside a Can never be redeclared
the program. block
JavaScript var:
This keyword is used to declare variables globally. If you used this keyword to declare a variable
then the variable can be accessed globally and changeable also. It is good for a short length of codes.
If the codes get huge then you will get confused.
Syntax: var variableName = “Variable-Value”;
Example: var sname = “JavaScript”;
Console.log(sname);
Output: JavaScript
JavaScript let:
This keyword is used to declare variables locally. If you used this keyword to declare a variable then
the variable can accessible locally and it is changeable as well. It is good if the code gets huge.
Syntax: let variableName = “Variable-Value”;
Example: if(true) {
Let sname = “JavaScript”;
Console.log(sname);
}
/* This will be an error and show geeks in not defined */
Console.log(geeks);
Output: JavaScript
JavaScript const:
This keyword is used to declare variables locally. If you use this keyword to declare a variable then
the variable will only be accessible within that block similar to the variable defined by using let and
the difference between let and const is that the variables declare using const values can’t be
reassigned. So we should assign the value while declaring the variable.
Syntax: const variableName = “Variable-Value”;
Example: const sname = “JavaScript”;
Console.log(sname);
Output: JavaScript
Operators
JavaScript Operators operate the operands, these are symbols that are used to manipulate a certain
value or operand. Operators are used to performing specific mathematical and logical computations
on operands. In other words, we can say that an operator operates the operands. In JavaScript,
operators are used to compare values, perform arithmetic operations, etc.
Types of Operators
There are various operators supported by JavaScript.
JS Arithmetic Operators
JS Assignment Operators
JS Comparison Operators
JS Logical Operators
JS Ternary Operators
JS Bitwise Operators
JS typeof Operators
JS Arithmetic Operators
There are the operators that operate upon the numerical values and return a numerical values.
1. Addition (+)
Addition ‘+’ operator perform addition on two operands. This ‘+’ operator can also be used to
concatenate (add) strings.
Y = 5 + 5 gives Y = 10
Y = “JavaScript” + “for” + “BCCA” gives Y = “JavaScriptforBCCA”
Y = “BCCA” + 4 + “II” gives Y = “BCCA4II”
2. Subtraction (-)
Subtraction ‘-‘ operator performs subtraction on two operands.
Y = 5 – 3 gives Y = 2
3. Multiplication (*)
The multiplication ‘*’ operator performs multiplication on two operands.
Y = 5 * 5 gives Y = 25
4. Division (/)
The division ‘/’ operator performs division on two operands (divide the numerator by the
denominator)
Y = 5/5 gives Y = 1
5. Modulus (%)
Modulus ‘%’ operator gives a remainder of an integer division.
Y = 5%4 gives Y=1
6. Exponentiation (**)
Exponentiation ‘**’ operator gives the power of the first operand raised to the second operand.
Y = 5**3 gives Y = 125
7. Increment (++):
Increment ‘++’ operator increases an integer value by one.
Let A = 10 and Y = A++ then A = 11, Y = 10
If A = 10 and Y = ++A then A=11, Y=11
8. Decrement (--):
The decrement ‘—‘ operator descreases an integer value by one.
Let A = 10 and Y = A-- then A = 9, Y = 10
If A = 10 and Y = --A then A=9, Y=9
9. Unary (+):
Unary ‘+’ is the fastest and preferred way of converting something into a number.
+a means a is a positive number.
10. Negation (-):
The negation ‘-‘ operator gives the negation of an operand.
-a means a is a negative number.
JS Assignment Operators
The assignment operation evaluates the assigned value. Chaining the assignment operator is possible
to assign a signle value to multiple variables.
Operator Meaning Example
Assignment(=) This operator assigns the right operand valued to If a=10 and y = a then
the left operand. y=10
Addition Sums up left and right operand values and then y+= 5 it means y= y+5
Assignment(+=) assigns the result to the left operand.
Subtraction It subtracts the right side value from the left side y-=5 it means y= y-5
JS Logical Operators
These operators are used to determine the logic between variables or values.
Operators Meaning Example
Logical AND It checks whether two operands are non-zero (0, false, Y=5 and X=6
(&&) undefined, null or infinity are considered as zero), if yes then Y && X is 6
return the last operand when evaluating from left to right.
Logical OR It checks whether two operands are non-zero (0, false, Y = 5 and X = 0
(||) undefined, null or infinity is considered as zero), if yes then Y || X is 5
return the first operand when evaluating from left to right.
Logical NOT It reverses the Boolean result of the operand (or condition). Y = 5 and X = 0
(!) !(Y || X) is false.
JS Ternary Operators
The ternary operator has three operands. It is the simplified operator of if/else.
Ternary Operator (? :) : It is like the short form of the if-else condition.
Y ==10?A:B;
JS Bitwise Operators
Bitwise operators treat its operands as a set of 32-bit binary digits (zeros and ones) and perform
actions. However, the result is shown as a decimal value.
Operator Meaning Example
Bitwise AND & Bitwise AND & returns 1 if the corresponding bits X & Y
of both operands are 1 else it returns 0.
Bitwise OR | Bitwise OR | return 0 if the corresponding bits of X | Y
both operands are 0 else return 1.
Bitwise XOR ^ Bitwise XOR ^ return 0 if one operand is 1 and X ^ Y
another operand is 0 otherwise return 0.
Bitwise NOT ~ Bitwise NOT ~ return 1 if the operand is false ~X
otherwise return 0.
Bitwise Left Shift Shift bits left and set number of 0’s in right. X << 2
<<
Bitwise Right Shift bits right and set number of 0’s in left. X >> 2
Shift >>
Bitwise Right Shift bits right and set number of 0’s in left with X >>> 2
Shift with 0 fill zero fill.
JS typeof Operators
It returns the data type of its operand in the form of a string. The operand can be any object, function
or variable.
JavaScript typeof:
It returns the operand type, the possible types that exist in JavaScript are
typeof variable;
Example:
let a = 17;
let b = “abc”;
let c = “”;
let d = null;
document.write(“Type of a = “ + typeof(a));
document.write(“Type of b = “ + typeof(b));
document.write(“Type of c = “ + typeof(c));
document.write(“Type of d = “ + typeof(d));
document.write(“Type of e = “ + typeof(e));
Output:
Type of a = number
Type of b = string
Type of c = string
Type of d = object
Type of e = undefined
The example below defines a loop that starts with i=1. The loop will continue to run as long as I is
less than, or equal to 5. I will increase by 1 each time the loop runs.
<!DOCTYPE html>
<html lang= "en">
<head>
<title>
Illustration of for loop
</title>
</head>
<body>
<script type="text/javascript">
var i;
for(i=1;i<=5;i++)
{
document.write("<br>The Number is :" + i);
}
</script>
</body>
</html>
Output:
The Number is :1
The Number is :2
The Number is :3
The Number is :4
The Number is :5
Example:
The example is the same as above
<!DOCTYPE html>
<html lang= "en">
<head>
<title>
Illustration of while loop
</title>
</head>
<body>
<script type="text/javascript">
var i=1;
while(i<=5)
{
document.write("<br>The Number is :" + i);
i++;
}
</script>
</body>
</html>
Output:
The Number is :1
The Number is :2
The Number is :3
The Number is :4
The Number is :5
<!DOCTYPE html>
<html lang= "en">
<head>
<title> Illustration of while loop </title>
</head>
<body>
<script type="text/javascript">
var i=5;
do
{
i++;
}while(i<5);
document.write("<br>The Number is :" + i);
</script>
</body>
</html>
Output:
The Number is : 6
Conditional Statement
While writing a program, there may be a situation when you need to adopt one out of given set of
paths. In such cases, you need to use conditional statements that allow your program to make correct
decisions and perform right actions.
Conditional statements are used to decide the flow of execution based on different conditions. If a
condition is true, you can perform one action and if the condition is false, you can perform another
action.
JavaScript supports the following forms of if…else statements:
if statement
if…else statement
if…else if statement
if statement:
The if statement is the fundamental control statement that allows JavaScript to make decisions and
execute statements conditionally.
Syntax:
if(expression)
{
Statement(s) to be executed if the expression is true.
}
Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s) are
executed. If the expression is false, then no statement would be not executed. Most of the time, you
will use comparison operators while making decisions.
Example:
if …else statement
The if…else statement is the next form of control statement that allows JavaScript to execute
statements in a more controlled way.
Syntax:
if(expression){
Statement(s) to be executed if the expression is true.
}
else {
Statement(s) to be executed if the expression is false. }
Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in the
‘if’ block, are executed. If the expression is false, then the given statement(s) in the else block is
executed.
Example:
if…else if statement
The if…else if statement is an advanced form of if…else that allows JavaScript to make a correct
decision out of several conditions.
Syntax:
if (expression 1){
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if expression 3 is true
} else {
Statement(s) to be executed if no expression is true
}
It is just a series of if statements, where each if is a part of the else clause of the previous statement.
Statement(s) are executed based on the true condition, if none of the conditions is true, then the else
block is executed.
Example:
Switch Statement
You should use the switch statement if you want to select one of many blocks of code to be executed.
The switch statement is a part of JavaScript's "Conditional" Statements, which are used to perform
different actions based on different conditions. Use switch to select one of many blocks of code to be
executed. This is the perfect solution for long, nested if/else statements.
Syntax:
switch(n)
{
case 1:
execute code block 1;
break;
case 2:
execute code block 2;
break;
default:
code to be executed if n is different from case 1 and 2
break;
}
Example:
JavaScript Function
Introduction
A function is a set of statements that take inputs, do some specific computation, and produce output.
The idea is to put some commonly or repeatedly done tasks together and make a function so that
instead of writing the same code again and again for different inputs, we can call that function.
JavaScript functions are used to perform operations. We can call the JavaScript function many times
to reuse the code.
Advantages of JavaScript Functions
There are mainly two advantages of javascript functions:
1. Code Reusability: We can call a function several times so it saves coding.
2. Less Coding: It makes our program compact. We don’t need to write many lines of code each
time to perform a common task.
Example: A basic javascript function, here we create a function that divides the 1st element by the
second element.
function myFunction(g1,g2) {
return g1/g2;
}
const value = myFunction(8,2); //Calling the function
document.write(value);
Output: 4
JavaScript supports function. JavaScript allows us to create user-defined functions also. We can
create function in JavaScript using the keyword function.
Function Declaration
The basic syntax to create a function in JavaScript is shown below:
function functionName(Parameter1, Parameter2, ….)
{
//Function Body
}
To create a function in JavaScript, we have to first use the keyword function, separated by the name
of the function and parameters within parenthesis. The part of the function inside the curly braces { }
is the body of the function.
In JavaScript, functions can be used in the same way as variables for assignments, or calculations.
Function Definition
Before, using a user-defined function in JavaScript we have to create one. We can use the above
syntax to create a function in JavaScript. A function definition is sometimes also termed a function
declaration or function statement. Below are the rules for creating a function in JavaScript:
1. Every function should begin with the keyword function followed by function name.
2. A user-defined function name that should be unique.
3. A list of parameters enclosed within parenthesis and separated by commas.
4. A list of statements composing the body of the function enclosed within curly braces { }.
Example: This eample shows a basic declaration of a function in JavaScript.
function calcAddition(number1, number2) {
return number1 + number2;
}
document.write(calcAddition(6,8));
Output: 14
In the above example, we have created a function named calcAddition.
This function accepts two numbers as parameters and returns the addition of these two
numbers.
Accessing the function with just the function name without ( ) will return the function object
instead of the function result.
Type of Writing a Function
There are three ways of writing a function in JavaScript:
Function Declaration
It declares a function with a function keyword. The function declaration must have a function name.
Syntax:
function fun(paramA, paramB) {
//Set of statements.
}
Function Expression
It is similar to a function declaration without the function name. Function expressions can be stored
in a variable assignment.
Syntax:
let fun = function(paramA, paramB) {
//set of statements
}
Example: This example explains the usage of the function expression.
const square = function(number) {
return number*number;
}
const x = square(4); //x gets the value 16
document.write(x);
Output: 16
Arrow Function
It is one of the most used and efficient methods to create a function in javascript because of its
comparatively easy implementation. It is a simplified as well as a more compact version of a regular
function expression or syntax.
Syntax:
let function_name = (argument1, argument2, ….) => expression
Example:
This example describes the usage of the Arrow function.
const a = [“Hydrogen”, “Helium”, “Lithium”, “Beryllium”];
const a1 = a.map(function(s){
return s.length;
});
Console.write(“Normal way “, a2); //[8,6,7,9]
const a3 = a.map((s)=>s.length);
console.write(“Using Arrow Function ”, a3); //[8,6,7,9]
Output:
Normal way [8,6,7,9]
Using Arrow Function [8,6,7,9]
Function Parameters
Parameters are additional information passed to a function. For example, in the above example, the
task of the function calcAddition is to calculate the addition of two numbers. These two numbers on
which we want to perform the addition operation are passed to this function as parameters. The
parameters are passed to the function within parentheses after the function name and separated by
commas. A function in JavaScript can have any number of parameters and also at the same time, a
function in JavaScript can not have a single parameter.
Example:
In this example, we pass the argument to the function.
function multiply(a,b){
b = typeofb != “undefined” ?b:1;
return a*b;
}
document.write(multiply(69)); //69
Output: 69
Calling Functions
After defining a function, the next step is to call them to make use of the function. We can call a
function by using the function name separated by the value of parameters enclosed between the
parenthesis and a semicolon at the end. The below syntax shows how to call functions in JavaScript:
Syntax:
functionName(value1,value2,….);
Example:
Below is a sample program that illustrate the working of functions in JavaScript:
function welcomeMsg(name){
return (“Hello ” + name + “ welcome to BCCA”);
}
//creating a variable
let nameVal = “Students”;
//calling the function
document.write(welcomeMsg(nameVal);
Output:
Hello Students welcome to BCCA
Return Statement
There are some situations when we want to return some values from a function after performing
some operations. In such cases, we can use of the return statement in JavaScript. This is an optional
statement and most of the time the last statement in a JavaScript function. Look at our first example
with the function named as calcAddition. This function is calculating two numbers and then returns
the result.
Syntax: The most basic syntax for using the return statement is:
return value;
The return statement begins with the keyword return separated by the value which we want to return
from it. We can use an expression also instead of directly returning the value.
Built-in Functions
There are several built-in functions in JavaScript. Each one is discussed below.
Number Functions
Boolean Functions
String Functions
StringHTML Wrappers
Array Functions
Math Functions
Date and Time Functions
Number Functions
The number object contains only the default methods that are part of every object’s definition.
Function Description
constructor() Returns the function that create this object’s instance. By default, this is the
Number object.
toExponential() Forces a number to display in exponential notation, even if the number is in the
range in which JavaScript normally uses standard notation.
toFixed() Formats a number with a specific number of digits to the right of the decimal.
toLocalString() Returns a string value version of the current number in a format that may vary
according to a browser’s local settings.
toPrecision() Defines how many total digits (including digits to the left and right of the
deciamal) to display a number.
toString() Returns the string representation of the number’s value.
valueOf() Returns the number’s value.
Boolean Functions
Here is a list of each method and its description.
Function Description
toSource() Returns a string containing the source of the Boolean object; you can use this
string to create an equivalent object.
toString() Returns a string of either “true” or “false” depending upon the value of the
object.
valueOf() Returns the primitive value of the Boolean object.
String Functions
Here is a list of each method and its description.
Function Description
charAt() Returns the character at the specified index.
charCodeAt() Returns a number indicating the Unicode value of the character at the given
index.
concat() Combines the text of two strings and returns a new string.
indexOf() Returns the index within the calling String object of the first occurrence of
StringHTML Wrappers
Here is a list of each method that returns a copy of the string wrapped inside the appropritate HTML
tag.
Function Description
anchor() Creates an HTML anchor that is used as a hypertext target.
big() Creates a string to be displayed in a big font as if it were in a <big> tag.
blink() Creates a string to blink as if it were in a <blink> tag.
bold() Creates a string to be displayed as bold as if it were in a <b> tag.
Array Functions
Here is a list of each method and its description.
Function Description
concat() Returns a new array comprised of this array joined with another array(s) and/or
value(s).
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() Returns the first (last) index of an element within the array equal to the specified
value, or -1 if none is found.
join() Joins all elements of an array into a string.
lastIndexOf() Returns the last (greatest) index of an element within the array equal to the
specified value, or -1 if none is found.
map() Creates a new array with the results of calling a provided function on every
element in this array.
pop() Removes the last element from an array and returns that element.
push() Adds one or more elements to the end of an array and returns the new length of
the array.
reduce() Apply a function simultaneously against two values of the array (from left to
Math Functions
Here is a list of each method and its description.
Function Description
abs() Return the absolute value of a number.
acos() Returns the arccosine (in radians) of a number.
asin() Returns the arcsine (in radians) of a number.
atan() Returns the arctangent (in randians) of a number.
atan2() Returns the arctangent of the quotient of its arguments.
ceil() Returns the smallest integer greater then or equal to a number.
cos() Returns the cosine of a number.
exp() Returns EN, where N is the argument, and E is Euler’s constant, the base of the
natural logarithm.
floor() Returns the largest integer less than or equal to a number.
log() Returns the natural logarithm (base E) of a number.
max() Returns the largest of zero or more numbers.
min() Returns the smallest of zero or more numbers.
pow() Returns base to the exponent power, that is, base exponent.
random() Returns a pseudo-random number between 0 and 1.
round() Returns the value of a number rounded to the nearest integer.
sin() Returns the sine of a number.
Document
Root element:
<html>
Element: Element:
<head> <body>
With the object model, JavaScript gets all the power it needs to create dynamic HTML.
JavaScript can change all the HTML elements on the page.
JavaScript can change all the HTML attributes on the page.
JavaScript can change all the CSS styles on the page.
JavaScript can remove existing HTML elements and attributes.
JavaScript can add new HTML elements and attributes.
JavaScript can react to all exsiting HTML events on the page.
JavaScript can create new HTML events on the page.
The “name” and “value” attributes are used to send the checkbox data to the server.
Example: In this example we use checkbox to select language.
<!DOCTYPE html>
<!-- Program for illustration of form elements-->
<HTML>
<HEAD>
<TITLE>
Checkbox
</TITLE>
</HEAD>
<BODY>
<center>
<h1>Registration Form</h1>
<form>
<label>Languages Known :</label>
<input type="checkbox" name="lang" value="English">English
<input type="checkbox" name="lang" value="Hindi">Hindi
<input type="checkbox" name="lang"
value="Marathi">Marathi<br><br>
<input type="submit" value="Submit">
</form>
</center>
</BODY>
</HTML>
Output:
</select>
The “name” and “value” attributes are used to send the Combobox data to the server.
Example: In this example, we will create a dropdown menu to select Nationality.
<!DOCTYPE html>
<!-- Program for illustration of form elements-->
<HTML>
<HEAD>
<TITLE>
Combobox
</TITLE>
</HEAD>
<BODY>
<center>
<h1>Registration Form</h1>
<form>
<label>Select Your Nationality :</label>
<select name="language">
<option value="Indian">Indian</option>
<option value="Nepali">Nepali</option>
<option value="Japanies">Japanies</option>
</select><br><br>
<input type="submit" value="Submit">
</form>
</center>
</BODY>
</HTML>
Output
Output:
}
Parameter Rules
There is no need to specify the data type for parameter in JavaScript function definitions.
It does not perform type-checking based on the passed-in JavaScript functions.
It does not check the number of received arguments.
Parameters:
Name: It is used to specify the name of the function.
Arguments: It is provided in the argument field of the function.
Example:
This example uses JavaScript function parameters and finds the largest number.
<!DOCTYPE html>
<!-- WAP to read three numbers and find highest of them
using function-->
<HTML>
<HEAD>
<TITLE>
Program to read 3 numbers and find highest
</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
function highest(a,b,c){
if(a>b && a>c)
l=a;
else if(b>c)
l=b;
else
l=c;
return l;
}
var n1,n2,n3,h;
n1 = prompt("Enter First Number :");
n2 = prompt("Enter Second Number :");
n3 = prompt("Enter Third Number :");
h = highest(n1,n2,n3);
Default Parameter
The default parameters are used to initialize the named parameters with default values in the case
when no value of undefined is passed.
Syntax:
function Name(param1, param2=value, param3=value){
//Statements
}
Example:
<!DOCTYPE html>
<!-- Program for illustration of default parameters-->
<HTML>
<HEAD>
<TITLE>
Default Parameters
</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
function interest(p,n=5,r=6.0){ //default arguments
si = p*r*n/100;
return si;
}
document.write("Simple Interest :" + interest(10000,3,5.5));
document.write("<br>Simple Interest :" + interest(20000,2));
document.write("<br>Simple Interest :" + interest(30000));
</SCRIPT>
</BODY>
</HTML>
Arguments Object
The arguments object are inbuilt objects in JavaScript functions. In all non-arrow functions, the
arguments object is a local variable. Analyze the arguments inside the function by using its
arguments object.
Example:
This example uses argument objects as parameters and finds the largest of numbers.
<!DOCTYPE html>
<!-- Program for illustration of argument object-->
<HTML>
<HEAD>
<TITLE>
argument object
</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
function GFG(){
let i;
let maximum = arguments[0];
for(i=1;i<arguments.length;i++){
if(arguments[i]>maximum)
maximum=arguments[i];
}
return maximum;
}
document.write("Largest Value of Collection is :" +
GFG(10,12,500,5,440,45));
</SCRIPT>
</BODY>
</HTML>
var1 = 100;
var2 = 200;
/*Display the value of a variable inside function*/
document.write("Var1 = " + var1 + "Var2 = " + var2);
}
var1 = 10;
var2 = 20;
/*The value of the variable before the Function Call*/
document.write("Var1 = " + var1 + "Var2 = " + var2);
/*Function Call*/
GeeksForGeeks(var1,var2);
/*The value of the variable after Function call*/
document.write("Var1 = " + var1 + "Var2 = " + var2);
</SCRIPT>
</BODY>
</HTML>
Output:
varObj.b = 200;
/*Display the value of a variable inside function*/
document.write("<br>Var1 = " + varObj.a + " Var2 = " +
varObj.b);
}
/*Create an object*/
varObj = {a:10,b:20};
/*The value of the variable before the Function Call*/
document.write("<br>Var1 = " + varObj.a + " Var2 = " + varObj.b);
/*Function Call*/
GeeksForGeeks(varObj);
/*The value of the variable after Function call*/
document.write("<br>Var1 = " + varObj.a + " Var2 = " + varObj.b);
</SCRIPT>
</BODY>
</HTML>
Output:
return;
x+y;
There is the automatic insertion of the semicolon after the return statement. The code written after
the return statement (x+y;) will be considered as the unreachable code. We can use parentheses to
prevent this problem. It can be written as:
return{
x+y;
};
Example:
This is a simple example of using return statement. Here, we are returning the result of the product of
two numbers and returning the value to the function caller.
The variable res is the function caller; it is calling the function fun() and passes two integers as the
arguments of the function. The result will be stored in the res variable. In the output, the value 360 is
the product of arguments 12 and 30.
<!DOCTYPE html>
<!-- Program for illustration of Returning Value-->
<HTML>
<HEAD>
<TITLE>
Returning Value
</TITLE>
</HEAD>
<BODY>
<h2>JavaScript Programs</h2>
<h3>Example of the JavaScript return Statement</h3>
<SCRIPT type="text/javascript">
function fun1(x,y){
return x*y;
}
var res = fun1(12,30);
document.write("Result : " + res);
</SCRIPT>
</BODY>
</HTML>
Array
JavaScript Array is a single variable that is used to store elements of different data types. JavaScript
arrays are zero-indexed. The JavaScript Arrays are not associative in nature.
Arrays are used when we have a list of items. An array allows you to store several values with the
same name and access them by using their index number.
Declaration of an Array
There are two ways to declare an array.
1. Creating an array using array literal:
2. Creating an array using the JavaScript new keyword
Example:
//Creates an array with one element
let arr4 = new Array(“1BHK”);
document.write(“Array 4:” + arr4);
Output:
Array 1: [10,20,30]
Array 2: [10, 20, 30, 40, 50]
Array 3: [<5 empty items>]
Array 4: [‘1BHK’]
document.write(course.toString());
Output:
HTML, CSS, JavaScript
Increase and Decrease the length of an array
Length of an array using the JavaScript’s length property.
const courses = [“HTML”, “CSS”, “JavaScript”];
courses.length = 5; //Increase array length to 5
console.log(“Array after Increased length :”, courses);
courses.length = 2; //Decrease array lennth to 2
console.log(“Array after Decrease length :”, courses);
Output:
Array after Increase length : [“HTML”, “CSS”, “JavaScript”, <2 empty items>]
Array after Decrease length : [“HTML”, “CSS”]
Objects
Objects, in JavaScript, are the most important data types and form the building blocks for modern
JavaScript. These objects are quite different from JavaScript’s pritimitive data types (Numer, String,
Boolean, null, undefined and symbol) in the sense that these primitive data types all stores a single
value each (depending on their types).
In JavaScript, an object is a unordered collection of key-value pairs. Each key-value pair is called a
property. The key of a property can be a string. And the value of a property can be any value, e.g. a
string, a number, an array, and even a function. JavaScript provides you with many ways to create an
object. The most commonly used one is to used the object literal notation.
Syntax:
new Object(value)
Object(value)
let object_name = {
key_name : value,
…
}
Object() can be called with or without new. Both create a new object.
Example:
const o = new Object();
o.foo = 42;
document.write(o);
Output:
foo: 42
Accessing Object Properties
To access a property of an object, you use one of two notations: the dot notation and array-like
notation.
The dot notation(.):
The following illustrates how to use the dot notation to access a property of an object:
objectName.propertyName
For example, to access the fistName property of the person object, you use the following expression:
person.firstName;
This example creates a person object and shows the first name and last name to the console.
let person = {
firstName: ‘John’,
lastName: ‘Doe’
};
document.write(person.firstName);
document.write(person.lastName);
Array-like notation ([]):
The following illustrates how to access the value of an object’s property vai the array-like notation:
objectName[‘propertyName’];
For Example:
let person = {
firstName: ‘John’,
lastName: ‘Doe’
};
document.write(person[‘firstName’]);
document.write(person[‘lastName’]);
When a property name contains spaces, you need to place it inside quotes. For example, the
following address object has the ‘building no’ as a property:
let address = {
‘building no’: 3960,
street: ‘North 1st street’,
state: ‘CA’,
country: ‘USA’
};
To access the ‘buiding no’ property, you need to use the array-like notation:
address[‘building no’];
If you use the dot notation, you’ll get an error:
Address.‘building no’;
Creating Object
JavaScript is a flexible object-oriented language when it comes to syntax. Here, we will see the
different ways to create objects in JavaScript. Before we proceed it is important to note that
JavaScript is an object-based language based on prototypes, rather than being class-based. Because
of this different basis, it can be less apparent how JavaScript allows you to create hierarchies of
objects and to have an inheritance of properties and their values.
Creating an object with constructor:
One of the easiest ways to instantiate an object is in JavaScript. Constructor is nothing but a function
and with the help of a new keyword, the constructor allows to create a multiple objects of the same
flavor as shown below:
//Simple function
function vehicle(name, maker, engine){
this.name = name;
this.maker = maker;
this.engine = engine;
}
//New keyword to create an object
let car = new vehicle(‘GT’, ‘BMW’, ‘1998cc’);
//Property accessors
document.write(car.name);
document.write(car.maker);
document.write(car.engine);
Output:
GT
BMW
1998cc
A class in OOPs has two major components, certain parameters, and few member functions. In this
method we declare a function similar to a class, there are three parameters, name, maker and engine
(this key is used to differentiate the name, maker and engine of the class from the name, maker and
engine of the arguments that are being supplied.). We then simply create an object obj of the vehicle,
initialize it and call its method.
Using Object Literals:
Literals are smaller and simpler ways to define objects. We simply define the property and values
inside curly braces as shown below:
let car = {
name: ‘GT’,
maker: ‘BMW’,
engine: ‘1998cc’
};
//Property accessor
document.write(car.name); //dot notation
document.write(car[‘maker’]); //bracket notation
Output:
GT
BMW
Methods can also be part of the object while creation or can be added later like properties as shown
below:
//Adding methods to the car object
let car = {
name: ‘GT’,
maker: ‘BMW’,
engine: ‘1998cc’,
start: function(){
document.write(‘Starting the engine…’); }
};
car.start();
//Adding method stop() later to the object.
car.stop = function() {
document.write(‘Applying Brake…’);
}
car.stop();
Output:
Starting the engine…
Applying Brake…
Array Object
An array in JavaScript is the collection of multiple types of data at a single place in order, and an
array of object in JavaScript is a collection of homogenous data, that stores a sequence of numbered
objects at a single place.
Example:
let myArr = [
{
studentName: ‘Abhishek’,
studentClass: 6,
studentSection: “A”
},
{
studentName: ‘Sachin’,
studentClass: 7,
studentSection: ‘B’
}
];
document.write(myArr[1]);
Output:
{
studentName: ‘Sachin’,
studentClass: 7,
studentSection: ‘B’
}
Above, there is an array of object myArr and we are accessing an object from the array by using
array index myArr[1], also printing the value on the console. As a result, we are printing an object
from an array of objects. this prints all the key-value pairs present at that particular index.
Syntax:
Array of objects syntax:
let myArr = [
//Array
{
//object
},
{
}
];
Creating an Array of Objects
To create an array of objects in JavaScript, we have to declare an empty array first and then initialize
it with the objects separated by a comma.
Example:
let mySchoolArr = [
{
schoolName: “children’s school”,
schoolAddress: “random-address”
},
{
numberOfStudents: 500,
numberOfTeachers: 10
}
];
Above, we declare an array of objects where each arrayis separated by a comma and has three
properties in each.
Array Properties
There are three types of properties in an array Object:
Constructor
The constructor properties return a function that creates the Array prototype. This return function is a
native code that is provided by the JavaScript engine.
let myArr = [
{
studentName: ‘Abhishek’,
studentClass: 6,
studentSection: “A”
},
{
studentName: ‘Sachin’,
studentClass: 7,
studentSection: ‘B’
}
];
document.write(myArr.constructor);
Output:
function Array() {
[native code]
}
Above, we have an array of objects myArr and we are printing its constructor properties on the
console. As a result, we print the function Array() {[native code]} on the console.
Here, we get the native code as a reference which is a predefined function inside the JavaScript
engine responsible for creating the array prototype.
Length
It returns the length of elements in an array i.e., the number of objects present in the array.
Example:
let myArr = [
{
studentName: ‘Abhishek’,
studentClass: 6,
studentSection: “A”
},
{
studentName: ‘Sachin’,
studentClass: 7,
studentSection: ‘B’
}
];
document.write(myArr.length);
Output:
2
Above, we use the length properties on the myArr array of objects and also print it on the console.
As a result, we print 2 on the console.
Prototype
Array prototype property helps to add new methods into the array, for example, adding all values
into an array. It also helps to add properties to the Array Object.
Example:
//Adding add method into the Array Object using Array.prototype property.
let myArr = [1,2,3,4];
Array.prototype.add = function(){
let result = 0;
//This keyword references the array on which add method will get called
for(let i=0; i<this.length;i++){
result += this[i];
}
return result;
}
console.log(myArr.add());
Output:
10
Above, we are additing a user-defined method into the Array Object. To do that, we accessed the
array prototype using dot notation and added the user-defined function add into Array Object like
this Array.prototype.add. Then, assigned an anonymous function to add, which is the definition of
add method.
In the add method definition, we declare a result variable to store the array value count. Here, we are
using this keyword to reference the array on which the add method will get called and loop over the
array. In each iteration, we are accessing the individual array values and adding them to the result
variable, when all values inside the array get added to the result variable, we returned the final result.
String Object
A String is a collection of characters or sequence of characters, which is always enclosed with a
single (‘’) or double quote (“”). A JavaScript string stores a series of characters like “C Sharp
Corner”.
Use of string
It is used to store single characters, and
It stores an array of characters.
It is used to manipulate text – search a particular letter and replace text.
Creation of String
There are two ways to creates string.
By string literal
var string name = “string value”;
zero or more characters written inside single or double quotes or backticks. The string indexes are
zero-based, the first character is in position 0 and the second in 1.
By string object using ‘new’ keyword
var string name = new string(“string value”);
In this, a new keyword is used to create an instance of a string. The string object has some
disadvantages, for example, the execution speed is slow. Now, we can see an example of string
creation.
Example:
<!DOCTYPE html>
<!-- Program for illustration of String Object-->
<HTML>
<HEAD>
<TITLE>
String Object
</TITLE>
</HEAD>
<BODY>
<h2>String</h2>
<script>
var name = "Welcome Khushalkumar"; //literal
var dept = "Computer";
document.write(name);
document.write("<br>He belongs to " + dept + " Department.");
</script>
</BODY>
</HTML>
String as Object
JavaScript String Object is a universal object that is used to store strings. A string is a combination of
letters, numbers, special characters (single or double quotations) and arithmetic values.
Example:
<!DOCTYPE html>
<!-- Program for illustration of String Object-->
<HTML>
<HEAD>
<TITLE>
String Object
</TITLE>
</HEAD>
<BODY>
<h2>String Object</h2>
<script>
var msg = new String("Welcome to JavaScript");
document.write(msg);
//Comparisons of literal and objects
document.write("<br>");
var s1 = "String"; //literal
var s2 = new String("String"); //object
var s3 = new String("String"); //object
var s4 = "String";
(s1==s2)?document.write("<br>Equal"):document.write("<br>Not Equal");
(s1===s2)?document.write("<br>Equal"):document.write("<br>Not Equal");
(s2===s3)?document.write("<br>Equal"):document.write("<br>Not Equal");
(s2==s3)?document.write("<br>Equal"):document.write("<br>Not Equal");
</script>
</BODY>
</HTML>
Date Object
The Date Object is an inbuilt datatype of JavaScript language. It is used to work with dates and
times. The Date Object is created by using a new keyword, i.e. new Date(). The Date Object can be
used for date and time in terms of millisecond precision within 100 million days before or after
1/1/1970. But using another method we can only get and set the year, month, day, hour, minutes,
second, and millsecond fields using local UTC or GMT. So, we can represent the date and time till
the year 275755 using the Date object.
There are four different ways to declare a date, the basic thing is that the date objects are created by
the new Date() operator.
Syntax:
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hour, minute, second, millisecond)
Example:
<!DOCTYPE html>
<!-- Program for illustration of Date Object-->
<HTML>
<HEAD>
<TITLE>
Date Object
</TITLE>
</HEAD>
<BODY>
<h2>Date Object</h2>
<script>
//dt is a Date object
var dt = new Date();
document.write(dt +"<br>");
Math Object
The Math Object includes mathematical constants and functions. It provides many arithmetic and
trigonometric functions. You do not need to create the Math object before using it.
Syntax for using Math Object
var sqrt_value = Math.sqrt(16);
Example:
Window Object
The Window object is at the very top of the object hierarchy. Window object is parent object of all
other objects. It represents an open window in a browser. An object of window is created
automatically by the browser.
Following table shows some of the methods and properties for window object.
Properties of window Object
Property Description
document Returns the document object for the window.
location Returns the location object for the window.
name Sets or returns the name of a window.
status Sets the text in the status bar of a window.
closed Returns a Boolean value indicating whether a window has been closed or not.
Example:
The following code opens the sites in multiple new windows.
Example:
The following code displays an alert box after 5 seconds (5000 milliseconds).
Navigator Object
JavaScript Navigator Object is used to fetch information related to the browser (useragent), like the
browser name, browser version, operating system information etc.
JavaScript Navigator object is also a property of the JavaScript Window object and can be accessed
using the read-only property window.navigator for the current browser window.
In JavaScript, the Navigator Object includes some properties and methods which help us to navigate
from one element to another.
vibrate() If supported, this can be used to make the device vibrate, if not
supported, nothing happens. This is useful in mobile browsers.
Example:
Events
The change in the state of an object is known as an Event. In html, various events represent that
some activity is performed by the user or by the browser. When JavaScript code is include in HTML,
JS react to these events and allow the execution. This process of reacting to events is called Event
Handling. Thus, JS handles the HTML, events via Event Handlers.
For example, when a user clicks over the browser, add JS code, which will execute the task to be
performed on the event.
There are different types of Events.
Mouse Event
Frame Event
Form Event
Keyboard Event
Mouse Event
A mouse event is an event that gets generated when the mouse interacts with html elements that are
registered to the mouseEvent object. There are different events related to mouse event like a mouse
click, mouse over, mouse out, etc. Whenever a mouse event is generated some activity of action is
performed by the browser. The action performed to handle a mouse event is called mouse event
handler.
Types of Mouse Event
Click: click event occurs when the mouse is clicked on the register element. the name of the
event handler is onclick.
Mouseup: mouseup event occurs when the button of the mouse is released over an element. The
name of the event handler is onmouseup.
Mousedown: mousedown event occurs when the button of the mouse is pressed over an element.
The name of the event handler is onmousedown.
Mousemove: mousemove event occurs when the button of the mouse move over an element. The
name of the event handler is onmousemove.
Mouseover: mouseover event occurs when the mouse cursor moves onto the element. The name
of the event handler is onmouseover.
Mouseout: mouseout event occurs when the mouse cursors out of an element. The name of the
event handler is onmouseout.
Example:
Form Events
A form event in JavaScript gets triggered when a user loses focus, or in a sense, the user wants to
make modifications to the form control value. Modification of the value includes a selection of any
check box of the form, making modifications on the opened form which has lost its focus or
changing the typed text, etc. All these events, which get defined inside a form and can act as an event
for the user, act as JavaScript Form Events. Overall, when the user changes the form and the events
associated constitutes JavaScript Form Events as successful.
Various Form Events in JavaScript
There are various form events in JavaScript that work concerining the scenarios and events which the
user can create once the focus is apart from the actual focus control view:
onBlur: This is an event that arises when a user leaves an empty input field and does not even try to
create or type any extra text on the form.
Example:
This program illustrates the onblur From Event in JavaScript, where the user leaves the input field
empty and then tries to give output as shown:
Keyboard Events
Whenever a user presses any key on the Keyboard, different events are fired. There are three
keyboard events, namely keydown, keypress, and keyup. Keyboard events belong to
the KeyboardEvent object.
List of keyboard events
Property Description
Onkeydown The event occurs when the user is pressing a key.
Onkeypress The event occurs when the user presses a key.
Onkeyup The event occurs when the user releases a key.
Example:
onChange:
This is an event that arises when a user tries to open the form and does not type or enter any text into
the form, and then the user leaves the field empty. Also, the user tries to select the value from a
dropdown list as entitled in the form.
Example:
This program illustrates the onChange Form Event in JavaScript where the user leaves the input field
as empty and then tries to give select one of the field values from the dropdown, and then after
selection, it gets ready for the listed values.
onFocus:
This is a special event that behaves in a way that when a user is willing to highlight or turn the focus
on some event by highlighting the background of the text or the text as an input to it.
Example:
This program illustrates the Onfocus Form Event in JavaScript where the user leaves the input field
as empty and then tries to select and click the button, which is an event performed by the user to
highlight the important text which is written in the highlighted text by the users as shown in the
output of the give program.
onSelect:
This is a form event in JavaScript where the user tries to put some text as input to the text field and
then displays it to perform further action on the form.
Example:
This program illustrates the form event of the selecting text and then submitting it to the final value.
onSubmit:
This is a form event in which the user tries to make some input by putting text on the form event, and
then it selects that file which asks the user to give some text as input which on submitting as a form
event can perform further action like referring to the next page in moving on to the next segment.
Example:
This program illustrates the form of selecting the text and then submitting it to the final value.
onReset:
onReset is a form event where the user tries to click on the reset button to make the form event
appear or the control view to be appearing the same as the previous form, which initially the user
was trying to do.
Example:
This program illustrates the onreset form event where the user tries to reset the form.
onKeyDown:
Onkeydown is a form event where the user clicks on the form to perform an event where the user
presses and holds a down key.
Example:
This program illustrates the event where the user presses the keys of onkeydown.
Unit – III
What is PHP?
PHP originally stood for Personal Home Page.
It was created in 1994 by Rasmus Lerdorf.
PHP came to means PHP: Hypertext Preprocessor.
The definition basically means that PHP handles data before it becomes HTML – which
stands for Hypertext Markup Language.
PHP is “A popular general-purpose scripting language that is especially suited to web
development”.
PHP can be embedded into HTML means that PHP code can be written within your HTML
code.
HTML being the language with which all web pages are built.
Therefore, programming with PHP starts off as only slightly more complicated than handling
code in HTML.
PHP is a scripting language, as opposed to a compiled language.
This means that PHP is designed to do something only after an event occurs.
These technologies allow developers to create web application that are dynamically
generated, taking into account whichever elements the programmer desires.
Characteristics of PHP
PHP is much easier to learn and use.
PHP was written specifically for dynamic web page creation.
PHP is both free and cross platform.
PHP is the most popular tool available for developing dynamic websites.
2. After the initial PHP tag, add some comments to your script:
/* Filename : hello3.php */
3. In front of the print statement, type //.
4. After the closing PHP tag add an HTML comment:
<!--This is an HTML comment. -->
5. Save the script as hello3.php, place it on your PHP enabled server, and run the page in your
web browser.
6. View the source of the page to see the HTML comment.
Variables
What are Variables?
A variable is a container for data.
Once data has been stored in a variable, that data can be altered, printed to the browser, saved
to a database, emailed, and so forth.
Variable in PHP are, by their nature flexible.
You can put data into a variable, retrieve that data from it, put new data in it, and continue
this cycle as many times as necessary.
But variables in PHP are largely temporary.
Most only exist that is, they only have a value for the duration of the script’s execution on the
server.
Once the execution of the script completes, those variables cease to exist.
Furthermore, after they are taken to a new page that may have an entirely separate set of
variables.
Variable Syntax
PHP has some predefined variable however you can create your own variables, once you understand
the proper syntax. To create appropriate variable names, you must follow these rules:
All variable names must be preceded by a dollar sign ($).
Following the dollar sign, the variable name must begin wih either a letter (A-Z, a-z) or an
underscore (_). A number cannot immediately follow the dollar sign.
The rest of the variable name can contain any combination of letters, underscores, and
numbers.
Types of Variables
There are three types of variables:
1. Numbers
PHP breaks numbers into two types: integers and floating-point.
The first type of numbers – integers – is also known as whole numbers. They can positive or
negative but include neither fractions nor decimals.
Numbers that use a decimal point are floating point numbers, also known as float.
You use floating point number to refer to fractions, because they only way to express a fraction
in PHP is to convert it to its decimal equivalent.
2. Strings
A string is any number of characters enclosed within a pair of either single (‘) or double (“)
quotation marks.
String can contain any combination of characters that exist: letters, numbers, symbols, and
spaces.
Strings can also contain variables.
When PHP hits the second quotation mark in the example, it assumes the string ends there; the
continuing text causes an error. To use quotation mark within a string you escape the quotation
mark by putting a backslash (\) before it.
The backslash tells PHP to treat each escaped quotation mark as part of the value of the string,
rather than using it as the string’s opening or closing indicators.
3. Arrays
Arrays use keys to create and retrieve the values they store.
The resulting structure of list of key-value pairs-is similar to a two-column spreadsheet.
Unlike arrays in other programming languages, the array structure in PHP is so flexible that it
can use either numbers or strings for both the keys and the values.
The array doesn’t even need to be consistent in this respect.
PHP supports two kinds of arrays, based on the format of the keys. If the array uses numbers
for the keys, it’s known as an indexed array. If it uses strings for the keys, it’s an associative
array. In either case, the values in the array can be of any variable type.
Variable Values
To assign a value to a variable, regardless of the variable type, you use the equals sign(=). Therefore,
the equals sign is known as the assignment operator, because it assigns the value on the right to the
variable on the left. For example:
$number = 1;
$fnumber = 1.2;
$string = “Hello”;
Each of these lines represents a complete statement. So each concludes with a semicolon.
To print the value of a variable, use the print function:
print $number;
print $fnumber;
print $string;
If you want to print a variable’s value within a context, you can place the variable’s name in the
printed string, as long as you use double quotation marks:
print “Number is $number”;
print “String is $string”;
Using print in this way works for the scalar variable types – number and strings. For complex
variable types – arrays and objects – you cannot just use print.
print “_SERVER is $_SERVER”;
<html lang=”en”>
<head>
<meta charset= “utf-8”>
<title>Variables</title>
</head>
<body>
<?php
//Single or double quotation marks won’t matter here
$first_name = ‘Larry’;
$last_name = “Ullman”;
//Single or double quotation marks does matter here
$name1 = ‘$first_name $last_name’;
$name2 = “$first_name $last_name”;
//single or double quotation marks does matter here
print “<h1>Double Quotes</h1>
<p1>name1 is $name1<br>
name2 is $name2</p>;
printf ‘<h1>$Single Quates</h1>
<p1>name1 is $name1<br>
name2 is $name2</p>;
?>
</body>
</html>
To use quotation marks
1. Begin a new PHP script in your text editor or IDE, to be named quotes.php.
2. Create the initial HTML tags.
3. Begin the PHP code.
4. Create two string variables.
5. Create two different name variables, using the existing first_name and last_name variables.
6. Print out the variables using both types of quotation marks.
7. Complete the PHP section and the HTML page.
8. Save the file as quotes.php, upload it to your server and test it in your browser.
For the HTML form the following example you’ll create a feedback page that takes the user’s
salutation, name, email address, response, and comments. The code that generates form goes
between opening and closing form tags:
<form>
Form elements
</form>
The form tages dictate where a form begins and ends. Every element of the form must be entered
between these two tags. The opening from tag should also contain an action attribute. It indicates
the page to which the form data should be submitted. This value is one of the most important
considerations when you’re creating a form.
<form action = “somepage.php”>
To create HTML form
1. Begin a new document in your text editor or IDE to be named feedback.html.
2. Add the opening form tag.
3. Add a select menu plus a text input for the person’s name.
4. Add a text input for the user’s email address.
5. Add radio buttons for a response.
6. Add a textarea to record the comments.
7. Add the submit button.
8. Close the form.
9. Complete the page.
10. Save the page as feedback.html and view it in your browser.
Feedback.html
<html>
<head>
<meta charset=”utf-8”>
<title>Feedback Form</title>
</head>
<body>
<!--- feedback.html --->
<div><p>Please Complete this form to submit your feedback:</p>
<form action=”handle_form.php”>
<p>Name : <select name=”title” required>
<option value = “Mr.”>Mr. </option>
<option value = “Mrs.”>Mrs.</option>
<option value = “Ms.”>Ms.</option>
</select> <input type= “text” name= “name” size= “20” required>
</p>
<p>
Response : This is …
<input type = “radio” name = “response” value = “excellent” required> excellent
<input type = “radio” name = “response” value= “okay”> okay
<input type = “radio” name = “response” value = “boring” > boring
</p>
<p>
Comments: <textarea name = “comments” rows= “3” cols= “30” required > </textarea> </p>
<input type= “submit” name= “submit” value= “Send My Feedback”>
</form>
</div>
</body>
</html>
Choosing a Form Data in PHP
The experienced HTML developer will notice that the feedback form just created is missing one
thing. The initial form tag has no method attribute. The method attribute tells the server how to
transmit the data from the form to the handling script.
You have two choice with method : GET and POST. With respect to forms, the difference between
using GET and POST is squarely in how the information is passed from the form to the processing
script. The GET method sends all the gathered information along as part of the URL. The POST
method transmits the information invisibly to the user. For example, upon submitting a form, if you
use the GET method, the resulting URL will be something like
http://example.com/page.php?var=value&age=20&...
Following the name of the script, page.php, is a question mark, followed by one name=value pair
for each piece of data submitted.
When using the POST method, the end user will only see. http://example.com/page.php.
When deciding which method to use, keep in mind these four factors:
With the GET method, a limited amount of information can be passed.
The GET method sends the data to the handling script publicly.
A page generated by a form that used the GET method can be bookmarked, but one based on
POST can’t be.
Users will be prompted if they attempt to reload a page accessed via POST but will not be
prompted for pages accessed via GET.
Now you need to write script that will receive and process the submitted form data.
For above example the PHP script will simply repeated what the user entered into the form.
To access the submitted form data, you need to refer to a particular predefined variable.
When it comes to handling form data, the specific variable the PHP script would refer to is
either $_GET or $_POST.
If an HTML form uses the GET method, the submiited form data will be found in $_GET.
When an HTML form uses the POST method, the submitted form data will be found in
$_POST.
$_GET and $_POST, besides being predefined variables are arrays, a special variable type
($_SERVER is also an array).
This means that both $_GET and $_POST may contain numerous values, making the
printing of those values more challenging.
Example: Form data submitted to the script is displayed by referencing the associated $_POST variable
<html lang= “en”>
<head>
<title>Your Feedback</title>
</head>
<body>
<?php //Script handle_form.php
//It will receive: title, name, email, respose, comments, and submit in $_POST
//Create shorthand versions of the variables:
$title = $_POST[‘title’];
$name = $_POST[‘name’];
$response = $_POST[‘response’];
$comment = $_POST[‘comment’];
//Print the received data:
print “<p>Thank you, $title $name, for your comments. </p>
<p>You stated that you found this example to be ‘$response’ and added: <br>$comments</p>”;
?>
</body>
</html>
To handling an HTML form:
1. Begin a new document in your text editor of IDE, to be named handle_form.php.
2. Add the opening PHP tag and any comments.
3. Assign the received data to new variables.
4. Print out the user information.
5. Close the PHP section, and complete the HTML page.
6. Save the script as handle_form.php.
7. Upload the script to the server, making sure it’s saved in the same directory as
feedback.html.
8. Load feedback.html in your browser through a URL.
9. Fill out and then submit the form.
Displaying Errors
To have PHP display errors, you can do one of the following:
Turn display_errors back on the PHP as a whole.
Turn display_errors back on for an individual script.
While developing a site, the first option is by far preferred. However, it’s a possibility only for those
with administrative control over the server. But anyone can use the second option by including this
line in a script:
ini_set(‘display_errors’,1);
The ini_set() function allows a script to temporarily override a setting in PHP’s configuration file.
To display errors in a script
1. Open handle_form.php in your text editor or IDE, if it is not already open.
2. As the first line of PHP code, enter the following: ini_set(‘display_error’,1);
3. Save the file as handle_form.php.
4. Upload the file to your web server, and test it in your browser.
<html lang= “en”>
<head>
<title>Your Feedback</title>
</head>
<body>
<?php //handle_form.php
ini_set(‘display_errors’,1); //let me learn from my mistakes
//This page receives the data from feedback.html
//It will receive: title, name, email, response, comments, and submit in $_POST
//Create shorthand version of the variables.
$title = $_POST[‘title’];
$name = $_POST[‘name’];
$response = $_POST[‘response’];
$comments = $_POST[‘comment’];
//Print the received data :
print “<p>Thank you, $title $name, for your comments.</p>
<p> You stated that you found this example to be ‘$response’ and
added:<br>$comments</p>”;
?>
</body>
</html>
Error Reporting
PHP has more than a dozen different levels of errors, and you can define your own.
You can set what errors PHP reports on in two ways.
First, you can adjust the error_reporting level in PHP’s configuration file. If you are
running your own PHP server, you’ll probably want to adjust that global setting while
developing your scripts.
The second option is to use the error_reporting() function in a script. The function takes
either a number or one or more constants – nonquoted strings with predetermined meanings –
to adjust the levels.
Using Numbers
Creating the Form
Most of the PHP example will perform various calculation based on an e-commerce premise.
A form will take price, quantity, discount amount, tax rate, and shipping cost and PHP script
that handles the form will return a toal cost.
That cost will also be broken down by the number of payments the user wants to make in
order to generate a monthly cost value.
To start, let’s create an HTML page that allows the user to enter the values.
To create the HTML form
1. Begin a new HTML document in your text editor or IDE, to be named calculator.html.
2. Create the initial form tag: <form action= “handle_calc.php” method= “post”>.
3. Create the inputs for the price, quantity, discount and tax.
4. Add a field in which the user can select a shipping method.
5. Complete the HTML form.
6. Complete the HTML page.
7. Save the script as calculator.html and view it in your browser.
Calculator.html
<html>
<head>
<title>Product Cost Calculator</title>
</head>
<body><!---Script Calculator.html -->
<div> <p> Fill out this form to calculate the total cost :</p>
<form action = “handle_calc.php” method= “post”>
<p>Price : <input type = “text” name= “price” size= “5”></p>
<p>Quantity : <input type = “number” name= “quantity” size= “5”
min= “1” value= “1”></p>
<p>Discount : <input type = “text” name= “discount” size= “5”></p>
<p>Tax : <input type = “text” name= “tax” size= “5”>(%)</p>
<p>Shipping method: <select name= “shipping”>
<option value= “5.00”>Slow and steady</option>
<option value= “8.95”>Put a move on it.</option>
<option value= “19.36”>I need it yesterday!</option>
</select></p>
<p>Number of payment to make: <input type= “number” name=
“payment” size= “5” min= “1” value= “1”</p>
<input type= “submit” name= “submit” value= “Calculate!”>
</form>
</div>
</body>
</html>
Performing Arithmetic
Like in grade school, basic mathematics involves the principles of addition, subtraction,
multiplication, and division. These are performed in PHP using the most obvious operators:
Addition
Subtraction
Multiplication
Division
To create your sales cost calculator
1. Create a new document in your text editor or IDE, to be named handle_calc.php.
2. Insert the PHP tag and address error handling, if desired.
3. Assign the $_POST elements to local variables.
4. Begin calculating the total cost.
5. Calculate the tax rate and the new total.
6. Calculate the monthly payment.
7. Print the results.
8. Close the PHP section.
9. Save the script as handle_calc.php and place it in the proper directory for your PHP enabled
server.
10. Test the script in your browser by filling out and submitting the form.
Handle_calc.php
<html lang= “en”>
<head>
<title>Product Cost Calculator</title>
<style type= “text/css”>
.number{font-weight: bold;}
</style>
</head>
<body>
<?php //handle_calc.php
/*This script takes values from calculator.html and performs total cost and
monthly payment calculations. */
//Get the values from the $_POST array:
$price = $_POST[‘price’];
$quantity = $_POST[‘quantity’];
$discount = $_POST[‘discount’];
$tax = $_POST[‘tax’];
$shipping = $_POST[‘shipping’];
$payments = $_POST[‘payments’];
Formatting Numbers
Although the calculator is on its way to being practical, it still has one legitimate problem:
you can’t ask someone to make a monthly payment of $10.12183333! to create more usable
numbers, you need to format them.
Two functions are appropriate for this purpose. The first round(). Rounds a value to specified
number of decimal places. The function’s first argument is the number to be rounded. This
can be either a number or a variable that has a numeric value.
The second argument is optional; it represents the number of decimal places to which to
round. If omitted, the number will be rounded to the nearest integer.
For example:
round(4.30); //4
round(4.289,2); //4.29
$num = 239.26985;
round($num); //239
The other function you can use in this situation is number_format(). It works like round() in
that it takes a number and an optional decimal specifier. This function has the added benefit
of formatting the number with commas, the way it would commonly be written:
number_format(428.4959,2); //428.50
number_format(428,2); //428.00
number_format(12345687); //1,234,5687
To format numbers
1. Open handle_calc.php in your text editor or IDE, if it is not already open.
2. After all the calculations but before the print statement, add the following:
$total = number_format($total,2);
$monthly = number_format($monthly,2);
3. Save the file, place it in the same directory as calculator.html and test it in your browser.
Handle_calc.php
Understanding Precedence
Precedence refers to the order in which a series of calculations are executed.
For example, what is the value of the following variable?
$number = 10-4/2;
Is $number worth 3(10 minus 4 equals 6, divided by 2 equals 3) or 8(4 divided by 2 equals
2, subtract from 10 equals 8)?
The answer here is 8, because division takes precedence over subtraction.
To manage precedence
1. Open handle_calc.php in your text editor or IDE, if it is not already open.
2. Replace the three lines that initially calculate the order total.
3. Change the two lines that calculate and add in the tax to this.
4. Save the script, place it in the same directory as calculation.html and test it in your browser.
Handle_calc.php
<html lang= “en”>
<head>
<title>Product Cost Calculator</title>
<style type= “text/css”>
.number{font-weight: bold;}
</style>
</head>
<body>
<?php //handle_calc.php
/*This script takes values from calculator.html and performs total cost and
monthly payment calculations. */
//Get the values from the $_POST array:
$price = $_POST[‘price’];
$quantity = $_POST[‘quantity’];
$discount = $_POST[‘discount’];
$tax = $_POST[‘tax’];
$shipping = $_POST[‘shipping’];
$payments = $_POST[‘payments’];
Solely for the sake of testing this concept, you’ll rewrite the handle_calc.php script one last time.
To increment the value of a variable
1. Open handle_calc.php in your text editor or IDE, if it is not already open.
2. Change the tax rate calculation from:
$taxrate = $tax/100;
$taxrate++;
3. Save the script, place it in the same directory as calculation.html, and test it in your browser.
Handle_calc.php
<html lang= “en”>
<head>
<title>Product Cost Calculator</title>
<style type= “text/css”>
.number{font-weight: bold;}
</style>
</head>
<body>
<?php //handle_calc.php
/*This script takes values from calculator.html and performs total cost and
monthly payment calculations. */
//Get the values from the $_POST array:
$price = $_POST[‘price’];
$quantity = $_POST[‘quantity’];
$discount = $_POST[‘discount’];
$tax = $_POST[‘tax’];
$shipping = $_POST[‘shipping’];
$payments = $_POST[‘payments’];
//Calculate the total:
$total = (($price * $quantity) + $shipping) - $discount;
//Determine the tax rate:
$taxrate = $tax/100;
$taxrate++;
//Factor in the tax rate:
$total = $total * taxrate;
//Calculation the monthly payments:
$monthly = $total/$payments;
//Apply the proper formatting:
$total = number_format($total,2);
$monthly = number_format($monthly,2);
//Print out the results:
print “<p>You have selected to purchase:<br>
<span class= \ “number\”>$quantity</span> widget(s) at <br>
Using String
A second category of variables used by PHP is string - a collection of characters enclosed
within either single or double quotation marks.
The values of a string variable may be single letter, a word, a sentence, a paragraph, HTML
code, or even a jumble of nonsensical letters, numbers, and symbols.
Strings may be the most common variable type used in PHP.
<body>
<div><p>Please complete this form to submit your posting :</p>
<form action= “handle_post.php” method = “post”>
<p>First Name :<input type= “text” name= “first_name” size= “20”> </p>
<p>Last Name :<input type= “text” name= “last_name” size= “20”></p>
<p>Email Address :<input type= “email” name= “email” size= “30”></p>
<p>Posting: <textarea name= “posting” row= “9” cols= “30”></textarea></p>
<input type= “Submit” name= “submit” value= “Send My Posting”>
</form>
</body>
</html>
Concatenating Strings
Concatenation is an unwieldy term but a useful concept. It refers to the appending of one item onto
another. Specifically, in programming, you concatenate strings. The period (.) is the operator for
performing this action, and it’s used like so:
$s1= ‘Hello,’;
$s2 = ‘world!’;
$greeting = $s1.$s2;
The result of this concatenation is that the $greeting variable has a value of Hello, World!
Because of the way PHP deals with variables, the same effect could be accomplished using
$greeting = “$s1$s2”
This code works because PHP replaces variables within double quotation makrs with their value.
However, the formal method of using the period to concatenate strings is more commonly used and
is recommended.
Another way of performing concatenation involves the concatenation assignment operator.
$greeting = ‘Hello,’;
$greeting .= ‘World!’;
This second line roughly means “assign to $greeting is current value plus the concatenation of
world!” The end result is $greeting having the value Hello, World! once again.
The posting.html script sends several string variables to the handle_post.php page. Of those
variables, the first and last names could logically be concatenated.
To use concatenation
1. Begin a new document in your text editor or IDE, to be named handle_post.php.
2. Create the initial PHP tag, and address error management, if necessary.
3. Assign the form data to local variables.
4. Create a new $name variable using concatenation.
Handling Newlines
A common question beginning PHP developers have involved newlines in strings. The textarea
form element allows a user to enter text over multiple lines by pressing Return/Enter. Each use of
Return/Enter equates to a newline in the resulting string. These newlines work within a textarea but
have no effect on a rendered PHP page.
To create the equivalent of newlines in a rendered web page, you use the break tag: <br>.
Fortunately, PHP has the nl2br() function, which automatically converts newlines into break tags;
$var = nl2br($var);
Let’s apply this function to handle_post.php so that the user’s posting retains its formatting.
To convert newlines to breaks:
1. Open handle_post.php.
2. Apply the nl2br() function when assigning a value to the $posting variable.
3. Save the file, place it in the same directory as posting.html and test again in your browser.
Comparing Strings
To compare two strings, you can always use the equality operator. Otherwise, you can use the
strcmp() function. It indicates how two strings compare by returning a whole number: 0 if they are
the same, and a positive or negative number if one is “greater” than the other. PHP also has a case-
insensitive companion, strcasecmp().
To see if a substring is contained within another string, you’ll use these functions:
strstr() returns the haystack from the first occurrence of a needle to the end.
strpos() searches through a haystack and returns the numeric location of a particular need.
Both of these functions also have a case insensitive alternative: stristr() and stripos(), respectively.
Each of these functions is normally used in a conditional to test whether the substring was found.
Finding Substrings
PHP has a few function you can use to pull apart string, search through them, and perform
comparisons. Although these functions are normally used with conditionals. The strtok() function
creates a substring, referred to as a token, from a larger string by using a predetermined separator.
For example, if you have users enter their full name in one field, you can pull out their first name
with this code:
$first = strtok($_POST[‘name’], ‘’);
That line tells PHP to extract everthing from the beginning of $_POST[‘name’] until it finds a blank
space.
If you have users enter their full name in the format Surname, First, you can find their surname by
writing $last = strtok($_POST[‘name’], ‘’);
A second way to pull out sections of a string is by referring to the indexed position of the characters
within the string. The indexed position of a string is the numerical location of a character, counting
from the beginning. However, PHP – like most programming languages – begins all indexes with the
number 0.
You can use the substr() function to create a substring based on the index position of the substring’s
characters:
$sub = substr($string, 0,10);
The first argument is the master string from which the substring will be divided. Second, indicate
where the substring begins, as its indexed position. Third, from that starting point, state how many
characters the substring should contain. If the master string does not have that many characters in it,
the resulting substring will end with the end of the master string. This argument is optional; if
omitted, the substring will also go until the end of the master string.
You can also use negative numbers to cound backward from the end of the string:
$string = ‘aardvard’;
$sub = substr($string, -3,3);
Handle_post.php
<html lang= “en”>
<head>
<title>Forum Posting</title>
</head>
<body>
<?php //handle_post.php
/*This script receives five values from posting.html first_name, last_name,
email, posting and submit*/
//Get the value from the $_POST array:
$first_name = $_POST[‘first_name’];
$last_name = $_POST[‘last_name’];
$posting = n12br($_POST[‘posting’]);
//Create a full name variable
$name = $first_name. ‘’.$last_name;
//Get a word count:
$word = str_word_count($posting);
//Get a snipped of the posting
$posting = substr($posting,0,50);
//Print a message:
print “<div>Thank you, $name, for your posting:
<p> $posting…</p>
<p>($words words)</p></div>”;
?>
</body>
</html>
To create substrings
1. Open handle_post.php.
2. Before the print statement, add the following:
$word = str_word_count($posting);
3. On the next line, add
$posting = substr($posting,0,50);
4. Update the print statement to read
print “<div>Thank you, $name, for your posting: <p> $posting…</p>
<p>($words words)</p></div>”;
5. Save the file, place it in the proper directory of you PHP-enabled browser.
Adjusting String Case
A handful of PHP functions are used to change the case of a string’s letters:
ucfirst() capitalizes the first letter of the string.
ucwords() capitalizes the first letter of words in a string.
strtoupper() makes an entire string uppercase.
strtolower() makes an entire string lowercase.
Control Structure
Control structures – conditionals and loops – are a staple of programming languages. PHP has two
conditionals – if and switch. Conditionals allow you to establish a test and then perform actions
based on the results. This functionality provides the ability to make websites even more dynamic.
If conditionals require introduction of two last categories of operators: comparison and logical.
You’ll commonly use these operators in your conditionals, along with the Boolean concepts of
TRUE and FALSE.
9. Save the file as register.html, place it in the proper directory for you PHP enabled server,
and load the page in your browser.
Register.html
<html lang = “en”>
<head>
<meta charset= “utf-8”>
<title>Registration Form</title>
</head>
<body>
<!—script register.html -->
<div><p>Please complete this form to register:</p>
<form action = “handle_reg.php” method= “post”>
<p>Email Address : <input type= “text” name= “email” size= “30”></p>
<p>Password : <input type= “password” name= “password” size= “20”></p>
<p>Confirm Password:<input type=“password” name=“confirm” size=“20”></p>
<p>YearYouWereBorn:<input type=“text” name=“year” value=“YYYY” size=“4”></p>
<p>Favorite Color:
<select name= “color”>
<option value= “”>Pick One</option>
<option value= “red”>Red</option>
<option value= “yellow”>Yellow</option>
<option value= “green”>Green</option>
<option value= “blue”>Blue</option>
</select></p>
<p><input type= “checkbox” name= “terms” value= “Yes”> I agree to the
terms (Whatever they may be). </p>
<input type= “submit” name= “submit” value= “Register”>
</form>
</body>
</html>
The if Conditional
The basic programming conditional is the standard if. The syntax for this kind of conditional is
simple:
if(condition)
{
Statement(s);
}
The condition must go within parentheses: then the statement(s) are placed within braces. The
statements are commands to be executed – for example, printing a string or adding two numbers
together. Each separate statement must have its own semicolon indicating the end of the line, but
there’s no limit on the number of statements that can be associated with a conditional.
To create an if conditional:
1. Begin a new document in your text editor of IDE, tobe named handle_reg.php.
2. Begin the PHP section and address error management, if necessary.
3. Create a flag variable:
$okay = true;
4. Print a message if everything is all right.
5. Complete the PHP section and the HTML page.
6. Save the file as handle_reg.php, place it in the proper directory for you PHP enabled server,
and test both in your browser.
Handle_reg.php
<html lang= “en”>
<head>
<title>Registration</title>
</head>
<body><h1>Registration Results</h1>
<?php
/*This script receives seven values from register.html: email,
password, confirm, year, terms, color, submit */
//Address error management, if you want
//Flag variable to track success:
$okay = true;
//If there were no errors, print a success message:
if($okay){
print “<p>You have been successfully registered (but not really).</p>”; }
?>
</body>
</html>
Validation Functions
PHP has dozens of functions commonly used to validate form data. Of these functions, three of the
most important ones are used.
First up is the empty() function, which checks to see if a given variable has an “empty” value. A
variable is considered to have an empty value if the variable has no value, has a value of 0, or has a
value of FALSE. In any of these cases, the function returns TRUE; otherwise, it returns FALSE:
$var1 = 0;
$var2 = ‘something’;
empty($var1);
Next is the isset() function, which is almost the opposite of empty(), albeit with a slight difference.
The isset() function return TRUE if a variable has any value. If the variable does not have a value,
isset() returns FALSE.
$var1=0;
$var2= “something”;
$var3= “”;
isset($var); //FALSE, no defined value
isset($var1); //TRUE
isset($var2); //TRUE
isset($var3); //TRUE
Finally, the is_numeric() function returns TRUE if the submitted variable has a valid numerical
value and FALSE otherwise. Integers, decimals, and even strings can all pass the is_numeric() test:
$var1=2309;
$var2= “80.23”;
$var3= “Bears”;
is_numeric($var1); //TRUE
is_numeric($var2); //TRUE
is_numeric($var3); //FALSE
An interesting thing to note is that using is_numeric() on a variable that doesn’t exist not only
returns FALSE, but also generates a warning. For this reason, you’ll often see isset() used along with
other validation functions like is_numeric().
Handle_reg.php
<html lang= “en”>
<head>
<meta charset = “utf-8”>
<title>Registration</title>
<style type= “text/css” media= “screen”>
.error { color:red; }
</style>
</head>
<body>
<h1>Registration Results</h1>
<?php
/*This script receives seven values from register.html: email,
password, confirm, year, terms, color, submit */
//Address error management, if you want
//Flag variable to track success:
$okay = true;
//Validate the email address:
if(empty($_POST[‘email’]))
{
Using else
This control structure allows you to execute one or more statements when a condition is TRUE and
execute one or more other statements when the condition is FALSE.
if(condition)
{
Statement(s)
}
else
{
Other_statements(s);
}
The important thing to remember when using this construct is that unless the condition is explicitly
met, the else statement will be executed. In other words, the statements after the else constitute the
default action, whereas the statements after the if condition are the exception to the rule.
To use else
Developed By. Dr. Munesh Thakre Page 229 of 306
Web Engineering BE CSE SEM-VII
1. Open handle_reg.php.
2. After the password validation but before the $okay conditional, begin a new conditional.
if(is_numeric($_POST[‘year’])){
3. Create a new variable:
$age = 2016 - $_POST[‘year’];
4. Add an else clause:
} else {
5. After the final print statement but within the same $okay conditional, also print out the value
of $age.
6. Save you script, place it in the same directory as register.html and test it in your browser
again.
Handle_reg.php
<html lang= “en”>
<head>
<title>Registration</title>
<style type= “text/css” media= “screen”>
.error { color:red; }
</style>
</head>
<body><h1>Registration Results</h1>
<?php
/*This script receives seven values from register.html: email,
password, confirm, year, terms, color, submit */
//Address error management, if you want
//Flag variable to track success:
$okay = true;
//Validate the email address:
if(empty($_POST[‘email’]))
{
print “<p class= “error”>Please entery your email address.</p>”;
$okay=false;
}
//Validate the password:
if(empty($_POST[‘password’]))
{
print “<p class= “error”>Please enter your password.</p>”;
$okay=false;
}
//Validate the birth year:
if(is_numeric($_POST[‘year’]))
{
$age = 2016 - $_POST[‘year’]; //calculate age this year.
}
else
{
print ‘<p class= “error”>Please enter the year you were born as four digits.</p>’;
$okay = false;
}
//If there were no errors, print a success message:
if($okay){
print “<p>You have been successfully registered (but not really).</p>”;
print “<p>You will turn $age this year.</p>”;}
?>
</body>
</html>
More Operators
PHP’s operators along with the variable types that use them. These operators include arithmetic for
numbers: addition(+), subtraction(-), multiplication(*), and division(/), along with the increament
(++) and decrement(--) shortcuts for increasing or decresing the value of number by 1.
Then there is the assignment operator(=), which is used to set the value of a variable, regardless of
type.
When it comes to creating conditionals, the comparison and logical operators are the most important.
Comparison
The line
$var=5;
Doesn’t state that $var is equal to 5 but that it is assigned the value of 5. This is an important
distinction.
When you’re writing conditionals, you’ll often want to see if a variable is equal to a specific value –
to match usernames or passwords, perhaps, which you can’t do with the equals sign alone. Instead
for comparisons, use the equality operator(==).
$var=5;
if($var==5)
{
….
}
To use comparison operators
1. Open handle_reg.php in you text editor or IDE, if it is not already open.
2. After the password validation, check that the two passwords match.
3. After the year validation, report an error if the year is greater than or equal to 2016.
4. Save your script, place it in the same directory as register.html and test it in you browser
again.
Handle_reg.php
<html lang= “en”>
<head>
<meta charset = “utf-8”>
<title>Registration</title>
<style type= “text/css” media= “screen”>
.error { color:red; }
</style>
</head>
<body><h1>Registration Results</h1>
<?php
/*This script receives seven values from register.html: email,
password, confirm, year, terms, color, submit */
//Address error management, if you want
//Flag variable to track success:
$okay = true;
//Validate the email address:
if(empty($_POST[‘email’]))
{
print “<p class= “error”>Please entery your email address.</p>”;
$okay=false;
}
//Validate the password:
if(empty($_POST[‘password’]))
{
print “<p class= “error”>Please enter your password.</p>”;
$okay=false;
}
//Check the two password for equality:
if($_POST[‘password’] != $_POST[‘confirm’])
{
print ‘<p class= “error”> Your confirmed password does not match the
original password.</p>’;
$okay = false;
}
//Validate the birth year:
if(is_numeric($_POST[‘year’])){
$age = 2016 - $_POST[‘year’]; //calculate age this year. }
else {
print ‘<p class= “error”>Please enter the year you were born as four
digits.</p>’;
$okay = false; }
//Check that they were born before this year
if($_POST[‘year’] >= 2016) {
print ‘<p class= “error”>Either you entered your birth year wrong or
you come from the future!</p>’;
$okay=false; }
//If there were no errors, print a success message:
if($okay) {
print “<p>You have been successfully registered (but not really).</p>”;
print “<p>You will turn $age this year.</p>”;
}
?>
</body>
</html>
Using else if
Similar to the if-else conditional is if-else if. This conditional acts like a running if statement and can
be expanded to whatever complexity you require:
if(condition1)
{
Statement(s);
}
else if(condition2)
{
Other_statement(s);
}
else
{
Other_other_statement(s);
}
Understand that this structure means, for example, that other_statement(s) are only executed if
condition1 is FALSE but condition2 is TRUE. If both conditions are FALSE, the
other_other_statement(s) are executed.
To use elseif
1. Open handle_reg.php.
2. Before the $okay conditional, begin a new conditional.
3. Add an elseif clause for the second color.
4. Add elseif clauses for the other two colors.
Once PHP finds a case that matches the value of the conditional variable, it executes the subsequent
statements. here’s the tricky part: Once PHP has found a matching case, it will continue going
through the switch until it either comes to the end of the switch conditional or hits a break
statement, at which point it exits the switch construct. Thus, it’s imperative that you close every case
even the default case, for consistency’s sake with a break.
To use a switch conditional
1. Open handle_reg.php in your text editor or IDE, if it is not already open.
2. Delete the extended colors conditional.
3. Begin the switch.
4. Create the first case.
5. Add a case for the second color.
6. Add cases for remaining colors.
7. Add a default case and complete the switch.
8. Save your script, place it in the same directory as regiseter.html and test it in your browser
again.
Handle_reg.php
<html lang= “en”>
<head>
<title>Registration</title>
<style type= “text/css” media= “screen”>
.error { color:red; } </style>
</head>
<body><h1>Registration Results</h1>
<?php
/*This script receives seven values from register.html: email,
password, confirm, year, terms, color, submit */
//Address error management, if you want
//Flag variable to track success:
$okay = true;
//Validate the email address:
if(empty($_POST[‘email’]))
{
print “<p class= “error”>Please entery your email address.</p>”;
$okay=false;
}
//Validate the password:
if(empty($_POST[‘password’]))
{
case ‘green’:
$color_type = ‘secondary’;
break;
case ‘blue’:
$color_type = ‘primary’;
break;
default:
print ‘<p class = “error”>Please select your favorite
color.</p>’;
$okay=false;
break;
}
//If there were no errors, print a success message:
if($okay) {
print ‘<p> You have been Successfully registered (but not really).<p>’;
print “<p> You will turn $age this year.</p>”;
print “<p>Your favorite color is a $color_type color.<p>”;
}
?>
</body>
</html>
PHP supports three kinds of loops: for, while and foreach. The while loop is similar to for, but it’s
used most frequently when retrieving values from a database or reading from a text file. The foreach
loop is related to using arrays.
The for loop is designed to perform one or more statements for a determined number of iterations.
You normally use a dummy variable in the loop for this purpose:
for(initial expression; condition; closing expression)
{
Statement(s);
}
The initial expression is executed once: the first time the loop is called. Then the condition is used to
determine whether to execute the statements. The closing expression is executed each time the
condition is found to be TRUE, but only after the statements are executed.
To write a for loop
1. Open registration.html in your text editor or IDE, if it is not already open.
2. Remove the existing birth year prompt and input.
3. Where the birth year prompt was, after the password confirmation and before the color
option, add a prompt and a list of months.
4. Begin a select menu for the day of the month the user was born.
5. Create a new PHP section.
6. Create a for loop to print out 31 days as select menu options.
7. Close the PHP section, and the select element.
8. Save the file as register.php.
9. Place the file in the proper directory for your PHP enabled server.
10. If desired, view the HTML source code to see the PHP generated options.
Register.php
<html lang = “en”>
<head>
<meta charset= “utf-8”>
<title>Registration Form</title>
</head>
<body>
<div><p>Please complete this form the register:</p>
<form action = “handle_reg.php” method = “post”>
<p>Email Address: <input type= “text” name= “email” size= “30”></p>
<p>Password: <input type= “password” name= “password” size= “20”></p>
<p>Password: <input type= “password” name= “confirm” size= “20”></p>
<p>Date of Birth:
The second of the three types of loops that exist in PHP – the while loop – is designed to continue
working as long as the condition you establish is TRUE. Like the for loop, it checks the value of the
condition before each iteration. Once the condition becomes FALSE, the while loop is exited:
while(condition)
{
Statement(s);
}
The main difference between for and while is that while doesn’t include a system for setting initial
conditions or for executing closing expressions.
You also have the option of using the do..while loop, which guarantees that the statements are
executed at least once.
do
{
Statement(s);
}while(condition);
Using Arrays
Arrays are significantly different from numbers or strings, and you can’t make the most of
programming in PHP without understanding them.
Because of their unique nature, this section will cover arrays more deliberately and slowly than the
other variable types.
What is an Array
Arrays constitute a complicated but very useful notion. Whereas numbers and strings are scalar
variables – meaning they always have only a single value – an array is a collection of multiple values
assembled into one overriding variable. An array can consist of numbers and/or strings and/or other
arrays, which allows this one variable to hold exponentially more information than a simple string or
number can. For example, if you wanted to create a grocery list using strings, your code would look
something like this:
$item1 = ‘apples’;
$item2 = ‘bananas’;
$item3 = ‘oranges’;
For each added item, you’d need to create a new string. This approach is cumbersome, and it makes
it difficult to refer back to the entire list or any specific value. You can greatly simplify matters by
placing your entire list into one array.
As an array, your list can be added to, sorted, searched, and so forth. With this context in mind, let’s
look into the syntax of arrays.
Syntactical rules for arrays
The other variable types you’ve dealt with – numbers and strings – have a variable name and a
corresponding value. arrays also have a name, derived using the same conventions:
They begin with a dollar sign.
They continue with a letter or underscore.
They finish with any combination of letters, numbers, or the underscore.
But arrays differ in that they contain multiple elements. An element consists of an index or key the
two words can be used interchangeably and a value.
An array’s index is used as a reference point to the values. An array can use either numbers or strings
as its keys, or both, depending on how you set it up.
Generally, when you use an array it looks the same as any other variable, except that you include a
key in brackets([], sometimes referred to as square brackets) to reference particular values. Whereas
$items refers to the array as a whole, $item[1] points to a specific element in the array.
Creating an Array
The formal method of creating an array is to use the array() function. Its syntax is
$list = array(‘apples’, ‘bananas’, ‘orange’);
Arrays automatically begin their indexing at 0, unless otherwise specified. In that example – which
doesn’t specify an index for the elements – the first item, apples, is automatically indexed at 0, the
second item at 1, and the third at 2.
If you desire, you can assign the index when using array().
$list = array(1=> ‘apples’, 2=> ‘bananas’, 3=> ‘orange’);
Because PHP is very liberal when it comes to blank spaces in your code, you can make this structure
easier to read by writing it over multiple lines:
$list = array(
1 => ‘apples’,
2 => ‘bannas’,
3 => ‘orange’
);
Create array using the short array syntax. Simply use brackets instead of a call to array():
$list = [‘apples’, ‘bananas’, ‘orange’];
Naturally, you can se the indexes with this syntax as well:
$list = [
1 => ‘apples’,
2 => ‘bannas’,
3 => ‘orange’
];
Finally, the index value you specify doesn’t have to be a number – you can use strings instead. As an
example, you could create an array that records the soup of the day for each day of the week, as in
the following script. This example will also demonstrate how you can, and cannot, print out an array.
To create an array
1. Begin a new document in your text editor or IDE, to be named soups1.php.
2. Being the PHP section of the script, and address error handling, if necessary.
3. Create an array.
4. Attempt to print the array.
5. Use the print_r() function to print out the array differently.
6. Close the PHP and the HTML section.
7. Save your document as soups1.php, place it in the proper directory for your PHP-enabled
server, and test it in you browser.
Soups1.php
<html lang = “en”>
<head>
<meta charset= “utf-8”>
<title>No Soup for You!</title>
</head>
<body>
<h1>Mmm….Soups</h1>
<?php
//This script creates and prints out an array
//Address error management, if you want
//Create the array
$soups = [
‘Monday’ => ‘Clam Chowder’,
‘Tuesday’ => ‘White Chicken Chili’,
‘Wednesday’ => ‘Vegetarian’
];
//Try to print the array
print “<p>$soups</p>”;
//Print the contents of the array
print_r($soups);
?>
</body>
</html>
unset($array[4]);
unset($array[‘key’]);
Removing a single element will not re-index the array, however, the code removes one element, no
element is now indexed at 4, and every other element continue to be indexed where they were.
If you apply unset() to an entire array or any other variable type, the whole variable is deleted:
unset($array);
unset($string);
You can also reset an array using the array() function or short array syntax:
$array = array();
$array =[];
This has the effect of initializing the variable: making it exist and defining its type without assigning
a value.
To add elements to an array
1. Open soups1.php in you text editor or IDE, if it is not already open.
2. After the array is initialized on lines 14 through 18, add the following to be named
soups2.php.
3. Add three more elements to the array.
4. Recount how many elements are in the array, and print out this value.
5. Delete this line.
6. Save your script as soups2.php, place it in the proper directory for your PHP-enabled server,
and test it in your browser.
Soups2.php
<html lang = “en”>
<head>
<title>No Soup for You!</title>
</head>
<body>
<h1>Mmm….Soups</h1>
<?php
//This script creates and prints out an array
//Address error management, if you want
//Create the array
$soups = [
‘Monday’ => ‘Clam Chowder’,
‘Tuesday’ => ‘White Chicken Chili’,
‘Wednesday’ => ‘Vegetarian’
];
Merging Arrays
PHP has a function that allows you to append one array onto another. Think of it as concatenation for
arrays. The function array_merge(), work like so:
$new_array = array_merge($array1,$array2);
You could also write the soups2.php page using this function:
$soups2 = [
‘Thursday’ => ‘Chiken Noodle’,
‘Friday’ => ‘Tomato’,
‘Saturday’ => ‘Cream of Broccoli’
];
$soups = array_merge($soups, $soups2);
You could even accomplish this result with the plus sign:
$soups = $soups + $soups2;
Or
$soups += $soups2;
A difference between using array_merge() and the plus sign is that array_merge() will re-index the
arrays in the new array, whereas the plus sign maintains the existing indexes. Also, with array
addition, only elements in the second array indexed at new positions are added in. Any element in
the second array indexed at the same position as an element in the first array will be ignored.
Sorting Arrays
PHP supports a variety of ways to sort an array. Sort refers to an alphabetical sort if the values being
sorted are strings, or a numerical sort if the value being sorted are numbers. When sorting an array,
you must keep in mind that an array consists of pairs of keys and values. Thus, an array can be sorted
based on the keys or the values. This is further complicated by the fact that you can sort the values
and keep the corresponding keys aligned, or you can sort the values and have them be assigned new
keys.
To sort the values without regard to the keys, use sort(). To sort these values in reverse order, use
rsort(). The syntax for every sorting function is:
function_name($array);
So, sort() and rsort() are used as follows:
sort($array);
rsort($array);
To sort the values while maintaining the correlation between each values and its key, use asort(). To
sort the values in reverse while maintaining the key correlation, use arsort().
To sort by the keys while maintaining the correlation between the key and its value, use ksort().
Conversely, krsort() sorts the keys in reverse.
Finally, shuffle() randomly reorganizes the order of an array. Like sort() and rsort(), shuffle() drops
the existing keys in the process.
To sort an array
1. Being a new document in your text editor or IDE, to be named sort.php.
2. Begin the PHP section, an address error handling, if desired.
3. Create the array.
4. Print caption, and then print each element of the array using a foreach loop.
5. Sort the array in reverse order by value to determine who has the highest grade.
6. Print the array again using another loop.
7. Sort the array by key to put the array in alphabetical order by student name.
8. Print a caption and the array one last time.
9. Complete the script with the standard PHP and HTML tags.
10. Save your script as sort.php, place it in the proper directory for your PHP-enabled server,
and test it in your browser.
Sort.php
<html lang = “en”>
<head>
<meta charset = “utf-8”>
<title>My Little Gradebook</title>
</head>
<body>
<?php
//This script creates, sorts, and print out an array
//Address error management, if you want
//Create the array
$grades = [
‘Richard’ => 95,
‘Sherwood’ => 82,
‘Toni’ => 98,
‘Franz’ => 87,
‘Melissa’ => 75,
‘Roddy’ => 85
];
//Print the original array
print ‘<p>Originally the array looks like this:<br>”;
foreach($grades as $student => $grade)
{
print “$student: $grade<br>”;
}
print ‘<p>’;
//Sort by value in revseorder, then print again
arsort($grades);
print ‘<p>After sorting the array by value using arsort(), the array
looks like this:</p>’;
foreach($grades as $student => $grade)
{
print “$student: $grade<br>”;
}
print ‘<p>’;
//Sort by key, then print again
ksort($grades);
print ‘<p>After sorting the array by key using ksort(), the array
looks like this:</p>’;
foreach($grades as $student => $grade)
{
print “$student: $grade<br>”;
}
print ‘<p>’;
?>
</body>
</html>
Template.html
<html>
<head>
<meta charset= “utf-8”>
<meta http-equiv= “X-UA-Complatble” content = “IE=edge, chrome=1”>
<meta name= “viewport” content= “width=device-width, initial-scale=1.0”>
<meta name= “HandleidFriendly” content= “True”>
<title> Raise High the Roof Beam!</title>
<link rel=“stylesheet” type=“text/css” media= “screen” href= “css/concise.min.css”/>
<link rel= “stylesheet” type= “text/css” media= “screen” href= “css/masthead.css”/>
</head>
<body>
<header container class= “siteHeader”>
<div row>
<h1 column=4 class= “logo”><a href= “index.php”>Raise High the
Roof Beam!</a></h1>
<nav column= “8” class= “nav”>
<ul>
<li><a href= “books.php”>Books</a></li>
<li><a href= “#”>Stories</a></li>
<li><a href= “#”>Quotes</a></li>
<li><a href= “login.php”>Login</a></li>
<li><a href= “register.php”>Register</a></li>
</ul>
</nav>
</div>
</header>
<main container class= “siteContent”>
<!—BEGIN CHANGEABLE CONTENT. -->
</ul>
</nav>
</div>
</header>
<main container class= “siteContent”>
<!—BEGIN CHANGEABLE CONTENT. -->
<!-- Script:header.html -->
<!-- Script : footer.html -->
<!—END CHANGEABLE CONTENT -->
</main>
<footer container class= “siteFooter”>
<p>Design uses <a href= “http://concisecss.com/”>Concise CSS Framework</a></p>
</footer>
</body>
</html>
To create the footer file
1. Open template.html in your text editor or IDE, if it isn’t already open.
2. Select everything from the <!—END CHANGEABLE CONTENT -->HTML comment to the
end of script.
3. Copy this code.
4. Create a new, blank document in your text editor, to be named footer.html.
5. Paste the coped text into the document.
6. Save the file as footer.html.
Using External Files
As the preceding section stated, you can save development time by creating separate pages for
particular elements and then incorporating them into the main PHP pages using specific functions.
Two of these functions are include() and require():
include(‘file.php’);
require(‘file.html’);
Both functions work the same way, with one relatively key differences: if an include() function fails,
the PHP script generates a warning but continues to run. Conversely, if require() fails, it terminates
the execution of the script.
Both include() and require() incorporate the referenced file into the main file. The result is the same
as if the included code were part of the parent file in the first place.
Understanding this basic idea is key to making the most of external files: including a file makes it as
if that file’s contents were in the parent script to begin with. This means that any code within the
included file not within PHP tags is treated as HTML. And this is true regardless of what extension
the included file has, because it’s the extension of the including file that counts.
There are many reasons to use included files. You could put your own defined functions into a
common file. You might also want to place your database access information into a configuration
file. First, however, let’s include the template files created in the preceding section of the chapter in
order to make pages abide by a consistent design.
To use external files
1. Create a new document in your text editor or IDE, to be named index.php.
2. Start with the initial PHP tags, and add any comments.
3. Address error management, if necessary.
4. Include the header file.
5. Close the PHP section, and create the page specific content.
6. Create another PHP section, and include the footer file.
7. Save the file as index.php.
8. Create a folder named templates within the main web document directory on your PHP-
enabled computer or server.
9. Place header.html and footer.html in the templates directory you just created.
10. Place index.php in the same directory as the templates folder.
11. Create a folder named css within the main web document directory on your PHP-enabled
computer or server.
12. Place the concise.min.css and masthead.css scripts, available as part of the book’s
downloadable code, in the css directory.
13. Run index.php in your browser.
14. View the page’s source code in your browser.
Index.php
<?php
//This is the home page for this site. It uses templates to create the layout.
//Include the header:
include(‘templates/header.html’);
//Leave the PHP section to display lot of HTML
?>
<h2>Welcom to a J.D. Salinger Fan Club!</h2>
<p>Lorem ipsum dolar sit amet, consectetur adipisicing elit, sed to eiusmod tempor incididunt ut
labore et dolore magna aligqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non provident, sunt in culpa qui official deserunt mollit anim id est
laborum.
</p>
<?php
include(‘templates/footer.html’);
//include the footer
?>
Using Constants
Many of PHP’s data types have already been discussed, primarily: numbers, strings, and arrays.
Constants are another data type, but unlike variables, their values cannot change.
Whereas variables are assigned values via the assignment operator(=), constants are assigned values
using the define() function:
define(‘CONSTANT_NAME’, value);
Notice that as a rule of thumb constants are named using all capital letters, although doing so isn’t
required. Most important, constants don’t use the initial dollar sign as variables do, because constants
are not variables. Here are two constants:
define(‘PI’, 3.14);
define(‘CURRENCY’, ‘euros’);
As with any value, quotes those that are strings, not those that are numbers. Referring to constants is
generally straightforward:
print CURRENCY;
number_format(PI,1);
But using constants within quotation marks is more complicated. You can’t print constants within
single or double quotation marks, like this:
print “The cost is 468 CURRENCY”;
print ‘The cost is 468 CURRENCY’;
Instead, concatenation or multiple print statements are required:
print ‘The cost is 468’, CURRENCY;
or
print ‘The cost is 468’;
print CURRENCY;
To use constants
1. Create a new PHP document in your text editor or IDE, to be named books.php.
2. Define the page title as a constant.
3. Include the header file.
include(‘templates/footer.html’);
?>
Header.html
<html>
<head>
<meta charset= “utf-8”>
<meta http-equiv= “X-UA-Complatble” content = “IE=edge, chrome=1”>
<meta name= “viewport” content= “width=device-width, initial-scale=1.0”>
<meta name= “HandleidFriendly” content= “True”>
<title>
<?php //print the page title.
if (defined(‘TITLE’)) //Is the title defined?
{
print TITLE;
}
else //The title is not defined
{
print ‘Raise High the Roof Beam! A. J.D. Salinger Fan Club’;
}
?>
</title>
<link rel=“stylesheet” type=“text/css” media= “screen” href= “css/concise.min.css”/>
<link rel= “stylesheet” type= “text/css” media= “screen” href= “css/masthead.cs”/>
</head>
<body>
<header container class= “siteHeader”>
<div row>
<h1 column=4 class= “logo”><a href= “index.php”>Raise High the
Roof Beam!</a></h1>
<nav column= “8” class= “nav”>
<ul>
<li><a href= “books.php”>Books</a></li>
<li><a href= “#”>Stories</a></li>
<li><a href= “#”>Quotes</a></li>
<li><a href= “login.php”>Login</a></li>
<li><a href= “register.php”>Register</a></li>
</ul>
</nav>
</div>
</header>
<main container class= “siteContent”>
<!—BEGIN CHANGEABLE CONTENT. -->
<!-- Script:header.html -->
However, if the user submitted the form without completing it, that variable may not be set. A more
reliable solution is to add a hidden input to a form so that it can be checked:
<input type= “hidden” name= “submitted” value= “true”>
Again, the only purpose of this hidden input is to reliably indicate that the form has been submitted,
even if the user did nothing to complete the form.
To use one page to display and handle a form
1. Begin a new PHP document in your text editor or IDE, to be named login.php.
2. Define the page title as a constant and include the header file.
3. Add some introductory text.
4. Begin the conditional to check whether the form has been submitted.
5. Create a nested pair of conditional to process the form data.
6. Complete the main conditional.
7. Require the footer file, and complete the PHP page.
8. Save the file as login.php, place it in the same directory as index.php and test it in you
browser.
Login.php
<?php
//This page lets people log into the site
//Set the page title and include the header file.
define(‘TITLE’, ‘Login’);
include(‘templates/header.html’);
//print some introductory text
print ‘<h2>Login Form</h2>
<p>Users who are logged in can take advantage of certain features like this, that, and
the other thing.</p>’;
//Check if the form has been submitted :
if($_SERVER[‘REQUEST_METHOD’] == ‘POST’)
{
//Handle the form
if((!empty($_POST[‘email’])) && (!empty($_POST[‘password’])))
{
if((strlower($_POST[‘email’]) == ‘me@example.com’) && ($_POST[‘password’]==‘testpass’))
{ //correct
print ‘<p class= “text – success”>You are logged in!<br> Now you can
blah, blah, blah … </p>’;
}
else
{ //Incorrect
print ‘<p class= “text – error”> The submitted email address and
password do not match those on file!<br> Go back and try again.</p>’;
}
}
else
{ //Forgot a field
print ‘<p class= “text – error”>Please make sure you enter both an email
address and a password!<br>Go back and try again.</p>’;
}
}
else
{ //Display the form
print ‘<form action= “login.php” method= “post” class= “form – inline”>
<p><label for= “email”>Email Address:</label><input type= “email” name=
“email” size= “20”></p>
<p><label for= “password”>Password : </label><input type= “password”
name= “password” size= “20”></p>
<p><input type= “submit” name= “submit” value= “log In!” class= “button— pill”></p>
</form>’;
}
include(‘template/footer.html’); //Need the footer
?>
When you begin working with cookies in PHP, you’ll need to know how to debug your cookies
related scripts when difficulties arise. Three areas might cause you problems:
Sending the cookie with PHP.
Receiving the cookies in your browser.
Accessing a cookie in a PHP script.
Creating Cookies
An important thing to understand about cookies is that they must be sent from the server to the client
prior to any other information. This means a script should send cookies before any print statement,
before including an external file that contains HTML, and so forth.
Should the server attempt to send a cookie after the web browser has already received HTML – even
an extraneous white space –an error message will result and the cookies won’t be sent. This is by far
the most common cookie-related error.
Cookies are sent using the setcookie() function:
setcookie(name,value);
setcookie(‘CookieName’, ‘This is the cookie value’);
You can continue to send more cookies to the browser with subsequent uses of the setcookie()
function, although you’re limited by the browser as to how many cookies can be sent from the same
site:
setcookie(‘name2’, ‘some value’);
setcookie(‘name3’, ‘another value’);
There’s no universal, hard limit as to how many cookies a browser will accept from one site, but you
should keep the number to a minimum.
Finally, when creating cookies, you can-as you’ll see in this example – use a variable for the name or
value attribute of your cookies:
setcookies($cookie_name, $cookie_value);
To send cookies:
1. Create a new PHP document in your text editor or IDE, to be named customize.php.
2. Check whether the form has been submitted.
3. Create the cookies:
setcookie(‘font_size’, $_POST[‘font_size’]);
setcookie(‘font_color’, $_POST[‘font_color’]);
These two lines create two separate cookies. One is named font_size and the other
font_color. Their values will be based on the selected values from the HTML form, which
are stored in the $_POST[‘font_size’] and $_POST[‘font_color’] variables.
4. Create a message and complete the conditional and the PHP section:
$msg = ‘<p> Your settings have been entered! Now see them <a href=
“view_settings.php”> in action</a>.</p>’;
When the form has been submitted, the cookies will be sent and the $msg variable will be
assigned a string value. This variable will be used later in the script to print a message.
5. Create the HTML head and opening body tag.
6. Create another PHP section to report on the cookies being sent:
<?php
if(isset($msg))
{
print $msg;
}
?>
7. Being the HTML form.
8. Complete the HTML form.
9. Complete the HTML page.
10. Save the file as customize.php, and place it in the proper directory for your PHP enabled
server.
11. Make sure you’ve set your browser to prompt for each cookie, if possible.
12. Run the script in your browser.
Customize.php
<?php
//Handle the form if it has been submitted
if(isset($_POST[‘font_size’], $_POST[‘font_color’]))
{
//send the cookies
setcookies(‘font_size’, $_POST[‘font_size’]);
setcookies(‘font_color’, $_POST[‘font_color’]);
//Message to be printed later:
$msg = ‘<p> Your settings have been entered! Now see them <a href=
“view_seeting.php”> in action</a>.</p>’;
}
?>
<!doctype html>
<html lang= “en”>
<head>
{
<?php
//check for a font_size value
if(isset($_COOKIE[‘font_size’]))
{
print “\t\tfont_size:”.htmlentities($_COOKIE[‘font_size’]).“;\n”;
}
else
{
print(“\t\tfont_size: medium:”;
}
//check for a font_color value
if(isset($_COOKIE[‘font_color’]))
{
print “\t\tcolor: #”.htmlentities($_COOKIE[‘font_color’]).“;\n”;
}
else
{
print “\t\tcolor: #000;”;
}
?>
}
</style>
</head>
<body>
<p><a href= “customize.php”>Customize Your Settings</a></p>
<p><a href= “reset.php”>Reset Your Settings</a></p>
<p>yadda yadda yadda yadda yadda
yadda yadda yadda yadda yadda
yadda yadda yadda yadda yadda
yadda yadda yadda yadda yadda
yadda yadda yadda yadda yadda
</p>
</body>
</html>
set the expiration time by adding a particular number of minutes or hours to the current time. You
can find the current time in PHP by using the time() function. Therefore, this line of code sets the
expiration time of the cookie to be one hour from the current movement.
setcookie(name, value, time()+36000);
Because theexpiration time will be calculated as the value of time() plus 36000, that argument isn’t
put in quotes.
The path and domain arguments are used to limit a cookie to a specific folder in a website – the path
– or to a specific domain. Using the path option, you could limit a cookie to exist only while a user
is in a specific subfolder of the domain:
setcookie(name, value, time()+3600, ‘/subfolder/’);
Cookies are already specific to a domain, so the domain argument might be used to limit a cookie to
a subdomain, such as forum.example.com:
setcookie(name, value, time()+3600, ‘ ’, ‘forum.example.com’);
The secure value dictates that a cookie should only be sent over a secure HTTPS connection. A
value of 1 indicates that a secure connection must be used, whereas 0 indicates that a secure
connection isn’t necessary. You could ensure a secure cookie transmission for e-commerce sites:
setcookies(‘cart’, ‘82ABC3012’, time()+3600, ‘’, ‘shop.example.com’,1);
To set a cookie’s expiration date
1. Open customize.php in your text editor of IDE.
2. Change the two setcookie() lines to read as follows:
setcookie(‘font_size’,$_POST[‘font_size’], time()+10000000, ‘/’, ‘’, 0);
3. Save the file, place it in the proper directory for your PHP enabled server, and test it again in
your PHP enabled server, and test it again in your browser.
Customize.php
<?php
//Handle the form if it has been submitted
if(isset($_POST[‘font_size’], $_POST[‘font_color’]))
{
//send the cookies
setcookies(‘font_size’, $_POST[‘font_size’], time()+10000000, ‘/’);
setcookies(‘font_color’, $_POST[‘font_color’], time()+10000000, ‘/’);
//Message to be printed later:
$msg = ‘<p> Your settings have been entered! Now see them <a href=
“view_seeting.php”> in action</a>.</p>’;
}
?>
<!doctype html>
<html lang= “en”>
<head>
<meta charset= “utf-8”>
<title>Customize Your Settings </title>
</head>
<body>
<?php
//if the cookies were sent, print a message
if(isset($msg))
{
print $msg;
}
?>
<p>Use this form to set your preferences:</p>
<form action= “customize.php” method= “post”>
<select name= “font_size”>
<option value= “”>Font Size</option>
<option value= “xx-small”>xx-small</option>
<option value= “x-small”>x-small</option>
<option value= “small”>small</option>
<option value= “medium”>medium</option>
<option value= “large”>large</option>
<option value= “x-large”>x-large</option>
<option value= “xx-large”>xx-large</option>
</select>
<select name= “font_color”>
<option value= “”>Font Color</option>
<option value= “999”>Gray</option>
<option value= “oco”>Green</option>
<option value= “oof”>Blue</option>
<option value= “coo”>Red</option>
<option value= “ooo”>Black</option>
</select>
<input type= “submit” name= “submit” value= “Set My Preferences”>
</form>
</body>
</html>
Deleting a Cookies
The final thing to know about cookies is how to delete them. Although a cookie automatically
expires when the user’s browser is closed or when the expiration date/time is met, sometimes you’ll
want to manually delete the cookies as well. For example, websites that have registered users and
login capabilities delete any created cookies when the user logs out.
The setcookies() function can take up to seven arguments, but only one is required the name. If you
send a cookie that consists of a name without a value, it will have the same effect as deleting the
existing cookie of the same name. For example, to create the cookie username, you use this line:
setcookie(‘username’, ‘Larry’);
To delete the username cookie, you code
setcookie(‘username’, ‘’);
or
setcookie(‘username’, FALSE);
As an added precaution, you can also set an expiration date that’s in the past.
setcookie(‘username’, FALSE, time()-6000);
The only caveat when it comes to deleting a cookie is that you must use the same argument values
that were used to set the cookie in the first place, aside from the value and expiration. For example, if
you set a cookie while providing a domain value, you must also provide that value when deleting the
cookie:
setcookie(‘user’, ‘larry’, time()+3600, ‘’, ‘forums.example.com’);
setcookie(‘user’, ‘’, time()-600, ‘’, ‘forums.example.com’);
To demonstrate this feature, let’s add a reset page to the web application. This PHP script will
destroy the sent cookies so that the user’s preferences are forgotten.
1. Begin a new PHP script in your test editor or IDE, to be named reset.php.
2. Delete the existing cookies by sending blank cookies. Then complete the PHP code.
3. Create te HTMLhead.
4. Add the page’s body.
5. Complete the HTML.
6. Save the page as reset.php, place it in the proper directory for you PHP enabled server, and
test it in your browser.
Reset.php
<?php
//Delete the cookies
setcookie(‘font_size’, ‘’, time()-600, ‘/’);
setcookie(‘font_color’, ‘’, time()-600, ‘/’);
?>
<!doctype html>
<html laug= “en”>
<head>
<meta charset= “utf-8”>
<title>Reset Your Settings </title>
</head>
<body>
<p>Your settings have been reset! Feel free to <a href= “view_setting.php”>
customize</a>them again.</p>
</body>
</html>
Creating a Session
Creating, accessing, or deleting a session begins with the session_start() function. This function will
attempt to send a cookie the first time a session is started, so it absolutely must be called prior to any
HTML or white space being sent to the browser. Therefore, on pages that use sessions, you should
call the session_start() function as one of the very first lines in you script:
<?php
session_start();
The first time a session is started, a random session ID is generated and a cookie is sent to the web
browser with a name of PHP SESSID and the value like mo7puk861tm60tbm4b8coh0og2.
Once the session has been started, you can record data to it by assigning values to the $_SESSION
array:
$_SESSION[‘first_name’ ] ‘Krishna’;
$_SESSION[‘age’] = 90;
Unlike with other arrays you might use in PHP, you should always treat this array as an associative
array. In other words, you should explicitly use strings for the keys, such as first_name and age.
Each time a value is assigned to the $_SESSION array, PHP writes that data to a temporary file
stored on the server.
To create a session
1. Open login.php in your text editor or IDE.
2. Before the ob_end_clean() line, add the following:
session_start();
$_SESSION[‘email’] = $_POST[‘email’];
$_SESSION[‘loggedin’] = time();
3. Save the file as login.php, and place it in the appropriate directory on you PHP enabled
computer.
4. Load the form in your browser to ensure that it has no errors.
Login.php
<?php
//This page lets people log into the site
//Set the page title and include the header file.
define(‘TITLE’, ‘Login’);
include(‘templates/header.html’);
//print some introductory text
print ‘<h2>Login Form</h2>
<p>Users who are logged in can take advantage of certain features like this, that, and
the other thing.</p>’;
//Check if the form has been submitted :
if($_SERVER([‘REQUEST_METHOD’] == ‘POST’)
{
//Handle the form
if((!empty($_POST[‘email’])) && (!empty($_POST[‘password’])))
{
if((strlower($_POST[‘email’]) == ‘me@example.com’) &&
($_POST[‘password’] == ‘testpass’))
{
//correct
//Do session stuff;
session_start();
$_SESSION[‘email’] = $_POST[‘email’];
$_SESSION[‘loggedin’] = time();
//Redirect the user to the welcome page
ob_end_clean(); //Destroy the buffer!
header(‘Location: welcome.php’);
exit();
}
else
{ //Incorrect
print ‘<p class= “text – error”> The submitted email address and
password do not match those on file!<br> Go back and try again.</p>’;
}
}
else
{ //Forgot a field
print ‘<p class= “text – error”>Please make sure you enter both an email
address and a password!<br>Go back and try again.</p>’;
}
}
else
{ //Display the form
print ‘<form action= “login.php” method= “post” class= “form – inline”>
<p><label for= “email”>Email Address:</label><input type= “email” name=
“email” size= “20”></p>
<p><label for= “password”>Password : </label><input type= “password”
name= “password” size= “20”></p>
<p><input type= “submit” name= “submit” value= “log In!” class= “button—
pill”></p>
</form>’;
}
include(‘template/footer.html’); //Need the footer
?>
Deleting a Session
It’s important to know how to delete a session, just as It’s important to know how to delete a cookie:
Eventually you’ll want to get rid of the data you’ve stored. Session data exists in two places – in an
array during the execution of the script and in a text file – so you’ll need to delete both. But first you
must begin with the session_start() function, as always:
session_start();
Then, you clear the session variables by resetting the $_SESSION array:
$_SESSION = []; //or = array();
Finally, remove the session data from the server. To do this, use:
session_destroy();
With that in mind, let’s write logout.php, which will delete the session, effectively logging out the
user.
To delete a session
1. Start a new PHP script in your text editor or IDE, to be named logout.php.
2. Begin the session.
3. Reset the session array.
4. Destroy the session data on the server.
5. Include the HTML header, and complete this PHP section.
6. Make the page content.
7. Include the HTML footer.
8. Save the file as logout.php, place it in the proper directory for your PHP enabled server, and
test it in your browser by clicking the link in welcome.php.
Logout.php
<?php //This is the logout page, it destroys the session information //Need the session
session_start();
//Reset the session array
$_SESSION=[];
//Destroy the session data on the server
session_destroy();
//Define a page title and include the header
define(‘TITLE’, ‘Logout’);
include(‘template/header.html’);
?>
<h2>Welcome to the J.D. Salinger Fan Club!</h2>
<p>You are now logged out..</p>
<p>Thank you for using this site, We hope that you liked it.<br>
Blah, blah, blah…. Blah, blah, blah….</p>
<?php include(‘template/footer.html’);
?>
Creating Functions
PHP User Defined Functions. Besides the built-in PHP functions, we can create our
own functions. A function is a block of statements that can be used repeatedly in a program.
A function will not execute immediately when a page loads. A function will be executed by a call to
the function.
PHP functions are similar to other programming languages. A function is a piece of code which
takes one more input in the form of parameter and does some processing and returns a value.
You already have seen many functions like fopen() and fread() etc. They are built-in functions but
PHP gives you option to create your own functions as well.
There are two parts which should be clear to you −
Creating a PHP Function
Calling a PHP Function
In fact you hardly need to create your own PHP function because there are already more than 1000
of built-in library functions created for different area and you just need to call them according to
your requirement.
The exact formatting of a function isn’t important as long as the requisite elements are there. These
elements include the word function, the function’s name, the opening and closing parentheses, the
opening and closing braces, and the statement(s). It’s conventional to indent a function’s statement(s)
from the function keyword line, for clarity’s sake, as you would with a loop or conditional. In any
case, select a format style that you like – which is both syntactically correct and logically sound –
and stick to it.
You call the function by refereing to it just as you do any built-in function. The line of code:
whatever();
will cause the statement part of the previously defined function – the print command to be executed.
To create and call a basic function
1. Start a new PHP document in your text editor or IDE, to be named menus.php.
2. Begin the PHP section.
3. Start defining a function:
function make_date_menus() {
4. Create the month pull down menu:
5. Create the day pull down menu.
6. Create the year pull down menu.
7. Close the function.
8. Make the form tags, and call the function.
9. Complete the PHP and HTML.
10. Save the file as menus.php, place it in the proper directory for your PHP enabled server, and
run it in your browser.
11. If you want, check out the HTML source of the page to see what was dynamically generated.
Menus.php
<!doctype html>
<html>
<head>
<meta charset= “utf-8”>
<title>Date Menus</title>
</head>
<body>
<?php
//This script define and calls a function
//This function makes three pull down menus for the months, days, and years
function make_date_menus()
{
<body>
<?php
//This script define and calls a function that creates a sticky text input.
//This function makes a sticky text input
//This function requires two arguments be passed to it.
function make_text_input($name, $label)
{
//Begin a paragraph and a label
print ‘<p><label>’. $label. ‘: ’;
//Begin the input
print ‘<input type= “text” name= “ ‘ .$name.’ ” size= “20” ’;
//Add the value
if(isset($_POST[$NAME]))
{
print ‘Value = “ ‘. htmlspecialchars($_POST[$name]). ’ ” ’;
}
//Complete the input, the label and the paragraph
print ‘<p></label></p>’;
}
//Make the form
print ‘<form action= “ ” method= “post”>’;
//Create some text inputs
make_text_input(‘first name’, ‘First Name’);
make_text_input(‘last name’, ‘Last Name’);
make_text_input(‘email’, ‘Email Address’);
print ‘<input type= “submit” name= “submit” value= “Register!”></form>’;
?>
</body>
</html>
greeting();
greeting(‘Zoe’);
The parameters with default values must always be written after the other parameters. This is
because PHP directly assigns values to parameters in the order they’re received from the call line.
Thus, it isn’t possible to omit a value for the first argument but include one for the second. For
example, suppose you have
function calculate_total($qty, $price=20.00, $tax=0.06) {…
if you call the function with the line
calculate_total(3,0.07);
with the intention of setting $qty to 3, leaving $price is set to 0.07, and $tax remain at 0.06, which
isn’t the desired outcome. The proper way to achieve that effect would be to code.
calculate_total(3,20.00,0.07);
To write a function that uses default values
1. Open sticky1.php in you text editor or IDE, if it isn’t open already.
2. Add a third argument with a default value to the make_text_input() function.
3. Change the creation of the input so that it uses the $size variable.
4. Change the function calls to vary the sizes.
5. Save the script as sticky2.php, place it in the proper directory of you PHP enabled server,
and test it in your browser.
Sticky2.php
<!doctype html>
<html>
<head>
<meta charset= “utf-8”>
<title>Sticky Text Inputs</title>
</head>
<body>
<?php
//This script define and calls a function that creates a sticky text input.
//This function makes a sticky text input
//This function requires two arguments be passed to it.
//A third argument is optional (it has a default value).
function make_text_input($name, $label, $size=20)
{
//Begin a paragraph and a label
print ‘<p><label>’. $label. ‘: ’;
//Begin the input
?>
<form action= “” method= “post”>
<p>Quantity: <input type= “text” name= “quantity” size= “3”></p>
<p>Price: <input type= “text” name= “price” size= “5”</p>
<input type= “submit” name= “submit” value= “Calculate!”>
</form>
</body>
</html>
foo($var);
When the function is called, the value of $var will be assigned $param, so their values are the same
but their names are different and they are different variables. Now if the name of the parameter in the
function is also $var
function bar($var) {
//Do whatever.
}
$var=1;
bar($var);
then the $var variable within the function is assigned the same value as the original $var outside of
the function – but they’re still two separate variables. The one has a scope within the function, and
the other has a scope outside of it. This means that you can use the same name for variables in the
function as exist outside of the function without conflict.
To use the global statement
1. Open calculator1.php in your text editor or IDE, if it is not already open.
2. Before the function definition, add the following:
$tax = 8.75;
3. Within the function definition, add a global statement:
global $tax;
4. Before the $total in the function is formatted, recalculate the value using the tax rate.
5. After the main print line so that it prints the tax rate as well.
6. Save the script, place it in the proper directory for your PHP enabled server, and test it in
your browser.
Calculator1.php
<!doctype html>
<html>
<head>
<meta charset= “utf-8”>
<title>Cost Calculator</title>
</head>
<body>
<?php
//This script displays and handles an HTML form.
//It uses a function to calculate a total from a quantity and price.
//Define a tax rate
$tax = 8.75
//This function performs the calculations.
function calculate_total($quantity,$price)
{
$global $tax;
$total = $quantity * $price; //Calculation
$taxrate = ($tax/100)+1;
$total = $total * $taxrate; //Add the tax
$total = number_format($total,2); //Formating
return $total;
}
//Check for a form submission.
if(isset[$_POST[‘submitted’]))
{
//check for values
if(is_numeric($_POST[‘quantity’] AND is_numeric($_POST[‘price’]))
{
//Call the function and print the results
$total = calculate_total($_POST[‘quantity’], $_POST[‘price’]);
print “<p>Your total comes to $<span style=\” font-weight:
bold;\“>$total</span>, including the $tax percent tax rate.</p>”;
}
else
{
//Inappropriate value entered
print ‘<p style= “color: red;”>Please enter a valid quantity and
price!</p>’;
}
}
?>
<form action= “” method= “post”>
<p>Quantity: <input type= “text” name= “quantity” size= “3”></p>
<p>Price: <input type= “text” name= “price” size= “5”</p>
<input type= “submit” name= “submit” value= “Calculate!”>
<input type= “hidden” name= “submitted” value= “true”>
</form>
</body>
</html>
Introduction to Databases
The internet wouldn’t be what it is today if not for the existence of databases. In fact, PHP probably
wouldn’t be as popular or as useful if not for its built-in support for numerous types of databases. In
this section use MySQL as the example of database management system(DBMS). Although MySQL
which is available for most platforms – may not be as powerful as the highest-end commercial
database servers, it has enough speed and functionality for most purposes. And its price-free for most
uses-makes it the common choice for web development.
Introduction to SQL
A database is a collection of tables (made up of columns and rows) that stores information. Most
databases are created, updated, and read using SQL (Structured Query Language). SQL has
surprisingly few command (like ALTER, CREATE, DELETE, DROP, INSERT, SELECT, and
UPDATE), which is both a blessing and a curse.
SQL was designed to be written a lot like the English language, which makes it very user friendly.
But SQL is still extremely capable, even if it takes some thought to create more elaborate SQL
statements with only the handful of available terms.
For people new to PHP, confusion can stem from PHP’s relationship to HTML. When you
incorporate a database, the relationships can become even fuzzier. The process is quite simple: PHP
is used to send SQL statement to the database application, where they are executed. The result of the
execution – the creation of a table, the insertion of a record, the retrieval of some records, or even an
error – is then returned by a database to the PHP script.
With that in mind, PHP’s mysqli_query() function will be the most used tool. It sends an SQL
command to MySQL:
$result = mysqli_query(database connection, SQL command);
When a PHP script that interacts with a MySQL database does not perform as expected, the first step
is to determine if the problem is in the query itself. To take this step, you can start by printing out the
query being executed, using code such as the following:
print $query;
Assuming that $query represents the complete SQL command, often containing the values of PHP
variables, this one simple line will reveal to you the actual SQL statement being run.
Next, you would take the printed query and exeute it using another application. The two most
common options are:
The MySQL client, a command-line tool for interacting with MySQL.
Connecting to MySQL
When you worked with text files, “Files and Directories”, you saw some functions, such as fwrite()
and fgets(), require that you first create a file pointer using fopen(). This pointer you use a similar
process when working with databases. First, you have to establish a connection to the database server
– in this case, MySQL. This connection is then used as the access point for any future commands.
The syntax for connecting to a database is:
$dbc = mysqli_connect(hostname, username, password, database_name);
The database connection-assigned to $dbc in this example-is normally established using at least four
arguments: the host, which is almost always localhost, the username; the password for that username
and the database name.
If you’re using a database through a hosting company, the company will most likely provide you
with all of these values.
One you’re finished working with a database, you can close the connection, just as you’d close on
open file:
mysqli_close($dbc);
The PHP script will automatically close the database connection when the script terminates, but it’s
considered good form to formally close the connection once it’s no longer needed.
To connect to a MySQL database
1. Begin a new PHP document in your text editor or IDE, to be named mysqli_connect.php.
2. Start the section of PHP code.
3. Connect to MySQL, and report on the results.
4. Complete the PHP code and the HTML page.
5. Save the file as mysqli_connect.php, place it in the proper directory of your PHP-enabled
computer, and test it in your browser.
Mysqli_connect.php
<!doctype html>
<html lang= “en”>
<head>
<title>Connect to MySQL</title>
</head>
<body>
<?php
/*This script connect to the MySQL database*/
//Attempt to connect to MySQL and print out messages
if($abc = mysqli_connect(‘localhost’, ‘username’, ‘password’, ‘myblog’))
{
print ‘<p>Successfully connected to the database!</p>’;
mysqli_close($abc); //close the connection
}
else
{
print ‘<p style= “color: red;”>Could not connect to the
database.</p>’;
}
?>
</body>
</html>
Connection errors are slightly different, however. To report upon those, invoke
mysqli_connect_error(). This function does not take any arguments:
print mysql_connect_error();
Along with these functions, you may want to use some PHP tools for handling errors. For beginners,
you can start with the error suppression operator. When use preceding a function name, it suppresses
any error messages or warnings the function might invoke:
@function_name();
To use error handling
1. Open mysqli_connect.php in your text editor or IDE.
2. Suppress any PHP error created by the mysqli_connect() function by changing the if
conditional.
3. Add the mysqli_error() function to print statement in the else section.
4. Save the file, and test it again in your browser.
Mysqli_connect2.php
<html lang= “en”>
<head><title>Connect to MySQL</title></head>
<body>
<?php
/*This script connect to the MySQL database*/
//Attempt to connect to MySQL and print out messages
if($abc = mysqli_connect(‘localhost’, ‘username’, ‘password’, ‘myblog’))
{
print ‘<p>Successfully connected to the database!</p>’;
mysqli_close($abc); //close the connection
}
else {
print ‘<p style= “color: red;”>Could not connect to the
database.<br>’.mysqli_connect_error(). ‘.</p>’;
}
?>
</body>
</html>
Creating a Table
Once you’ve created and selected initial database, you can begin creating individual tables in it. A
database can consist of multiple tables, but in the simple example you’ll create one table in which all
the data will be stored.
To create a table in the database, you’ll use SQL-the language that databases understand. Because
SQL is a lot like spoken English, the proper query to create a new table records like this:
CREATE TABLE tablename(column1 definition, column2 definition, etc.);
For each column, separated by commas, you first indicate the column name and then the column
types are TEXT, VARCHAR(a variable number of characters), DATETIME, and INT(integer).
Because it’s highly recommended that you create a column that acts as the primary key(a column
used to refer to each row), a simple CREATE statement could be:
CREATE TABLE my_table(id INT PRIMARY KEY, information TEXT);
A table’s primary key is a special column of unique values that is used to refer to the table’s row.
The database makes an index of this column in order to more quickly navigate through the table. A
table can have only one primary key, which you normally set up as an automatically increamented
column of integers. The first two has a key of 1, the second has a key of 2, and so forth. Referring
back to the key always retrieves the values for that row.
Finally, it’s a good idea to establish the default character set when creating a table(or a database).
This is accomplished by adding CHARACTER SET name at the end of the table creation statement:
CREATE TABLE my_table(id INT PRIMARY KEY, information TEXT) CHARACTER SET
utf8;
To Create a New Table
1. Begin a new PHP document in your text editor or IDE, to be named create_table.php.
2. Begin a secion of PHP code.
3. Connect to the MySQL database.
4. Define the query for creating the table.
5. Execute the query.
6. Close the database connection, and complete the $dbc conditional.
7. Complete the PHP code and the HTML page.
8. Save the script as create_table.php, place it in the proper directory for your PHP-enabled
server, and test it in your browser.
Create_table.php
<html lang= “en”>
<head>
<title>Create a Table</title>
</head>
<body>
<?php
/*This script connect to the MySQL server, selects the database, and creates a
table*/
//Connect and select
if($dbc = @mysqli_connect(‘localhost’, ‘username’, ‘password’, ‘myblog’))
{
//Define the query
$query = ‘CREATE TABLE entries(id INT UNSIGNED NOT NULL
AUTO_INCREMENT PRIMARY KEY, title VARCHAR(100) NOT
NULL, entry TEXT NOT NULL, date_entered DATETIME NOT
NULL) CHARACTER SET utf8’;
//Execute the query
if(@mysqli_query($dbc, $query))
{
print ‘<p>The table has been created!</p>’;
}
else
{
print ‘<p style= “color: red;”>Could not create the table
because :<br>’.mysqli_error($dbc). ‘.</p><p>The query being
run was: ‘.$query. ‘</p>’;
}
mysqli_close($dbc);//close the connection
}
else
{ //connection failure.
print ‘<p style= “color: red;”>Could not connect to the
database:<br>’.mysqli_connect_error(). ‘.</p>’;
}
?>
</body>
</html>
Inserting Data into a Database
As mentioned, this database will be used as a simple blog, an online journal. Blog entries –
consisting of a title and text – will be added to the database using one page.
The last script created the table, which consists of four columns: id, title, entry, and date_entered.
The process of adding information to a table is similar to creating the table itself in terms of which
PHP functions you use, but the SQL query is different. to insert records, use the INSERT SQL
command with either of the following syntaxes:
{
$title = trim(strip_tags($_POST[‘title’]));
$entry = trim(strip_tags($_POST[‘entry]));
}
else
{
print ‘<p style= “color: red;”>Please submit both a title and an
entry.</p>’;
$problem = TRUE;
}
if($problem)
{
//Connect and select
$abc = mysqli_connect(‘localhost’, ‘username’, ‘password’,
‘myblog’);
//Define the query
$query = “INSERT INTO entries(id, title, entry, date_entered)
VALUES(0, ‘$title’, ‘$entry’, NOW())”;
//Execute the query
if(@mysqli_query($dbc, $query))
{
print ‘<p>The blog entry has been added!</p>’;
}
else
{
print ‘<p style= “color: red;”>Could not add the entry
because:<br>’ .mysqli_error($dbc). ‘.</p><p>The
query being run was: ‘.$query. ‘</p>’;
}
$mysqli_close($dbc);//close the connection
}
}
?>
<form action= “add_entry.php” method= “post”>
<p>Entry Title :<input type= “text” name= “title” size= “40” maxsize=
“100”></p>
</form>
</body>
</html>
}
}
$mysqli_close($dbc);//close the connection
}
?>
<form action= “add_entry1.php” method= “post”>
<p>Entry Title :<input type= “text” name= “title” size= “40” maxsize=
“100”></p>
<p>Entry Text :<textarea name= “entry” cols= “40” rows=
“5”></textarea></p>
<input type= “submit” name= “submit” value= “Post This Entry!”>
</form>
</body>
</html>
Just as $dbc is a reference to an open database connection, $result is a reference to a query result
set. This variable is then provided to the mysqli_fetch_array() function, which retrieves the query
results:
$row = mysqli_fetch_array($result);
The function fetches one row from the result set at a time, creating an array in the process. The array
will use the selected column names as its indexes: $row[‘name’], $row[‘email’], and so on.
To retrieve data from a table
1. Begin a new PHP document in your text editor or IDE, to be named view_entries.php.
2. Begin a PHP section, and connect to the database.
3. Define the SELECT query.
4. Run the query.
5. Print out the returned results.
6. Handle the errors if the query didn’t run.
7. Close the database connection.
8. Complete the PHP section and the HTML page.
9. Save the script as view_entries.php, place it in the proper directory for your PHP-enabled
server, and test it in your browser.
10. If you want, add another record to the blog using the add_entry.php page and run this page
again.
11. Check the source code of the page to see the dynamically generated links.
view_entry.php
<!doctype html>
<html lang= “en”>
<head>
<title>View My Blog</title>
</head>
<body>
<h1>My Blog</h1>
<?php
/*This script retrieves blog entries from the database.*/
//Connect and Select
$dbc = mysqli_connect(‘localhost’, ‘username’, ‘password’, ‘myblog’);
//Define the query
$query = “SELECT * FROM entries ORDER BY date_entered DESC”;
if($r = mysqli_query($dbc, $query))
{ //Run the query
//Retrieve and print the record
while($row = mysqli_fetch_array($r))
{
print “<p><h3>{$row[‘title’]}</h3>
{$row[‘entry’]}<br>
<a href=\“edit_entry.php?id={$row[‘id’]}\”>Edit</a>
<a href=\“delete_entry.php?id={$row[‘id’]}\”>Delete</a>
</p><hr>\n”;
}
}
else
{ //Query didn’t run
print ‘<p style= “color: red;”>Could not retrieve the data
because:<br>’ .mysqli_error($dbc). ‘.</p><p>The query being run
was: ‘.$query. ‘</p>’;
}
mysqli_close($dbc);//close the connection
?>
</body>
</html>
3. If the page received a valid entry ID in the URL, define and execute a SELECT query.
4. Retrieve the record, and display the entry in a form.
5. Report an error if the query failed.
6. Check for the submission of the form.
7. 8Define and execute the query.
8. Check the result of the query.
9. Complete the main conditional.
10. Close the database connection, and complete the page.
11. Save the script as delete_entry.php place it in the proper directory for your PHP-enabled
server, and test it in your browser.
delete_entry.php
<html lang= “en”>
<head>
<title>Delete My Blog</title>
</head>
<body>
<h1>Delete an Entry</h1>
<?php
/*This script deletes a blog entry.*/
//Connect and Select
$dbc = mysqli_connect(‘localhost’, ‘username’, ‘password’, ‘myblog’);
if(isset($_GET[‘id’]) && is_numeric($_GET[‘id’]))
{ //Display the entry in a form
//Define the query
$query = “SELECT * FROM entries ORDER BY date_entered DESC”;
if($r = mysqli_query($dbc, $query))
{ //Run the query
$row = mysqli_fetch_array($r); //Retrieve the information
//Make the form
print ‘<form action= “delete_entry.php” method= “post”>
<p>Are you sure you want to delete this entry?</p>
<p><h3>’. $row[‘title’]. ‘</h3>’.$row[‘entry’].’ <br>
<input type= “hidden” name= “id” value= “’.$GET[‘id’].’”>
<input type= “submit” name= “submit” value= “Delete this
Entry!”></p>
</form>’;
}
else
{
print ‘<p style= “color: red;”>Could not retrieve the blog entry
because:<br>’ .mysqli_error($dbc). ‘.</p><p>The query
being run was: ‘.$query. ‘</p>’;
}
}
elseif(isset($_POST[‘id’]) && is_numeric($_POST[‘id’]))
{ //Hindle the form
//Define the query
$query = “DELETE FROM entries WHERE id = {$_POST[‘id’]}
LIMIT 1”;
$r = mysqli_query($dbc, $query); //Exceute the query
//Report on the result
if(mysqli_affected_rows($dbc)==1)
{
print ‘<p>The blog entry has been deleted.</p>’;
}
else
{
print ‘<p style= “color: red;”>Could not delete the blog entry
because:<br>’ .mysqli_error($dbc). ‘.</p><p>The query
being run was: ‘.$query. ‘</p>’;
}
}
else
{//No id received
print ‘<p style= “color: red;”>This page has been accessed in
error.</p>’;
}
$mysqli_close($dbc);//close the connection
?>
</body>
</html>
As with DELETE query, you should use a WHERE clause to limit the rows that are affected. If you
don’t do this, every record in the database will be updated.
To test that an update worked, you can again use the mysqli_affected_row() function to return the
number of records altered.
To update data in a database
1. Begin a new PHP document in your text editor or IDE, to be named edit_entry.php.
2. Start your PHP code and connect to the database.
3. If the page received a valid entry ID in the URL, define and execute a SELECT query.
4. Retrieve the record, and display the entry in a form.
5. Report an error if the query failed.
6. Check for the submission of the form.
7. Validate and secure the form data.
8. Define and execute the query.
9. Report on the success of the query.
10. Complete the conditionals.
11. Close the database connection, and complete the page.
12. Save the file as edit_entry.php, place it in the proper directory for your PHP-enabled server,
and test it in your browser.
edit_entry.php
<html lang= “en”>
<head><title>Edit a Blog Entry</title></head>
<body>
<h1>Edit an Entry</h1>
<?php
/*This script edits a blog entry using an UPDATE query.*/
//Connect and Select
$dbc = mysqli_connect(‘localhost’, ‘username’, ‘password’, ‘myblog’);
//Set the character set
mysqli_set_charset($dbc, ‘utf8’);
if(isset($_GET[‘id’]) && is_numeric($_GET[‘id’]))
{ //Display the entry in a form
//Define the query
$query = “SELECT title,enty FROM entries WHERE id={$_GET[‘id’]}”;
if($r = mysqli_query($dbc, $query))
{ //Run the query
$row = mysqli_fetch_array($r); //Retrieve the information
//Make the form
Unit – IV
Unit – V