WP HandBook
WP HandBook
Hand Book
Web Programming (3160713)
Year: 2023-2024
Index
1 Introduction to WEB
2.2 Page Layout and linking, User centric design, Sitemap, Planning and 30
publishing website,
3 Basics of HTML 42
4 CSS 84
5 Bootstrap 137
World Wide Web, which is also known as a Web, is a collection of websites or web pages
stored in web servers and connected to local computers through the internet. These
websites contain text pages, digital images, audios, videos, etc. Users can access the content
of these sites from any part of the world over the internet using their devices such as
computers, laptops, cell phones, etc. The WWW, along with the internet, enables the
The building blocks of the Web are web pages which are forma ed in HTML and
connected by links called "hypertext" or hyperlinks and accessed by HTTP. These links are
electronic connections that link related pieces of information so that users can access the
desired information quickly. Hypertext offers the advantage to select a word or phrase
from text and thus to access other pages that provide additional information related to that
word or phrase.
A web page is given an online address called a Uniform Resource Locator (URL). A
particular collection of web pages that belong to a specific URL is called a website, e.g.,
www.facebook.com, www.google.com, etc. So, the World Wide Web is like a huge
electronic book whose pages are stored on multiple servers across the world.
organizations place their WebPages on different servers in different countries so that when
users of a country search their site they could get the information quickly from the nearest
server.
So, the web provides a communication platform for users to retrieve and exchange
information over the internet. Unlike a book, where we move from one page to another in a
sequence, on the World Wide Web we follow a web of hypertext links to visit a web page
and from that web page to move to other web pages. You need a browser, which is
Some people use the terms 'internet' and 'World Wide Web' interchangeably. They think
they are the same thing, but it is not so. The Internet is entirely different from WWW. It is a
worldwide network of devices like computers, laptops, tablets, etc. It enables users to send
emails to other users and chat with them online. For example, when you send an email or
so that people can search and share information. Now, let us understand how it works!
The Web works as per the internet's basic client-server format as shown in the following
image. The servers store and transfer web pages or information to user's computers on the
network when requested by the users. A web server is a software program which serves the
web pages requested by web users using a browser. The computer of a user who requests
documents from a server is known as a client. Browser, which is installed on the user'
website occupies a space in a server and remains stored in it. The server hosts the website
whenever a user requests its WebPages, and the website owner has to pay the hosting price
The moment you open the browser and type a URL in the address bar or search something
on Google, the WWW starts working. There are three main technologies involved in
transferring information (web pages) from servers to clients (computers of users). These
Web Browser:
A web browser, which is commonly known as a browser, is a program that displays text,
data, pictures, videos, animation, and more. It provides a software interface that allows you
to click hyperlink resources on the World Wide Web. When you double click the Browser
icon installed on your computer to launch it, you get connected to the World Wide Web
and can search Google or type a URL into the address bar.
In the beginning, browsers were used only for browsing due to their limited potential.
Today, they are more advanced; along with browsing you can use them for e-mailing,
transferring multimedia files, using social media sites, and participating in online
discussion groups and more. Some of the commonly used browsers include Google
WWW stands for World Wide Web. A technical definition of the World Wide Web is : all
the resources and users on the Internet that are using the Hypertext Transfer Protocol
(HTTP).
A broader definition comes from the organization that Web inventor Tim Berners-Lee
helped found, the World Wide Web Consortium (W3C).The World Wide Web is the
In simple terms, The World Wide Web is a way of exchanging information between
computers on the Internet, tying them together into a vast collection of interactive
multimedia resources.
The Internet and Web are not the same thing: Web uses the internet to pass over the
information.
Evolution
World Wide Web came into existence as a proposal by him, to allow researchers to work
together effectively and efficiently at CERN. Eventually it became the World Wide Web.
Web 1.0
It is the “readable” phrase of the World Wide Web with flat data. In Web 1.0, there is only
limited interaction between sites and web users. Web 1.0 is simply an information portal
where users passively receive information without being given the opportunity to post
Web 2.0
It is the “writable” phrase of the World Wide Web with interactive data. Unlike Web 1.0,
Web 2.0 facilitates interaction between web users and sites, so it allows users to interact
more freely with each other. Web 2.0 encourages participation, collaboration, and
and so on.
Web 3.0
It is the “executable” phrase of Word Wide Web with dynamic applications, interactive
services, and “machine-to-machine” interaction. Web 3.0 is a semantic web which refers to
the future. In Web 3.0, computers can interpret information like humans and intelligently
WWW Architecture
WWW architecture is divided into several layers as shown in the following diagram:
Uniform Resource Identifier (URI) is used to uniquely identify resources on the web and
UNICODE makes it possible to build web pages that can be read and wri en in human
languages.
Syntax
XML (Extensible Markup Language) helps to define common syntax in semantic web.
Data Interchange
representation of data for the web. RDF represents data about resources in graph form.
Taxonomies
ontological constructs.
Ontologies
Ontology is about the exact description of things and their relationship. Web Ontology
Language (OWL) offers more constructs over RDFS. It comes in following three versions:
Rules
RIF and SWRL offer rules beyond the constructs that are available from RDFs and OWL.
Simple Protocol and RDF Query Language (SPARQL) is SQL like language used for
All semantic and rules that are executed at layers below Proof and their result will be used
to prove deductions.
Cryptography
Cryptography means such as digital signature for verification of the origin of sources is
used.
On the top of layer User interface and Applications layer is built for user interaction.
WWW Operation
WWW works on a client- server approach. Following steps explains how the web works:
1. User enters the URL (say, h p://www.tutorialspoint.com) of the web page in the
2. Then the browser requests the Domain Name Server for the IP address
corresponding to www.tutorialspoint.com.
3. After receiving the IP address, the browser sends the request for the web page to the
web server using HTTP protocol which specifies the way the browser and web
server communicates.
4. Then the web server receives a request using HTTP protocol and checks its search
for the requested web page. If found it returns it back to the web browser and closes
5. Now the web browser receives the web page, It interprets it and displays the
HTTP (Hypertext Transfer Protocol) is a set of rules that runs on top of the TCP/IP suite of
protocols and defines how files are to be transferred between clients and servers on the
World Wide Web. HyperText Transfer Protocol (HTTP) is an application layer protocol
which enables WWW to work smoothly and effectively. It is based on a client-server model.
The client is a web browser which communicates with the web server which hosts the
website. This protocol defines how messages are forma ed and transmi ed and what
actions the Web Server and browser should take in response to different commands. When
you enter a URL in the browser, an HTTP command is sent to the Web server, and it
When we open a website using a browser, a connection to the web server is opened, and
the browser communicates with the server through HTTP and sends a request. HTTP is
request and sends a response, and then the connection is closed. Thus, the browser
documents.
protocol, which means requests are initiated by the recipient, usually the Web
browser.
for instance text, layout description, images, videos, scripts, and more.
Structure
•<start line>
•<Header field>
• <blank Line>
• <Message Body>
Structure
A) Start Line
1) Request Method
2) Request URI
3) HTTP Version
1) Request Method:
❏ HEAD Same as GET, but transfers the status line and header section only.
❏ PUT Replaces all current representations of the target resource with the uploaded
content.
❏ TRACE when request is made using a trace method the server echoes back the
received request so that a client can see what intermediate servers are adding or
changing in the request.
2) Request URI
• The uniform resource identifier (URI) is a string to identify the names or resources on the
internet.
• The first version of HTTP was HTTP/0.9 but the official version of HTTP was
HTTP/1.1HTTP
• <status line>
• <header field>
• <blank line>
• <message body>
❏ HTTP Version
❏ Reason phrase
Status Code:
1xx: Informational - It means the request has been received and the process is continuing.
2xx: Success - It means the action was successfully received, understood, and accepted.
3xx: Redirection- It means further action must be taken in order to complete the request.
4xx: Client Error-It means the request contains incorrect syntax or cannot be fulfilled.
5xx: Server Error -It means the server failed to fulfill an apparently valid request.
Message Description
100 Continue Only a part of the request has been received by the server, but
as long as it has not been rejected, the client should continue
with the request.
202 Accepted The request is accepted for processing, but the processing is
not complete.
300 Multiple A link list. The user can select a link and go to that location.
Choices Maximum five addresses .
400 Bad Request The server did not understand the request.
404 Not Found The server can not find the requested page.
500 Internal The request was not completed. The server met an
Server Error unexpected condition.
505 HTTP The server does not support the "h p protocol" version.
Version Not
Supported
• HTTP is connectionless: The HTTP client, i.e., a browser initiates an HTTP request and
after a request is made, the client disconnects from the server and waits for a response. The
server processes the request and re-establishes the connection with the client to send a
response back.
• HTTP is media independent: It means, any type of data can be sent by HTTP.
• HTTP is stateless: that means HTTP protocol can not remember the previous
information of the user nor it remembers the number of times the user has visited a
particular website.
• It is stateless protocol and therefore can not remember the previous communication.
//Response
HTTP/1.1 200 OK
Date: Mon, 27 Jul 2009 12:28:53 GMT
Server: Apache/2.2.14 (Win32)
Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT
ETag: "34aa387-d-1568eb00"
Vary: Authorization,Accept
Accept-Ranges: bytes
Content-Length: 88
Content-Type: text/html
Connection: Closed
<html>
<body>
<h1>Hello, World!</h1>
</body>
</html>
Ex-2 HTTP request & response using Head Method to fetch hello.htm page
//Request
HEAD /hello.htm HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.google.com
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
//Response
HTTP/1.1 200 OK
Date: Mon, 27 Jul 2009 12:28:53 GMT
//Response
HTTP/1.1 200 OK
Date: Mon, 27 Jul 2009 12:28:53 GMT
Server: Apache/2.2.14 (Win32)
Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT
ETag: "34aa387-d-1568eb00"
Vary: Authorization,Accept
Accept-Ranges: bytes
Content-Length: 88
Content-Type: text/html
Connection: Closed
<html>
<body>
<h1>Request Processed Successfully</h1>
</body>
</html>
a web page is a document available on the world wide web. Web Pages are stored on a
A web page can contain huge information including text, graphics, audio, video and
Collection of linked web pages on a web server is known as a website. A unique Uniform
Static web pages are also known as flat or stationary web pages. They are loaded on the
client’s browser as exactly they are stored on the web server. Such web pages contain only
static information. Users can only read the information but can’t do any modification or
Static web pages are created using only HTML. Static web pages are only used when the
Dynamic web page shows different information at different points of time. It is possible to
change a portion of a web page without loading the entire web page. It has been made
It is created by using server-side scripting. There are server-side scripting parameters that
determine how to assemble a new web page which also include se ing up of more
client-side processing.
It is processed using client side scripting such as JavaScript. And then passed in to
Scripting Languages
Scripting languages are like programming languages that allow us to write programs in
the form of script. These scripts are interpreted not compiled and executed line by line.
Client-side Scripting
Client-side scripting refers to the programs that are executed on client-side. Client-side
scripts contain the instruction for the browser to be executed in response to certain user’s
action.
Client-side scripting programs can be embedded into HTML files or also can be kept as
separate files.
Server-side scripting acts as an interface for the client and also limits the user's access to
the resources on the web server. It can also collect the user’s characteristics in order to
customize response.
● Web pages are wri en using different HTML tags and viewed in the browser
window.
● The different browsers and their versions greatly affect the way a page is rendered,
as different browsers sometimes interpret the same HTML tag in a different way.
● The support for different tags also varies across the different browsers and their
versions.
● Same browser may work slightly differently on different operating systems and
hardware platforms.
systems.
Users have different connection speed, i.e. bandwidth, to access the Web sites.
Connection speed plays an important role in designing web pages, if user has low
bandwidth connection and a web page contains too many images, it takes more time to
download.
Generally, users have no patience to wait for longer than 10-15 seconds and move to
When a user gives the URL of the web page for the first time, the HTML file together with
Display Resolution
do not have any control on display resolution of the monitors on which the user
● If the page is displayed on a monitor with a higher resolution, the page is displayed
on the left-hand side and some part on the right-hand side remains blank. We can
● (Not For Exam) Ideally we should use some frameworks for designing like
● Bootstrap/Material design.
Look and feel of the website decides the overall appearance of the website.
● Web typography
● Graphics
● Visual structure
● Navigation etc…
links.
Page layout defines the visual structure of the page and divides the page area into different
Page layout allows the designer to distribute the contents on a page such that visitors can
Locating Information
A Web Page is viewed on a computer screen and the screen can be divided into five major
areas such as center, top, right, bo om and left in this particular order.
The first major area of importance in terms of users viewing pa ern is the center, then top,
It is very difficult for any Web designer to predict the exact behavior of the Web site users.
However, the idea of general behavior of the common user helps in making design of the
Users either scan the information on the web page to find the section of their interest or
Sitemap
Many times Web sites are too complex as there are a large number of sections and each
It becomes difficult for visitors to quickly move from one part to another.
Once the user selects a particular section and pages in that section, the user gets confused
• This is a simplest form of site map represents all links as basic HTML text with varying
• They are used to provide more obvious clue for the depth and
● Navigation links are either text based, i.e. a word or a phrase is used as a link, or
graphical, i.e. a
● It should be consistent.
● Provide a search link, if necessary, usually on top of the page. Use common links
● Horizontal navigation bar can be provided on each page to directly jump to any
section
Navigation System
A complex web site often includes several types of navigation systems. To design a
successful site, it is essential to understand the types of systems and how they work
together to provide flexibility and context.
From the main page to the destination pages that house the actual content, the main
options on each page are taken directly from the hierarchy
Local navigation systems help users to explore what is nearby. It is also known as
sub-navigation or page navigation. We can view it as ‘an extension’ of the global
navigation.
There are 3 common ways to arrange the global and the local navigation — inverted-L,
horizontal and embedded vertical.
a) Inverted-L:
Local navigation is presented as a vertical link list and is placed below the global
navigation, aligned along the left, forming an inverted-L shape.
Local navigation is placed directly below the horizontal global navigation and is
presented as a row, providing more options.
c) Embedded vertical
When the main navigation is presented in a vertical menu, it’s common to see the local
navigation being embedded between the main navigation options.
When the information can’t be fi ed neatly into the structure of global and local
navigation, we can make use of contextual navigation to point users to related pages,
supporting associative learning. On an e-commerce website, this could be “related
products” or “you may also like” links, typically use for cross-selling. Typically an
editor or content specialist will determine appropriate places for these types of links
once the content has been placed into the architectural framework of the web site.
A browser is a software application used to locate, retrieve and display content on the
World Wide Web, including Web pages, images, video and other files. As a client/server
model, the browser is the client run on a computer that contacts the Web server and
requests information. The Web server sends the information back to the Web browser
which displays the results on the computer or other Internet-enabled device that supports a
browser.
1. The User Interface: The user interface is the space where User interacts with the
browser. It includes the address bar, back and next bu ons, home bu on, refresh
and stop, bookmark option, etc. Every other part, except the window where
interface and the rendering engine. According to the inputs from various user
3. The Rendering Engine: The rendering engine, as the name suggests is responsible
for rendering the requested web page on the browser screen. The rendering engine
interprets the HTML, XML documents and images that are forma ed using CSS and
generates the layout that is displayed in the User Interface. However, using plugins
or extensions, it can display other types data also. Different browsers user different
rendering engines:
4. Networking: Component of the browser which retrieves the URLs using the
common internet protocols of HTTP or FTP. The networking component handles all
executes the javascript code embedded in a website. The interpreted results are sent
to the rendering engine for display. If the script is external then first the resource is
fetched from the network. Parser keeps on hold until the script is executed.
6. UI Backend: UI backend is used for drawing basic widgets like combo boxes and
windows. This backend exposes a generic interface that is not platform specific. It
There are different types of N-Tier Architectures, like 3-tier Architecture, 2-Tier
Architecture and 1- Tier Architecture. Generally all projects are broadly divided into two
types of applications 2 tier and 3 tier architecture. Basically high level we can say that 2-tier
architecture is Client server application and 3-tier architecture is Web based application.
Below I am concentrating on the difference between Two-Tier and Three-Tier Architecture,
what all advantages, disadvantages and practical examples.
Two-Tier Architecture:
The two-tier is based on Client Server architecture. The two-tier architecture is like client
server application. The direct communication takes place between client and server. There
is no intermediate between client and server. Because of tight coupling a 2 tiered
application will run faster.
The above figure shows the architecture of two-tier. Here the direct communication
between client and server, there is no intermediate between client and server.
On client application side the code is wri en for saving the data in the SQL server
database. Client sends the request to server and it process the request & send back with
data. The main problem of two tier architecture is the server cannot respond multiple
request same time, as a result it cause a data integrity issue.
Advantages:
1. Easy to maintain and modification is bit easy
2. Communication is faster
Disadvantages:
1. In two tier architecture application performance will be degrade upon increasing the
users.
2. Cost-ineffective
Three-Tier Architecture:
Three-tier architecture typically comprise a presentation tier, a business or data access
tier, and a data tier. Three layers in the three tier architecture are as follows:
1) Client layer
2) Business layer
3) Data layer
It is also called as Presentation layer which contains UI part of our application. This layer
is used for the design purpose where data is presented to the user or input is taken from
the user. For example designing registration form which contains text box, label, bu on
etc.
2) Business layer:
In this layer all business logic wri en like validation of data, calculations, data insertion
etc. This acts as a interface between Client layer and Data Access Layer. This layer is
also called the intermediary layer helps to make communication faster between client
and data layer.
3) Data layer:
In this layer actual database is comes in the picture. Data Access Layer contains
methods to connect with database and to perform insert, update, delete, get data from
database based on our input data.
Disadvantages
1. Increase Complexity/Effort
HTML
Introduction
HTML stands for Hyper Text Markup Language. It is a forma ing language used to define
the appearance and contents of a web page. It allows us to organize text, graphics, audio,
and video on a web page.
Key Points:
HTML Versions
The following table shows the various versions of HTML:
Version Year
XHTML 2000
HTML Tags
Tag is a command that tells the web browser how to display the text, audio, graphics or
video on a web page.
Key Points:
Basic tags
The following table shows the Basic HTML tags that define the basic web page:
Tag Description
<head> </head> Specifies the descriptive information about the web documents.
Tag Description
<b> </b> Specifies the text as bold. Eg. this is bold text
<em> </em> It is a phrase text. It specifies the emphasized text. Eg. Emphasized
text
<i> </i> The content of the italic tag is displayed in italic. Eg. Italic text
<ins> </ins> Specifies the inserted text. Eg. The price of the pen is now 2015.
<del> </del> Specifies the deleted text. Eg. The price of the pen is now 2015.
Table Tags
Following table describe the commonly used table tags:
Tag Description
List tags
Following table describe the commonly used list tags:
Tag Description
HTML Anchor
The HTML anchor tag defines a hyperlink that links one page to another page. It can create
hyperlinks to other web pages as well as files, location, or any URL. The "href" a ribute is
the most important a ribute of the HTML a tag. and which links to the destination page or
URL.href a ribute of HTML anchor tag
If we want to open that link to another page then we can use the target a ribute of <a> tag.
With the help of this link will be open on the next page.
Example:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p>Click on <a href=``https://www.google.com/'' target=``_blank''>
this-link </a> to go on the homepage of Google.</p>
</body>
</html>
Output:
Note:
● The target a ribute can only be used with the href a ribute in the anchor tag.
● If we will not use the target a ribute then the link will open on the same page.
Prepared By: Dr. . Ajay N. Upadhyaya & Prof. Heena Panjwani Page48
Appearance of HTML anchor tag
An unvisited link is displayed underlined and blue.
A visited link displayed underlined and purple.
An active link is underlined and red.
HTML img tag is used to display images on the web page. HTML img tag is an empty tag
that contains a ributes only, closing tags are not used in an HTML image element.
Output:
The src and alt are important a ributes of HTML img tag. All a ributes of HTML image
tag are given below.
1) src
It is a necessary a ribute that describes the source or path of the image. It instructs the
browser where to look for the image on the server.
The location of the image may be on the same directory or another server.
2) alt
3) width
It is an optional a ribute which is used to specify the width to display the image. It is not
recommended now. You should apply CSS in place of width a ribute.
4) height
It h3 the height of the image. The HTML height a ribute also supports iframe, image and
object elements. It is not recommended now. You should apply CSS in place of height
a ribute.
Example:
1. <img src="animal.jpg" height="180" width="300" alt="animal image">
We can use alt a ributes with tags. It will display an alternative text in case the image
cannot be displayed on the browser. Following is the example for alt a ribute:
Prepared By: Dr. . Ajay N. Upadhyaya & Prof. Heena Panjwani Page52
HTML Table
HTML table tag is used to display data in tabular form (row * column). There can be
We can create a table to display data in tabular form, using the <table> element, with the
In Each table, table row is defined by <tr> tag, table header is defined by <th>, and table
HTML tables are used to manage the layout of the page e.g. header section, navigation
bar, body content, footer section etc. But it is recommended to use a div tag over table to
Tag Description
<colgroup> It specifies a group of one or more columns in a table for forma ing.
Let's see the example of the HTML table tag. Its output is shown below.
<table>
<tr><th>First_Name</th><th>Last_Name</th><th>Marks</th></tr>
<tr><td>Sonoo</td><td>Jaiswal</td><td>60</td></tr>
<tr><td>James</td><td>William</td><td>80</td></tr>
<tr><td>Swati</td><td>Sironi</td><td>82</td></tr>
<tr><td>Chetna</td><td>Singh</td><td>72</td></tr>
</table>
Output:
Sonoo Jaiswal 60
James William 80
Swati Sironi 82
Chetna Singh 72
In the above html table, there are 5 rows and 3 columns = 5 * 3 = 15 values.
You can use the border a ribute of table tag in HTML to specify border. But it is not
recommended now.
<table border="1">
<tr><th>First_Name</th><th>Last_Name</th><th>Marks</th></tr>
<tr><td>Sonoo</td><td>Jaiswal</td><td>60</td></tr>
<tr><td>James</td><td>William</td><td>80</td></tr>
<tr><td>Swati</td><td>Sironi</td><td>82</td></tr>
<tr><td>Chetna</td><td>Singh</td><td>72</td></tr>
</table>
Output:
Sonoo Jaiswal 60
James William 80
Swati Sironi 82
Chetna Singh 72
table.
<style>
table, th, td {
border: 1px solid black;
}
</style>
You can collapse all the borders in one border by border-collapse property. It will
<style>
table, th, td {
border: 2px solid black;
border-collapse: collapse;
}
</style>
Output:
Sonoo Jaiswal 60
James William 80
Swati Sironi 82
Chetna Singh 72
You can specify padding for table header and table data by two ways:
The cellpadding a ribute of the HTML table tag is obsolete now. It is recommended to
use CSS. So let's see the code of CSS.
<style>
table, th, td {
border: 1px solid pink;
border-collapse: collapse;
}
th, td {
padding: 10px;
}
</style>
We can specify the HTML table width using the CSS width property. It can be specified
in pixels or percentage.
We can adjust our table width as per our requirement. Following is the example to
display the table with width.
table{
width: 100% }
Example:
<!DOCTYPE html>
<html>
<head>
<title>table</title>
<style>
table{
border-collapse: collapse;
width: 100%;
}
th,td{
border: 2px solid green;
padding: 15px;
}
</style>
</head>
<body>
Output:
If you want to make a cell span more than one column, you can use the colspan a ribute.
CSS code:
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
}
</style>
HTML code:
<table style="width:100%">
<tr>
<th>Name</th>
<th colspan="2">Mobile No.</th>
</tr>
<tr>
<td>Heena Panjwani</td>
<td>9125678593</td>
<td>7995825454</td>
</tr>
</table>
Output:
Name Mobile No.
If you want to make a cell span more than one row, you can use the rowspan a ribute.
It will divide a cell into multiple rows. The number of divided rows will depend on
rowspan values.
CSS code:
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 10px;
}
</style>
HTML code:
<table>
<tr><th>Name</th><td>Heena Panjwani</td></tr>
<tr><th rowspan="2">Mobile No.</th><td>9125678593</td></tr>
<tr><td>7995825454</td></tr>
</table>
Output:
7995825454
HTML caption is displayed above the table. It must be used after the table tag only.
<table>
<caption>Student Records</caption>
<tr><th>First_Name</th><th>Last_Name</th><th>Marks</th></tr>
<tr><td>Vimal</td><td>Jaiswal</td><td>70</td></tr>
<tr><td>Mike</td><td>Warn</td><td>60</td></tr>
<tr><td>Shane</td><td>Warn</td><td>42</td></tr>
<tr><td>Jai</td><td>Malhotra</td><td>62</td></tr>
</table>
Frames
Frames help us to divide the browser’s window into multiple rectangular regions. Each
region contains a separate html web page and each of them work independently.
A set of frames in the entire browser is known as frameset. It tells the browser how to
divide the browser window into frames and the web pages that each has to load.
The following table describes the various tags used for creating frames:
Tag Description
<frameset> It is a replacement of the <body> tag. It doesn’t contain the tags that are
</frameset> normally used in <body> element; instead it contains the <frame> element
used to add each frame.
<base> It is used to set the default target frame in any page that contains links whose
</base> contents are displayed in another frame.
The metadata does not display on the webpage, but it is used by search engines, browsers
and other web services which scan the site or webpage to know about the webpage.
With the help of meta tag, you can experiment and preview how your webpage will render
on the browser.
The <meta> tag is placed within the <head> tag, and it can be used more than one time in a
document.
Syntax:
1. <meta charset="utf-8">
Display None
Following are some specific syntaxes of meta tag which shows the different uses of meta
Tag.
1. <meta charset="utf-8">
It defines the character encoding. The value of charset is "utf-8" which means it will support
displaying any language.
It defines the website description which is useful to provide relevant search performed by
search engines.
It specifies the author of the page. It is useful to extract author information by Content
management system automatically.
In the above example we have set a URL with content so it will automatically redirect to the
given page after the provided time.
It specifies the viewport to control the page dimension and scaling so that our website
looks good on all devices. If this tag is present, it indicates that this page is mobile device
supported.
Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="keywords" content="HTML, CSS, JavaScript,
Tutorials">
<meta name="description" content="Free Online tutorials">
<meta name="author" content="thisauthor">
<meta http-equiv="refresh" content="5;
url=https://www.google.com/html-tags-list">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
</head>
<body>
<h2>Example of Meta tag</h2>
<p>This example shows the use of meta tag within an HTML
document</p>
</body>
</html>
HTML iframes
HTML Iframe is used to display a nested webpage (a webpage within a webpage). The
HTML <iframe> tag defines an inline frame, hence it is also called an Inline frame.
An HTML iframe embeds another document within the current HTML document in the
rectangular region.
The webpage content and iframe contents can interact with each other using JavaScript.
Iframe Syntax
1. <iframe src="URL"></iframe>
Here, "src" a ribute specifies the web address (URL) of the inline frame page.
You can set the width and height of an iframe by using "width" and "height" a ributes. By
default, the a ributes values are specified in pixels but you can also set them in percent. i.e.
Example: (Pixels)
<!DOCTYPE html>
<html>
<body>
<h2>HTML Iframes example</h2>
<p>Use the height and width attributes to specify the size of the
iframe:</p>
<iframe src="https://www.google.com/" height="300"
width="400"></iframe>
</body>
</html>
You can set a target frame for a link by using iframe. Your specified target a ribute of the
Example:
<!DOCTYPE html>
<html>
<body>
Forms
Forms are used to input the values. These values are sent to the server for processing.
Forms use input elements such as text fields, check boxes, radio bu ons, lists, submit
bu ons etc. to enter the data into it.
The following table describes the commonly used tags while creating a form:
Tag Description
<textarea> </textarea> Specifies a text area control that allows users to enter
multi-line text.
Form is a data collection mechanism within HTML that allows the design of various styles
of input to suit most types of information.
An input element can vary in many ways, depending on the type a ribute. An input
element can
be of type textfield, checkbox, password, radiobu on, submit bu on, and more.
2. Action:
The required action a ribute specifies where to send the form-data when a form
Issubmi ed.
<form action="URL"> Value : URL
Description : Where to send the form data.
3. Method :
The method a ribute specifies how to send form-data (the form-data is sent to the
page specified in the action a ribute).
<form method="get|post">
Value : get
Description : Default. Appends the form-data to the URL in name/value pairs:
URL?name=value name=value
Value : post
Description : Sends the form-data as an HTTP post transaction.
4. Target
The target a ribute specifies a name or a keyword that indicates where to display the
response that is received after submi ing the form.
<form target="_blank|_self|_parent|_top|framename">
1. mp3
2. wav
3. ogg
HTML5 supports <video> and <audio> controls. The Flash, Silverlight and similar
technologies are used to play the multimedia items.
This table defines that which web browser supports which audio file format.
Let's see the code to play an mp3 file using the HTML audio tag.
<audio controls>
<source src="koyal.mp3" type="audio/mpeg">
Your browser does not support the html audio tag.
</audio>
A ributes of HTML Audio Tag
A ribute Description
controls It defines the audio controls which are displayed with play/pause bu ons.
autoplay It specifies that the audio will start playing as soon as it is ready.
loop It specifies that the audio file will start over again, every time when it is
completed.
preload It specifies the author view to upload an audio file when the page loads.
Here we are going to use controls, autoplay, loop and src a ributes of HTML audio tag.
mp3 audio/mpeg
ogg audio/ogg
wav audio/wav
HTML 5 supports <video> tag also. The HTML video tag is used for streaming video files
such as a movie clip, song clip on the web page.
Currently, there are three video formats supported for HTML video tag:
1. mp4
2. webM
3. ogg
Let's see the table that defines which web browser supports video file format.
Let's see the code to play mp4 files using the HTML video tag.
<video controls>
<source src="movie.mp4" type="video/mp4">
Your browser does not support the html video tag.
</video>
A ribute Description
controls It defines the video controls which are displayed with play/pause bu ons.
poster It specifies the image which is displayed on the screen when the video is
not played.
autoplay It specifies that the video will start playing as soon as it is ready.
loop It specifies that the video file will start over again, every time when it is
completed.
preload It specifies the author view to upload a video file when the page loads.
Let's see the example of a video tag in HTML where we are using height, width, autoplay,
controls and loop a ributes.
mp4 video/mp4
ogg video/ogg
webM video/webM
If you want to achieve the Drag and Drop functionality in traditional HTML4, you must
either have to use complex JavaScript programming or other JavaScript frameworks like
jQuery etc.
Event Description
Drag It fires every time when the mouse is moved while the object is being
dragged.
Dragstart It is a very initial stage. It fires when the user starts dragging the object.
Dragenter It fires when the user moves his/her mouse cursor over the target element.
Dragover This event is fired when the mouse moves over an element.
Dragend It fires when the user releases the mouse bu on to complete the drag
operation.
If you want to make an element draggable, set the draggable a ribute to "true" on the
element. For example:
3) Where to Drop:
4) Do the Drop:
HTML5 Geolocation
The Geolocation is one of the best HTML5 API which is used to identify the user's
geographic location for the web application.
This new feature of HTML5 allows you to navigate the latitude and longitude coordinates
of the current website's visitor. These coordinates can be captured by JavaScript and send
to the server which can show your current location on the website
Most of the geolocation services use Network routing addresses such as IP addresses,
RFID, WIFI and MAC addresses or internal GPS devices to identify the user's location.
User privacy:
The user's location is a privacy concern, so the geolocation API protects the user's privacy
by taking the user's permission before ge ing the location. Geolocation API sends a
notification prompt box which the user can allow or deny, and if the user allows then only
his location will be identified.
Geolocation object
Syntax:
1. geo=navigator. geolocation;
If this object is present, then you can get the geolocation services.
Geolocation Methods
The Geolocation API uses three methods of Geolocation interface which are given
following:
Methods Description
getCurrentPosition() It identifies the device or the user's current location and returns a
position object with data.
<!DOCTYPE html>
<html>
<head>
<title>Geolocation API</title>
</head>
<body>
<h1>Find your Current location</h1>
<button onclick="getlocation()">Click me</button>
<div id="location"></div>
● error: An error callback function which takes "Position Error" object as input.
The below example will return the longitude and latitude of the visitor's current location.
Example
<!DOCTYPE html>
<html>
<head>
<title>Geolocation API</title>
</head>
<body>
<h1>Find your Current location</h1>
<button onclick="getlocation()">Click me</button>
<div id="location"></div>
<script>
var x= document.getElementById("location");
function getlocation() {
Storing data with the help of web storage is similar to cookies, but it is be er and faster
than cookie storage.
● Web Storage can use storage space upto 5MB per domain. (The browser software
● It will not send data to the server side, hence it is faster than cookie storage.
● The data stored by local Storage never expires, but cookie data expires after some
time or session.
There are two types of web storage with different scope and lifetime.
● Local Storage: Local Storages uses Windows.localStorage object which stores data
and is available for every page. But data persist even if the browser is closed and
data for one session and data will be lost if the window or browser tab will be
closed.
<!DOCTYPE html>
<html>
<body>
<div id="result"></div>
<script>
if(typeof(Storage)!=="undefined") {
document.getElementById("result").innerHTML = "Hey, Your browser
supports the Web Storage.";
}
else{
document.getElementById("result").innerHTML = "Sorry, your browser
does not support Web Storage";
}
</script>
</body>
</html>
HTML5
HTML5 provides details of all 40+ HTML tags including audio, video, header, footer, data,
datalist, article etc. This HTML tutorial is designed for beginners and professionals.
HTML5 is the next version of HTML. Here, you will get some brand new features which
will make HTML much easier. These new introducing features make your website layout
It is enriched with advanced features which makes it easy and interactive for
designer/developer and users.
● It facilitates you to design be er forms and build web applications that work offline.
● It provides you advanced features for that you would normally have to write
JavaScript to do.
● The most important reason to use HTML 5 is, we believe it is not going anywhere. It
New Features
HTML5 introduces a number of new elements and a ributes that can help you in building
modern websites. Here is a set of some of the most prominent features introduced in
HTML5.
● New Semantic Elements − These are like <header>, <footer>, and <section>.
● Forms 2.0 − Improvements to HTML web forms where new a ributes have been
applications.
● Server-Sent Events − HTML5 introduces events which flow from web server to the
● Canvas − This supports a two-dimensional drawing surface that you can program
with JavaScript.
● Audio & Video − You can embed audio or video on your webpages without
● Geolocation − Now visitors can choose to share their physical location with your
web application.
● Microdata − This lets you create your own vocabularies beyond HTML5 and extend
● Drag and drop − Drag and drop the items from one location to another location on
HTML HTML5
It didn’t support audio and video It supports audio and video controls with
without the use of flash player support. the use of <audio> and <video> tags.
It does not allow drag and drop effects. It allows drag and drop effects.
Not possible to draw shapes like circle, HTML5 allows you to draw shapes like
rectangle, triangle etc. circle, rectangle, triangle etc.
Doctype declaration is too long and Doctype declaration is quite simple and
complicated. easy.
Elements like nav, header were not New element for web structure like nav,
present. header, footer etc.
A ributes like charset, async and ping A ributes of charset, async and ping are a
are absent in HTML. part of HTML 5.
HTML 5 Example
<!DOCTYPE>
<html>
<head>
<title>Web page title</title>
</head>
<body>
<h1>Write Your First Heading</h1>
<p>Write Your First Paragraph.</p>
</body>
</html>
HTML 5 Tags
There is a list of newly included tags in HTML 5. These HTML 5 tags (elements) provide a
be er document structure. This list shows all HTML 5 tags in alphabetical order with
description.
Tag Description
<aside> It specifies that the article is slightly related to the rest of the whole page.
<bdi> The bdi stands for bi-directional isolation. It isolates a part of text that is
forma ed in another direction from the outside text document.
<menuitem> It defines a command that the user can invoke from a popup menu.
<rp> It defines what to show in browsers that don't support ruby annotation.
● The header tag contains information related to the title and heading of the related
content.
● The <header> element is intended to usually contain the section’s heading (an h1-h6
● The <header> element can also be used to wrap a section’s table of contents, a search
● The <header> tag is a new tag in HTML5 and it requires a starting tag as well as an end
tag.
Syntax:
Example 1:
<!DOCTYPE html>
<html>
<head>
<title>Header Tag</title>
</head>
<body>
<article>
<header>
<h1>This is the heading.</h1>
<h4>This is the
sub-heading.</h4>
<p>This is the metadata.</p>
</header>
</article>
</body>
</html>
Output:
The <footer> tag in HTML is used to define a footer of HTML documents. This section
contains the footer information (author information, copyright information, carriers, etc).
The footer tag is used within the body tag. The <footer> tag is new in the HTML5. The
footer elements require a start tag as well as an end tag.
The <article> tag is one of the new sectioning elements in HTML5. The HTML <article> tag
is used to represent an article. More specifically, the content within the <article> tag is
independent of the other content of the site (even though it can be related).
In other words, The article element represents a component of a page that consists of
self-contained composition in a document, page, or site. For Ex. in syndication.
● A magazine/newspaper article
● A blog entry
● A forum post
● A user-submi ed a comment
● On a page with a single piece of content, a single <article> element can be used to
contain the main content and set it off from the rest of the page.
● On a page with multiple pieces of content (a blog index page, a search results
page, a category page, news feed), multiple <article> elements can be used to
Either way, it is similar to the <div> element and displays the stylish work the same.
However, using the <article> element instead of <div> provides more semantic information
Note: This tag does not render as anything special in a browser, you have to use CSS for
that.
Default CSS se ing: Most browsers will display the Article element with the following
values.
HTML
<article> {
display:block;
When creating a <section> in HTML5, as when you used the <div> tag in HTML, you can
use either the id or class a ributes. Each id must be unique, as in HTML, and class can be
used multiple times when necessary.
You should always have a header element (H1 through H6) as a part of the section. If you
can’t come up with a title for the section, then again the <div> element is probably more
appropriate. And never ever use section tags for pu ing styles only.
Let’s say you were creating a document about data processing. The following represents a
typical use for the <section> elements.
What is CSS?
CSS Syntax
Example
<!DOCTYPE html>
<html>
<head>
<style>
p {
color: red;
text-align: center;
}
Hello World!
CSS Comments
Comments are used to explain the code, and may help when you edit the source code at a
later date.
Example
<!DOCTYPE html>
<html>
<head>
<style>
/* This is a single-line comment */
p {
color: red;
}
</style>
</head>
<body>
<p>Hello World!</p>
<p>This paragraph is styled with CSS.</p>
<p>CSS comments are not shown in the output.</p>
</body>
</html>
Hello World!
1. External Style Sheet − Define style sheet rules in a separate .css file and then include
that file in your HTML document using HTML <link> tag.
2. Internal Style Sheet − Define style sheet rules in header section of the HTML
document using <style> tag.
3. Inline Style Sheet − Define style sheet rules directly along-with the HTML elements
using style a ribute.
If you need to use your style sheet to various pages, then it's always recommended
to define a common style sheet in a separate file. A cascading style sheet file will
have extension as .css and it will be included in HTML files using <link> tag.
Example
.red {
color: red;
}
.thick {
font-size:20px;
}
.green {
color:green;
}
<!DOCTYPE html>
<html>
<head>
<title>HTML External CSS</title>
<link rel = "stylesheet" type = "text/css" href =
"/html/style.css">
</head>
<body>
<p class = "red">This is red</p>
<p class = "thick">This is thick</p>
<p class = "green">This is green</p>
<p class = "thick green">This is thick and green</p>
If you want to apply Style Sheet rules to a single document only, then you can include
those rules in the header section of the HTML document using <style> tag.
Rules defined in the internal style sheet overrides the rules defined in an external CSS file.
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML Internal CSS</title>
You can apply style sheet rules directly to any HTML element using the style a ribute of
the relevant tag. This should be done only when you are interested to make a particular
change in any HTML element only.
Rules defined inline with the element overrides the rules defined in an external CSS file as
well as the rules defined in <style> element.
- It has the ability to override other style specification methods at the local level.
- The styles for many documents can not be controlled from one source.
- Control classes can not be created to control multiple element types within the document.
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML Inline CSS</title>
</head>
<body>
<p style = "color:red;">This is red</p>
<p style = "font-size:20px;">This is thick</p>
<p style = "color:green;">This is green</p>
<p style = "color:green;font-size:20px;">This is thick and
green</p>
</body>
</html>
CSS Selectors
CSS selectors are used to "find" (or select) the HTML elements you want to style.
The element selector selects HTML elements based on the element name.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
p {
text-align: center;
color: red;
}
</style>
</head>
<body>
<p>Every paragraph will be affected by the style.</p>
<p id="para1">Me too!</p>
<p>And me!</p>
</body>
</html>
Me too!
And me!
The id selector uses the id a ribute 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
<!DOCTYPE html>
<html>
<head>
<style>
Hello World!
The class selector selects HTML elements with a specific class a ribute.
To select elements with a specific class, write a period (.) character, followed by the class
name.
<!DOCTYPE html>
<html>
<head>
<style>
.center {
text-align: center;
color: red;
}
</style>
</head>
<body>
<h1 class="center">Red and center-aligned heading</h1>
<p class="center">Red and center-aligned paragraph.</p>
</body>
</html>
The universal selector (*) selects all HTML elements on the page.
<!DOCTYPE html>
<html>
<head>
<style>
* {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<h1>Hello world!</h1>
<p>Every element on the page will be affected by the style.</p>
<p id="para1">Me too!</p>
<p>And me!</p>
</body>
</html>
Hello world!
Me too!
And me!
The grouping selector selects all the HTML elements with the same style definitions.
Look at the following CSS code (the h1, h2, and p elements have the same style definitions):
<!DOCTYPE html>
<html>
<head>
Hello World!
Smaller heading!
This is a paragraph.
CSS Pseudo-classes
Syntax
selector:pseudo-class {
property:value;
Anchor Pseudo-classes
<!DOCTYPE html>
<html>
<head>
<style>
/* unvisited link */
a:link {
color: red;
}
/* visited link */
a:visited {
color: green;
}
/* selected link */
a:active {
color: blue;
}
</style>
</head>
<body>
<h2>CSS Links</h2>
<p><b><a href="default.asp" target="_blank">This is a
link</a></b></p>
<p><b>Note:</b> a:hover MUST come after a:link and a:visited in the
CSS definition in order to be effective.</p>
<p><b>Note:</b> a:active MUST come after a:hover in the CSS
definition in order to be effective.</p>
</body>
</html>
CSS Links
This is a link
Note: a:active MUST come after a:hover in the CSS definition in order to be effective.
Hover on <div>
<!DOCTYPE html>
<html>
<head>
<style>
div {
background-color: green;
color: white;
padding: 25px;
text-align: center;
}
div:hover {
background-color: blue;
}
</style>
</head>
<body>
<p>Mouse over the div element below to change its background
color:</p>
<div>Mouseover Me</div>
</body>
</html>
Mouse over the div element below to change its background color:
Mouse Over Me
Hello World
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad
minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex
ea commodo consequat.
Example
<!DOCTYPE html>
<html>
<head>
<style>
div.a {
text-align: center;
}
div.b {
text-align: left;
}
div.c {
text-align: right;
}
div.d {
text-align: justify;
}
</style>
</head>
<body>
<h1>The text-align Property</h1>
<div class="a">
<h2>text-align: center:</h2>
<div class="c">
<h2>text-align: right:</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam
semper diam at erat pulvinar, at pulvinar felis blandit. Vestibulum
volutpat tellus diam, consequat gravida libero rhoncus ut.</p>
</div>
<div class="d">
<h2>text-align: justify:</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam
semper diam at erat pulvinar, at pulvinar felis blandit. Vestibulum
volutpat tellus diam, consequat gravida libero rhoncus ut.</p>
</div>
</body>
</html>
O/P:
text-align: center:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat
pulvinar, at pulvinar felis blandit. Vestibulum volutpat tellus diam, consequat gravida
libero rhoncus ut.
text-align: left:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat
pulvinar, at pulvinar felis blandit. Vestibulum volutpat tellus diam, consequat gravida
libero rhoncus ut.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat
pulvinar, at pulvinar felis blandit. Vestibulum volutpat tellus diam, consequat gravida
libero rhoncus ut.
text-align: justify:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat
pulvinar, at pulvinar felis blandit. Vestibulum volutpat tellus diam, consequat gravida
libero rhoncus ut.
Property Values
Value Description
justify Stretches the lines so that each line has equal width (like in
newspapers and magazines)
div.a {
text-align: justify; /* For Edge */
text-align-last: right;
}
div.b {
text-align: justify; /* For Edge */
text-align-last: center;
}
O/P:
text-align-last: right:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat
pulvinar, at pulvinar felis blandit. Vestibulum volutpat tellus diam, consequat gravida
libero rhoncus ut.
text-align-last: center:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat
pulvinar, at pulvinar felis blandit. Vestibulum volutpat tellus diam, consequat gravida
libero rhoncus ut.
text-align-last: justify:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat
pulvinar, at pulvinar felis blandit. Vestibulum volutpat tellus diam, consequat gravida
libero rhoncus ut.
The text-align-last property specifies how to align the last line of a text.
Notice that the text-align-last property sets the alignment for all last lines within the
selected element. So, if you have a <div> with three paragraphs in it, text-align-last will
apply to the last line of EACH of the paragraphs.
Note: In Edge/Internet Explorer the text-align-last property only works on text that has
"text-align: justify".
h2 {
text-decoration: line-through;
}
h3 {
text-decoration: underline;
}
h4 {
text-decoration: underline overline;
}
</style>
</head>
<body>
</body>
</html>
O/P:
This is heading 1
This is heading 2
This is heading 3
This is heading 4
● text-decoration-line (required)
● text-decoration-color
● text-decoration-style
text-decoration: underline;
text-decoration-color: red;
CSS Borders
● do ed - Defines a do ed border
● dashed - Defines a dashed border
● solid - Defines a solid border
● double - Defines a double border
● groove - Defines a 3D grooved border. The effect depends on the border-color value
● ridge - Defines a 3D ridged border. The effect depends on the border-color value
● inset - Defines a 3D inset border. The effect depends on the border-color value
● outset - Defines a 3D outset border. The effect depends on the border-color value
● none - Defines no border
● hidden - Defines a hidden border
The border-style property can have from one to four values (for the top border, right
Example
p.dotted {border-style: dotted;}
p.dashed {border-style: dashed;}
p.solid {border-style: solid;}
p.double {border-style: double;}
p.groove {border-style: groove;}
p.ridge {border-style: ridge;}
p.inset {border-style: inset;}
p.outset {border-style: outset;}
p.none {border-style: none;}
p.hidden {border-style: hidden;}
p.mix {border-style: dotted dashed solid double;}
The width can be set as a specific size (in px, pt, cm, em, etc) or by using one of the three
predefined values: thin, medium, or thick.
The border-width property can have from one to four values (for the top border, right
border, bo om border, and the left border).
Example
p.one {
border-style: solid;
border-width: 5px;
}
p.two {
border-style: solid;
border-width: medium;
}
p.one {
border-style: solid;
border-color: red;
}
p.two {
border-style: solid;
border-color: green;
}
p.three {
border-style: solid;
border-color: red green blue yellow;
}
CSS Margins
The CSS margin properties are used to create space around elements, outside of any
defined borders.
With CSS, you have full control over the margins. There are properties for se ing the
margin for each side of an element (top, right, bo om, and left).
CSS has properties for specifying the margin for each side of an element:
● margin-top
● margin-right
● margin-bo om
● margin-left
EXAMPLE:
<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 1px solid black;
margin-top: 100px;
margin-bottom: 100px;
margin-right: 150px;
margin-left: 80px;
background-color: lightblue;
}
</style>
</head>
<body>
</body>
</html>
O/P:
The CSS padding properties are used to generate space around an element's content, inside
of any defined borders.
With CSS, you have full control over the padding. There are properties for se ing the
padding for each side of an element (top, right, bo om, and left).
CSS has properties for specifying the padding for each side of an element:
● padding-top
● padding-right
● padding-bo om
● padding-left
Example:
<!DOCTYPE html>
O/P:
h2 {
position: absolute;
left: 100px;
top: 150px;
With absolute positioning, an element can be placed anywhere on a page. The heading
below is placed 100px from the left of the page and 150px from the top of the page.
Property Values
Value Description
static Default value. Elements render in order, as they appear in the document flow
absolute The element is positioned relative to its first positioned (not static) ancestor element
relative The element is positioned relative to its normal position, so "left:20px" adds 20
pixels to the element's LEFT position
CSS - Lists
Lists are very helpful in conveying a set of either numbered or bullet points. This chapter
teaches you how to control list type, position, style, etc., using CSS.
We have the following five CSS properties, which can be used to control lists −
● The list-style-type allows you to control the shape or appearance of the marker.
● The list-style-position specifies whether a long point that wraps to a second line
should align with the first line or start underneath the start of the marker.
● The list-style-image specifies an image for the marker rather than a bullet point or
number.
● The list-style serves as shorthand for the preceding properties.
● The marker-offset specifies the distance between a marker and the text in the list.
The list-style-type property allows you to control the shape or style of bullet point (also
known as a marker) in the case of unordered lists and the style of numbering characters in
ordered lists
Here are the values which can be used for an unordered list −
1 none
NA
2 disc (default)
A filled-in circle
3 circle
An empty circle
4 square
A filled-in square
Here is an example −
<body>
<ul style = "list-style-type:circle;">
<li>Maths</li>
<li>Social Science</li>
<li>Physics</li>
</ul>
○ Maths
○ Social Science
○ Physics
■ Maths
■ Social Science
CSS Gradients
CSS gradients let you display smooth transitions between two or more specified colors.
To create a linear gradient you must define at least two color stops. Color stops are the
colors you want to render smooth transitions among. You can also set a starting point and a
direction (or an angle) along with the gradient effect.
Syntax
Example:
#grad {
To create a radial gradient you must also define at least two color stops.
Syntax
Example:
#grad {
CSS Animations
● @keyframes
● animation-name
● animation-duration
● animation-delay
When you specify CSS styles inside the @keyframes rule, the animation will gradually
change from the current style to the new style at certain times.
The following example binds the "example" animation to the <div> element. The animation
will last for 4 seconds, and it will gradually change the background-color of the <div>
element from "red" to "yellow":
@keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
/* The element to apply the animation to */
div {
width: 100px; height:
100px; background-
color: red;
animation-name: example;
animation-duration: 4s;
}
Note: The animation-duration property defines how long an animation should take to
complete. If the animation-duration property is not specified, no animation will occur,
because the default value is 0s (0 seconds).
It is also possible to use percent. By using percent, you can add as many style changes as you like.
The following example will change the background-color of the <div> element when the
animation is 25% complete, 50% complete, and again when the animation is 100%
complete:
The following example will change both the background-color and the position of the
<div> element when the animation is 25% complete, 50% complete, and again when the
animation is 100% complete:
CSS Tooltips
CSS Tooltips are a great way to display extra information about something when the user moves
the mouse cursor over an element.
Top Tooltip
The top tooltip specifies that if you move your mouse cursor over the element, the tooltip
information will be displayed on the top of the element.
<!DOCTYPE html>
<html>
<style>
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
}
.tooltip .tooltiptext
{ visibility: hidden;
width: 120px;
background-color: red;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;
position: absolute;
z-index: 1;
bottom: 100%;
left: 50%;
margin-left: -60px;
}
.tooltip:hover .tooltiptext {
visibility: visible;
}
</style>
<body style="text-align:center;">
<h2>Top Tooltip Example</h2>
<p>Move your mouse cursor over the below heading</p>
Bo om Tooltip
The bo om tooltip specifies that if you move your mouse cursor over the element, the
tooltip information will be displayed on the bo om of the element.
<!DOCTYPE html>
<html>
<style>
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
}
.tooltip .tooltiptext
{ visibility: hidden;
width: 120px;
background-color: red;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;
position: absolute;
z-index: 1;
top: 100%;
left: 50%;
margin-left: -60px;
}
.tooltip:hover .tooltiptext {
visibility: visible;
}
</style>
<body style="text-align:center;">
<h2>Bottom Tooltip Example</h2>
<p>Move your mouse cursor over the below heading</p>
<div class="tooltip"><strong> Welcome to AIT</strong>
<span class="tooltiptext">A solution of all technology.</span>
</div>
Left Tooltip
The left tooltip specifies that if you move your mouse cursor over the element, the tooltip
information will be displayed on the left side of the element.
<!DOCTYPE html>
<html>
<style>
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
}
.tooltip .tooltiptext
{ visibility: hidden;
width: 120px;
background-color: red;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;
position: absolute;
z-index: 1;
top: -5px;
right: 105%;
}
.tooltip:hover .tooltiptext {
visibility: visible;
}
</style>
<body style="text-align:center;">
<h2>Left Tooltip Example</h2>
<p>Move your mouse cursor over the below heading</p>
<div class="tooltip"><strong> Welcome to AIT</strong>
<span class="tooltiptext">A solution of all technology.</span>
</div>
</body>
</html>
The right tooltip specifies that if you move your mouse cursor over the element, the tooltip
information will be displayed on the right side of the element.
<!DOCTYPE html>
<html>
<style>
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
}
.tooltip .tooltiptext
{ visibility: hidden;
width: 120px;
background-color: red;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;
position: absolute;
z-index: 1;
top: -5px;
left: 105%;
}
.tooltip:hover .tooltiptext {
visibility: visible;
}
</style>
<body style="text-align:center;">
<h2>Right Tooltip Example</h2>
<p>Move your mouse cursor over the below heading</p>
<div class="tooltip"><strong> Welcome to AIT</strong>
<span class="tooltiptext">A solution of all technology.</span>
</div>
</body>
</html>
Rounded Images
Rounded Image:
img {
border-radius: 8px;
}
Thumbnail Images
Thumbnail Image:
img {
border: 1px solid #ddd;
border-radius: 4px;
padding: 5px;
width: 150px;
}
Responsive Images
Example:
img {
max-width: 100%;
height: auto;
}
Transparent Image
The opacity property can take a value from 0.0 - 1.0. The lower value, the more transparent:
(default)
img {
opacity: 0.5;
CSS Variables
CSS variables have access to the DOM, which means that you can create variables with
local or global scope, change the variables with JavaScript, and change the variables based
on media queries.
The following example shows the traditional way of defining some colors in a style sheet
(by defining the colors to use, for each specific element):
Example:
var(name, value)
Value Description
name Required. The variable name (must start with two dashes)
value Optional. The fallback value (used if the variable is not found)
Note: The variable name must begin with two dashes (--) and it is case sensitive!
Global variables can be accessed/used through the entire document, while local variables
can be used only inside the selector where it is declared.
To create a variable with global scope, declare it inside the :root selector. The :rootselector
matches the document's root element.
To create a variable with local scope, declare it inside the selector that is going to use it. The
following example is equal to the example above, but here we use the var() function. First,
we declare two global variables (--blue and --white). Then, we use the var() function
to insert the value of the variables later in the style sheet:
Example:
:root {
--blue: #1e90ff;
--white: #ffffff;
}
body { background-color: var(--blue); }
h2 { border-bottom: 2px solid var(--blue); }
.container {
color: var(--blue);
background-color: var(--white);
padding: 15px;
}
button {
background-color: var(--white);
color: var(--blue);
border: 1px solid var(--blue);
padding: 5px;
}
Before the Flexbox Layout module, there were four layout modes:
The Flexible Box Layout Module makes it easier to design flexible responsive layout
structure without using float or positioning.
Flexbox Elements
To start using the Flexbox model, you need to first define a flex container.
The element above represents a flex container with three flex items.
Example:
<div class="flex-container">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
The flex container becomes flexible by se ing the display property to flex:
.flex-container {
display: flex;
● flex-direction
● flex-wrap
● flex-fl ow
● justify-content
● align-items
● align-content
The flex-direction property defines in which direction the container wants to stack the flex
items.
Example
The column value stacks the flex items vertically (from top to bo om):
.flex-container {
display: flex;
flex-direction: column;
}
Example
The column-reverse value stacks the flex items vertically (but from bo om to top):
.flex-container {
display: flex;
flex-direction: column-reverse;
}
Example
The row value stacks the flex items horizontally (from left to right):
.flex-container {
display: flex;
flex-direction: row;
}
Example
The row-reverse value stacks the flex items horizontally (but from right to left):
.flex-container {
display: flex;
flex-direction: row-reverse;
}
The flex-wrap property specifies whether the flex items should wrap or not.
The examples below have 12 flex items, to be er demonstrate the flex-wrap property.
3
4
10
11
12
Example
The wrap value specifies that the flex items will wrap if necessary:
.flex-container
{ display: flex;
flex-wrap: wrap;
}
Example
The nowrap value specifies that the flex items will not wrap (this is default):
.flex-container {
display: flex;
flex-wrap: nowrap;
}
Example
The wrap-reverse value specifies that the flexible items will wrap if necessary, in reverse order:
.flex-container {
display: flex;
flex-wrap: wrap-reverse;
}
The flex-flow property is a shorthand property for se ing both the flex-direction and
flex-wrap properties.
Example
.flex-container {
display: flex;
flex-flow: row wrap;
}
The following table lists all the CSS Flexbox Items properties:
Property Description
align-self Specifies the alignment for a flex item (overrides the flex
container's align-items property)
flex-grow Specifies how much a flex item will grow relative to the rest of
the flex items inside the same container
flex-shrink Specifies how much a flex item will shrink relative to the rest
of the flex items inside the same container
order Specifies the order of the flex items inside the same container
The @media rule, introduced in CSS2, made it possible to define different style rules for
different media types.
Examples: You could have one set of style rules for computer screens, one for printers, one
for handheld devices, one for television-type devices, and so on.
Unfortunately these media types never got a lot of support by devices, other than the print
media type.
Media queries in CSS3 extended the CSS2 media types idea: Instead of looking for a type of
device, they look at the capability of the device.
Using media queries is a popular technique for delivering a tailored style sheet to desktops,
laptops, tablets, and mobile phones (such as iPhone and Android phones).
A media query consists of a media type and can contain one or more expressions, which
resolve to either true or false.
The result of the query is true if the specified media type matches the type of device the
document is being displayed on and all expressions in the media query are true. When a
media query is true, the corresponding stylesheet or style rules are applied, following the
normal cascading rules.
Unless you use the not or only operators, the media type is optional and the all type will be
implied.
Value Description
speech Used for screen readers that "reads" the page out loud
One way to use media queries is to have an alternate CSS section right inside your style
sheet.
The following example changes the background-color to light green if the viewport is 480
pixels wide or wider (if the viewport is less than 480 pixels, the background-color will be
pink):
Example
@media screen and (min-width: 480px) {
body {
background-color: light green;
}
}
The following example shows a menu that will float to the left of the page if the viewport is
480 pixels wide or wider (if the viewport is less than 480 pixels, the menu will be on top of
the content):
Example
Syntax:
[a ribute*="value"] {
// CSS property
Example:
<!DOCTYPE html>
<html>
<head>
<style>
Output:
[a ribute^=”str”] Selector: The [a ribute^=”value”] selector is used to select those elements whose
a ribute value begins with a specified value str. This example shows how to use a wildcard to
select all div with a class that starts with str.
Syntax:
[a ribute^="str"] {
// CSS property
Syntax:
[a ribute$="str"] {
// CSS property
● CSS1 had a major difficulty with adaptation and consistency across different web
browsers. The number of web browsers has also increased largely. CSS2 still has
browser extension issues. CSS3 has complete support for almost all recent web
browsers.
● CSS1 had limited styling options and old design influences. The properties and
Bootstrap is the popular HTML, CSS and JavaScript framework for developing a
responsive and mobile friendly website.
What is Bootstrap
● Bootstrap is the most popular HTML, CSS and JavaScript framework for developing
● It includes HTML and CSS based design templates for typography, forms, bu ons,
History of Bootstrap
Bootstrap was developed by Mark O o and Jacob Thornton at Twi er.It was released as an
open source product in August 2011 on GitHub.
● It is very easy to use. Anybody having basic knowledge of HTML and CSS can use
Bootstrap.
● It is compatible on most browsers like Chrome, Firefox, Internet Explorer, Safari and
Opera etc.
A website is called a responsive website which can automatically adjust itself to look good
on all devices, from smartphones to desktops etc.
CSS: Bootstrap comes with the feature of global CSS se ings, fundamental HTML elements
style and an advanced grid system.
JavaScript Plugins: Bootstrap also contains a lot of custom jQuery plugins. You can easily
include them all, or one by one.
Customize: Bootstrap components are customizable and you can customize Bootstrap's
components, LESS variables, and jQuery plugins to get your own style.
What is Bootstrap 4?
Bootstrap is the newest and latest version of Bootstrap. It is the most popular HTML, CSS,
JavaScript framework for developing responsive, mobile first websites.
Bootstrap 4 has some new components, faster stylesheet, more bu ons, effects and more
responsiveness.
Bootstrap 4 supports some of the latest, stable releases of all major browsers and platforms.
Note: Internet Explorer 9 and down is not supported by Bootstrap 4. Although Internet
Explorer 8-9 supported Bootstrap 3. So, if you have Internet Explorer 8-9, you should use
Bootstrap 3. Bootstrap 3 is the most stable version of Bootstrap, and it is still supported by the
team for critical bug fixes and documentation changes.
Is Bootstrap Best?
Bootstrap is more than efficient to create a responsive and mobile first website but it is not
the best in the industry. There is an alternative of Bootstrap named W3.CSS which is
smaller, faster, and easier to use
Add the HTML 5 doctype: Bootstrap uses HTML elements and CSS properties, so you
have to add the HTML 5 doctype at the beginning of the page with lang a ribute and
correct character set.
Ex:
<!DOCTYPE html>
<html lang="en">
<head><meta http-equiv="Content-Type" content="text/html;
charset=windows-1252">
<title>Any title</title>
</head>
<body>
//write code
</body>
</html>
Mobile-first styles are part of the core framework of Bootstrap.You have to add the
following <meta> tag inside the <head> element for proper rendering and touch zooming:
Note: The "width=device-width" part is used to set the width of the page to follow the
screen-width of the device (vary according to the devices).
The initial-scale=1 part is used to set the initial zoom level when the page is first loaded by
the browser.
Containers: container is used to wrap the site contents. There are two container classes.
● The .container-fluid class provides a full width container, spanning the entire width
of the viewport.
In Bootstrap, a container is used to set the content's margins dealing with the responsive
behaviors of your layout. It contains the row elements and the row elements are the
container of columns (known as grid system).
1. container
2. container-fluid
<html>
<body>
<div class="container">
<div class="row">
<div class="col-md-xx"></div>
...
</div>
<div class="row">
<div class="col-md-xx"></div>
...
</div>
</div>
</body>
</html>
The Bootstrap Grid System allows up to 12 columns across the page. You can use all 12
columns individually or you can group the columns together to create wider columns.
Bootstrap Grid System is responsive and the columns are rearranged automatically
according to the screen size.
Grid Classes:
● xs (for phones)
● sm (for tablets)
● md (for desktops)
You can combine the above classes to create more dynamic and flexible layouts.
● Add the number of columns, you want in the grid (tags with appropriate .col-*-*
classes).
● Note that numbers in .col-*-* should always add up to 12 for each row.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Job</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap
.min.css"/>
</head>
<body>
<div class="container">
<h1>Grid Example</h1>
<div class="row">
<div
class="col-md-3"style="background-color:lavender;">Rahul</div>
<div
We can create different types of Bootstrap tables by using different classes to style them.
The basic Bootstrap table has a light padding and only horizontal dividers. The .table class
is used to add basic styling to a table.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Job</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap
.min.css"/>
</head>
<body>
<div class="container">
<h1>Basic Table Example</h1>
<table class="table">
<tr><th>Id</th><th>Name</th><th>Age</th></tr>
<tr><td>101</td><td>Rahul</td><td>23</td></tr>
<tr><td>102</td><td>Umesh</td><td>22</td></tr>
<tr><td>103</td><td>Max</td><td>29</td></tr>
<tr><td>104</td><td>Ajeet</td><td>21</td></tr>
</table>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min
.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.m
in.js"></script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Job</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap
.min.css"/>
</head>
<body>
<div class="container">
<h1>Striped Table Example</h1>
<table class="table table-striped">
<tr><th>Id</th><th>Name</th><th>Age</th></tr>
<tr><td>101</td><td>Rahul</td><td>23</td></tr>
<tr><td>102</td><td>Umesh</td><td>22</td></tr>
<tr><td>103</td><td>Max</td><td>29</td></tr>
<tr><td>104</td><td>Ajeet</td><td>21</td></tr>
</table>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min
.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.m
in.js"></script>
</body>
</html>
Class Description
.active It is used to apply the hover color to the table row or table cell
Bootstrap Forms
● Always use <form role="form"> (helps improve accessibility for people using screen
readers)
● Wrap labels and form controls in <div class="form-group"> (needed for optimum
spacing)
● Add class .form-control to all textual <input>, <textarea>, and <select> elements
<div class="container">
<h1>Vertical Form Example</h1>
<form style="width:300px">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control"
id="exampleInputEmail1" placeholder="Email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control"
id="exampleInputPassword1" placeholder="Password">
</div>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min
.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.m
in.js"></script>
</body>
</html>
In Bootstrap Inline forms, all elements are inline, left-aligned, and the labels are alongside.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,
initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap
.min.css">
</head>
<body>
<div class="container">
<h2>Inline form Example</h2>
<form class="form-inline" role="form">
<form style="width:300px">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control"
id="exampleInputEmail1" placeholder="Email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control"
id="exampleInputPassword1" placeholder="Password">
</div>
<button type="submit" class="btn btn-default">Login</button>
</form>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min
.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.m
in.js"></script>
</body>
</html>
You have to add some additional rules if you want to create a horizontal form.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,
initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap
.min.css">
</head>
<body>
<div class="container">
<h2>Horizontal form Example</h2>
<form class="form-horizontal" role="form">
<form style="width:300px">
<div class="form-group">
<label class="control-label col-sm-2"
for="email">Email:</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="email"
placeholder="Enter email">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"
for="pwd">Password:</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="pwd"
placeholder="Enter password">
</div>
</div>
<div class="form-group">
</body>
</html>
Bootstrap Images
Bootstrap supports images. There are three classes in Bootstrap that can be used to apply
some simple style to the images.
Classes Uses
The class .img-rounded is used to add rounded corners to an image ( IE8 does not support
rounded corners).
Example:
<!DOCTYPE html>
<html lang="en">
The class .img-circle is used to shape the image to a circle (IE8 does not support rounded
corners).
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap image</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap
.min.css">
</head>
<body>
<div class="container">
<h2>Circle</h2>
<img src="abc.jpg" class="img-circle" alt="abc" width="300"
height="250">
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap image</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap
.min.css">
</head>
<body>
<div class="container">
<h2>Thumbnail</h2>
<img src="abc.jpg" class="img-thumbnail" alt="abc" width="300"
height="250">
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min
.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.m
in.js"></script>
</body>
</html>
The responsive images can adjust themselves automatically to fit the size of screen. You can
create responsive images by adding an .img-responsive class to the <img> tag. The image
will then scale nicely to the parent element.
The .img-responsive class applies display: block; and max-width: 100%; and height: auto;
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,
initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap
.min.css">
</head>
<body>
<div class="container">
<h2>Responsive Image</h2>
<img class="img-responsive" src="abc.jpg" alt="abc" width="460"
height="345">
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min
.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.m
in.js"></script>
</body>
</html>
Typography
● Text alignment
● Text transform
● Font weight and italics
Text Alignment
syntax:
wider.</p>
wider.</p>
Text transform
Syntax:
Output:
lowercase text.
Syntax:
Output:
UPPERCASED TEXT.
Syntax:
Output:
CapiTaliZed Text.
Syntax:
Output:
Bold text.
Syntax:
Output:
Syntax:
Basic Works in the back end which could not Works at the front end and script are
be visible at the client end. visible among the users.
Affect Could effectively customize the web Can reduce the load to the server.
pages and provide dynamic websites.
JAVA JAVASCRIPT
Java applications can run in any virtual JavaScript code runs on browser only as
machine(JVM) or browser. JavaScript is developed for browser
only.
Java program has file extension “.Java” and JavaScript file has file extension “.js”
translates source code into bytecodes which and it is interpreted but not
is executed by JVM(Java Virtual Machine). compiled,every browser has the
Javascript interpreter to execute JS code.
<script type="text/javascript">
Your JavaScript code goes here.
</script>
<script type="text/javascript">
</script>
You would then save the file with a .js extension. For instance, you could save it as write.js.
Once the file is saved, you can call it from the HTML code via the src a ribute of the
opening script tag, as shown below for write.js.
Keywords are reserved words in JavaScript that you cannot use to indicate variable labels
Single-line Comment
Multi-line Comment
<script>
// It is single line comment
document.write("hello javascript");
</script>
<script>
/* It is a multi line comment.
It will not be displayed */
document.write("example of javascript multiline comment");
</script>
JavaScript Variables
A JavaScript variable is simply a name of storage location. There are two types of variables
in JavaScript : local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers).
2. After the first le er we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.
1. var x = 10;
2. var _value="sonoo";
1. var 123=30;
30
A JavaScript local variable is declared inside a block or function. It is accessible within the
function or block only. For example:
<script>
function abc(){
var x=10;//local variable
}
</script>
Or,
<script>
If(10<13){
var y=20;//JavaScript local variable
}
</script>
A JavaScript global variable is accessible from any function. A variable i.e. declared
outside the function or declared with a window object is known as global variable. For
example:
JavaScript provides different data types to hold different types of values. There are two
types of data types in JavaScript.
JavaScript is a dynamic type language, meaning you don't need to specify type of the
variable because it is dynamically used by the JavaScript engine. You need to use var here
to specify the data type. It can hold any type of values such as numbers, strings etc. For
example:
There are five types of primitive data types in JavaScript. They are as follows:
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands. For
example:
1. var sum=10+20;
1. Arithmetic Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
Addition
+
- Subtraction
Multiplication
*
++ Increment
/
Division
Operator Description
== Is equal to
!= Not equal to
Operator Description
|| Logical OR
! Logical Not
typeof Operator
The typeof operator is a unary operator that is placed before its single operand, which can
be of any type. Its value is a string indicating the data type of the operand.
Number "number"
String "string"
Boolean "boolean"
Object "object"
Function Function
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = "String";
output:
Set the variables to different values and different operators and then try...
The process of converting one data type to another data type is called type conversion.
There are two types of type conversion in JavaScript.
● Implicit Conversion
● Explicit Conversion
let result;
result = '3' + 2;
console.log(result) // "32"
result = '3' + true;
console.log(result); // "3true"
result = '3' + undefined;
console.log(result); // "3undefined"
result = '3' + null;
console.log(result); // "3null"
Note: When a number is added to a string, JavaScript converts the number to a string
before concatenation.
let result;
result = '4' - 2;
console.log(result); // 2
result = '4' * 2;
console.log(result); // 8
result = '4' / 2;
console.log(result); // 2
result = Number('324e-1')
console.log(result); // 32.4
// boolean to number
result = Number(true);
console.log(result); // 1
result = Number(false);
console.log(result); // 0
In JavaScript, empty strings and null values return 0. For example,
let result;
result = Number(null);
console.log(result); // 0
result = Number(undefined);
console.log(result); // NaN
result = Number(NaN);
console.log(result); // NaN
Note: You can also generate numbers from strings using parseInt(),
parseFloat(), unary operator + and Math.floor(). For example,
result = parseFloat('20.01');
console.log(result); // 20.01
result = +'20.01';
console.log(result); // 20.01
result = Math.floor('20.01');
console.log(result); // 20
Inline JavaScript
In the following example, the HTML document contains a form, and underneath it follows
the <script> element with the JavaScript code. The function in the code is called directly
from inside the HTML form, using an event handler.
<!DOCTYPE html>
<body>
<form onsubmit="inline(); return false">
Password:
External JavaScript
This is the HTML document that references the external JavaScript file:
<!DOCTYPE html>
<body>
<form>
Password:
<input type = "password">
JavaScript Variable
A JavaScript variable is simply a name of storage location. There are two types of variables
in JavaScript : local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers).
1. Name must start with a le er (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
2. After the first le er we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.
1. var x = 10;
2. var _value="sonoo";
1. var 123=30;
2. var *aa=320;
<script>
var x = 10;
30
<script>
function abc(){
var x=10;//local variable
}
</script>
Or,
<script>
If(10<13){
var y=20;//JavaScript local variable
}
</script>
outside the function or declared with a window object is known as global variable. For
<script>
var data=200;//global variable
function
a(){ document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>
Output:
200 200
To declare JavaScript global variables inside a function, you need to use a window object.
For example:
window.value=90;
Now it can be declared inside any function and can be accessed from any function. For
example:
function m(){
window.value=100;//declaring global variable by window object
}
function n(){
alert(window.value);//accessing global variable from other function
}
JavaScript Array
1. By array literal
1. var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by , (comma).
Let's see the simple example of creating and using arrays in JavaScript.
<script>
var emp=["Sonoo","Vimal","Ratan"];
for
(i=0;i<emp.length;i++){ document.w
rite(emp[i] + "<br/>");
}
</script>
Sonoo
Ratan
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
Arun
Varun
John
<script>
var emp=new Array("Jai","Vijay","Smith");
for
(i=0;i<emp.length;i++){ document.write(em
p[i] + "<br>");
}
</script>
Jai
Vijay
Smith
Methods Description
concat() It returns a new array object that contains two or more merged arrays.
copywithin() It copies the part of the given array with its own elements and returns
the modified array.
entries() It creates an iterator object and a loop that iterates over each key/value
pair.
every() It determines whether all the elements of an array are satisfying the
flatMap() It maps all array elements via mapping function, then fla ens the result
into a new array.
from() It creates a new array carrying the exact copy of another array element.
filter() It returns the new array containing the elements that pass the provided
function conditions.
find() It returns the value of the first element in the given array that satisfies
the specified condition.
findIndex() It returns the index value of the first element in the given array that
satisfies the specified condition.
forEach() It invokes the provided function once for each element of an array.
includes() It checks whether the given array contains the specified element.
indexOf() It searches the specified element in the given array and returns the
index of the first match.
keys() It creates an iterator object that contains only the keys of the array, then
loops through these keys.
lastIndexOf() It searches the specified element in the given array and returns the
index of the last match.
map() It calls the specified function for every array element and returns the
reduce(functio It executes a provided function for each value from left to right and
n, initial) reduces the array to a single value.
reduceRight() It executes a provided function for each value from right to left and
reduces the array to a single value.
some() It determines if any element of the array passes the test of the
implemented function.
slice() It returns a new array containing the copy of the part of the given
array.
toString() It converts the elements of a specified array into string form, without
affecting the original array.
unshift() It adds one or more elements in the beginning of the given array.
values() It creates a new iterator object carrying values for each index in the
array.
2. Less coding: It makes our program compact. We don’t need to write many lines of
//code to be executed
function msg(){
</script>
one argument.
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
<script>
function getInfo(){
return "hello Students! How r u?";
}
</script>
executes the code globally. However, if we call the constructor directly, a function is
Syntax
Parameter
Method Description
apply() It is used to call a function containing this value and a single array of
call() It is used to call a function containing this value and an argument list.
Example 1
<script>
var add=new Function("num1","num2","return num1+num2");
document.writeln(add(2,5));
</script>
Output:
Example 2
<script>
var pow=new Function("num1","num2","return Math.pow(num1,num2)");
document.writeln(pow(2,3));
</script>
Output:
given set of paths. In such cases, you need to use conditional statements that allow your
JavaScript supports conditional statements which are used to perform different actions
FlowChart of if-else
The following flow chart shows how the if-else statement works.
● if statement
● if...else statement
if statement
The if statement is the fundamental control statement that allows JavaScript to make
Syntax
if (expression) {
Statement(s) to be executed if 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
<html>
<body>
<script type = "text/javascript">
<!--
var age = 20;
Output
if...else statement
The 'if...else' statement is the next form of control statement that allows JavaScript to
Syntax
if (expression) {
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}
Here the 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
Example
Try the following code to learn how to implement an if-else statement in JavaScript.
<html>
Output
The if...else if... statement is an advanced form of if…else that allows JavaScript to make
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
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
Try the following code to learn how to implement an if-else-if statement in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var book = "maths";
if( book == "history" ) {
document.write("<b>History Book</b>");
} else if( book == "maths" ) {
document.write("<b>Maths Book</b>");
} else if( book == "economics" ) {
document.write("<b>Economics Book</b>");
} else {
document.write("<b>Unknown Book</b>");
}
//-->
</script>
<p>Set the variable to a different value and then try...</p>
</body>
<html>
Output
Maths Book
important parts −
● The loop initialization where we initialize our counter to a starting value. The
● The test statement which will test if a given condition is true or not. If the
condition is true, then the code given inside the loop will be executed, otherwise
● The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by semicolons.
Flow Chart
Example
Try the following example to learn how a for loop works in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br />");
Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Set the variable to a different value and then try…
The for...in loop is used to loop through an object's properties. As we have not
discussed Objects yet, you may not feel comfortable with this loop. But once you
understand how objects behave in JavaScript, you will find this loop very useful.
Syntax
loop continues till all the properties of the object are exhausted.
Example
Try the following example to implement a ‘for-in’ loop. It prints the web browser’s
Navigator object.
<html>
<body>
<script type = "text/javascript">
<!--
var aProperty;
document.write("Navigator Object Properties<br /> ");
for (aProperty in navigator)
{ document.write(aProperty);
document.write("<br />");
}
document.write ("Exiting from the loop!");
//-->
</script>
<p>Set the variable to a different object and then try...</p>
</body>
</html>
Output
situation when you need to come out of a loop without reaching its bo om. There may
also be a situation when you want to skip a part of your code block and start the next
To handle all such situations, JavaScript provides break and continue statements. These
statements are used to immediately come out of any loop or to start the next iteration of
The break statement, which was briefly introduced with the switch statement, is used to
Flow Chart
Example
The following example illustrates the use of a break statement with a while loop.
Notice how the loop breaks out early once x reaches 5 and reaches to document.write (..)
<html>
<body>
Output
2
3
4
5
Exiting the loop!
Set the variable to a different value and then try...
The continue statement tells the interpreter to immediately start the next iteration of the
loop and skip the remaining code block. When a continue statement is encountered, the
program flow moves to the loop check expression immediately and if the condition
loop.
Example
This example illustrates the use of a continue statement with a while loop. Notice how
the continue statement is used to skip printing when the index held in variable x
reaches 5 −
<html>
<body>
<script type = "text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
if (x == 5) {
continue; // skip rest of the loop body
}
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
<p>Set the variable to a different value and then try...</p>
</body>
</html>
Output
Entering the loop
2
3
4
6
7
8
JavaScript has three kinds of popup boxes: Alert box, Confirm box, and Prompt box.
Alert Box
An alert box is often used if you want to make sure information comes through to the
user.
When an alert box pops up, the user will have to click "OK" to proceed.
Syntax
window.alert("sometext");
Example
Confirm Box
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to
proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns
false.
Syntax
window.confirm("sometext");
Example
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
Prompt Box
A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box
Syntax
window.prompt("sometext","defaultText");
Example
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method). For
JavaScript is template based not class based. Here, we don't create classes to get the
1. By object literal
1. object={property1:value1,property2:value2.....propertyN:valueN}
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
<script>
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
<script>
function emp(id,name,salary){
this.id=id; this.name=name;
this.salary=salary;
this.changeSalary=changeSalary;
function changeSalary(otherSalary){
this.salary=otherSalary;
}
}
e=new emp(103,"Sonoo Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
e.changeSalary(45000);
document.write("<br>"+e.id+" "+e.name+" "+e.salary);
</script>
Model (DOM). In fact, the web browser creates a DOM of the webpage when the page is
a ributes, change the exis+ting elements and a ributes and even remove existing
elements and a ributes. JavaScript can also react to existing events and create new
<html>
<head>
Welcome
Technology
getElementsByTagName Example
getElementsByTagName: To access elements and a ributes using tag name. This method
will return an array of all the items with the same tag name.
<html>
<head>
<title>DOM!!!</title>
</head>
<body>
<h1>Welcome</h1>
<p>This is the welcome message.</p>
<h2>Technology</h2>
<p id="second">This is the technology section.</p>
<script type="text/javascript">
var paragraphs = document.getElementsByTagName("p");
alert("Content in the second paragraph is " +
Welcome
Technology
document.getElementById(id).onclick=function()
{
lines of code to be executed
}
OR
document.getElementById(id).addEventListener("click", functionname)
<html>
<head>
<title>DOM!!!</title>
</head>
<body>
<input type="button" id="btnClick" value="Click Me!!" />
<script type="text/javascript">
document.getElementById("btnClick").addEventListener("click",
clicked);
function clicked()
Functions or Methods?
you can also call these functions methods, since they are methods of the global object
where they run. In a web browser, the global object is the browser window. Then
Example
Syntax
decodeURI(uri)
Parameter Values
Parameter Description
Technical Details
Example
Encoded URI:
h ps%3A%2F%2Fw3Google.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car
%3Dsaab
Syntax
decodeURIComponent(uri)
Parameter Values
Parameter Description
Technical Details
Example
Encode a URI:
my%20test.asp?name=st%C3%A5le&car=saab
Syntax
encodeURI(uri)
Parameter Values
Parameter Description
Technical Details
Encode a URI:
characters: , / ? : @ & = + $ #
Syntax
encodeURIComponent(uri)
Parameter Values
Parameter Description
Technical Details
Prepared By: Prof. Neil Saxena Page218
218218
Return Value: A String, representing the encoded URI
Example
var x = 10;
var y = 20;
var a = eval("x * y") + "<br>";
var b = eval("2 + 2") + "<br>";
var c = eval("x + 17") + "<br>";
var res = a + b + c;
200
27
If the argument is an expression, eval() evaluates the expression. If the argument is one
Syntax
eval(string)
Parameter Description
Example
<!DOCTYPE html>
<html>
<body>
<p>Click the button to parse different strings.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var a = parseInt("10") + "<br>";
var b = parseInt("10.00") + "<br>";
var c = parseInt("10.33") + "<br>";
var d = parseInt("34 45 66") + "<br>";
var e = parseInt(" 60 ") + "<br>";
var f = parseInt("40 years") + "<br>";
var g = parseInt("He was 40") + "<br>";
</body>
</html>
Try it
10
10
10
34
60
40
NaN
10
10
8
16
16
The radix parameter is used to specify which numeral system to be used, for example, a
radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a
● If the string begins with "0", the radix is 8 (octal). This feature is deprecated
Note: If the first character cannot be converted to a number, parseInt() returns NaN.
ECMAScript, (older than ECMAScript 5, uses the octal radix (8) as default when the
string begins with "0". As of ECMAScript 5, the default is the decimal radix (10).
Syntax
parseInt(string, radix)
Parameter Values
Parameter Description
JavaScript provides a facility to validate the form on the client-side so data processing
will be faster than server-side validation. Most of the web developers prefer JavaScript
form validation.
Through JavaScript, we can validate name, password, email, date, mobile numbers and
more fields.
Here, we are validating the form on form submit. The user will not be forwarded to the
<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null ||
name==""){ alert("Name can't
be blank"); return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="abc.jsp" onsubmit="return
validateform()" >
Name: <input type="text" name="name"><br/>
if(firstpassword==secondpassword){
return true;
}
else{
alert("password must be same!");
return false;
}
}
</script>
<script>
function validate(){
var num=document.myform.num.value;
if (isNaN(num)){
document.getElementById("numloc").innerHTML="Enter Numeric value
only";
return false;
<script>
function validate(){
var name=document.f1.name.value;
var password=document.f1.password.value;
var status=false;
if(name.length<1){
document.getElementById("nameloc").innerHTML=
" <img src='unchecked.gif'/> Please enter your name";
status=false;
}else{ document.getElementById("nameloc").innerHTML
=" <img src='checked.gif'/>";
status=true;
}
if(password.length<6){ document.getElementById("p
asswordloc").innerHTML=
" <img src='unchecked.gif'/> Password must be at least 6 char
long";
There are many criteria that need to be follow to validate the email id such as:
<script>
function validateemail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
RegExp Object
functions on text.
Syntax
/pa ern/modifiers;
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
function myFunction()
{ var str = "Visit
AIT"; var patt =
/AIT/i;
var result = str.match(patt);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
Try it
AIT
Example explained:
Modifiers
Modifier Description
Brackets
Expression Description
[^0-9] Find any character NOT between the brackets (any non-digit)
Metacharacters
\d Find a digit
Quantifiers
Property Description
constructor Returns the function that created the RegExp object's prototype
<!DOCTYPE html>
<html>
<body>
Try it
1,2,3,4
JavaScript Events
The change in the state of an object is known as an Event. In html, there are various
events which represent that some activity is performed by the user or by the browser.
execution. This process of reacting over the events is called Event Handling. Thus, js
For example, when a user clicks over the browser, add js code, which will execute the
Mouse events:
mouseover onmouseover When the cursor of the mouse comes over the
element
Keyboard events:
Form events:
Window/Document events
load onload When the browser finishes the loading of the page
unload onunload When the visitor leaves the current webpage, the
browser unloads it
resize onresize When the visitor resizes the window of the browser
Click Event
<html>
<head> Javascript Events </head>
<body>
<script language="Javascript" type="text/Javascript">
MouseOver Event
<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function mouseoverevent()
{
alert("This is JavaTpoint");
}
//-->
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>
Focus Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
<!--
function focusevent()
{
document.getElementById("input1").style.background=" aqua";
}
Keydown Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
//-->
</script>
</body>
</html>
Load event
<html>
<head>Javascript Events</head>
</br>
<body onload="window.alert('Page successfully loaded');">
<script>
<!--
document.write("The page is loaded successfully");
//-->
</script>
</body>
</html>
JavaScript | Callbacks
Callbacks are a great way to handle something after something else has been completed.
after the return of some other function, then callbacks can be used.
JavaScript functions have the type of Objects. So, much like any other objects (String,
Arrays etc.), They can be passed as an argument to any other function while calling.
Code #1:
<script>
</script>
Output:
Here are the two functions – add(a, b, callback) and disp(). Here add() is called with the
disp() function i.e. passed in as the third argument to the add function along with two
numbers.
As a result, the add() is invoked with 1, 2 and the disp() which is the callback. The add()
prints the addition of the two numbers and as soon as that is done, the callback function
is fired!
Code #2:
An alternate way to implement above code is shown below with anonymous functions
being passed.
<script>
</script>
Output:
Callbacks are primarily used while handling asynchronous operations like – making an
API request to Google Maps, fetching/writing some data from/into a file, registering
event listeners and related stuff. All the operations mentioned use callbacks. This way
once the data/error from the asynchronous operation is returned, the callbacks are used
The JavaScript Math object allows you to perform mathematical tasks on numbers.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.PI</h2>
<p>Math.PI returns the ratio of a circle's circumference to its
diameter:</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.PI;
</script>
</body>
</html>
JavaScript Math.PI
3.141592653589793
All methods and properties can be used without creating a Math object first.
Example
Math Methods
Number to Integer
Math.round()
Example
Math.round(4.9); // returns 5
Math.round(4.7); // returns 5
Math.round(4.4); // returns 4
Math.round(4.2); // returns 4
Math.round(-4.2); // returns -4
Math.ceil()
Example
Math.ceil(4.9); // returns 5
Math.ceil(4.7); // returns 5
Math.ceil(4.4); // returns 5
Math.ceil(4.2); // returns 5
Math.ceil(-4.2); // returns -4
Math.floor()
Example
Math.trunc()
Math.sign()
Math.pow()
Math.sqrt()
Math.abs()
Math.sin()
Math.sin(x) returns the sine (a value between -1 and 1) of the angle x (given in radians).
If you want to use degrees instead of radians, you have to convert degrees to radians:
Math.cos()
Math.cos(x) returns the cosine (a value between -1 and 1) of the angle x (given in
radians).
If you want to use degrees instead of radians, you have to convert degrees to radians:
Math.min() and Math.max() can be used to find the lowest or highest value in a list of
arguments:
Math.random()
The natural logarithm returns the time needed to reach a certain level of growth.
Method Description
These methods can be used for ge ing information from a date object:
Method Description
The getTime() method returns the number of milliseconds since January 1, 1970:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript getTime()</h2>0
<p>The internal clock in JavaScript counts from midnight January 1,
1970.</p>
<p>The getTime() function returns the number of milliseconds since
then:</p>
<p id="demo"></p>
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getTime();
</script>
</body>
</html>
JavaScript getTime()
UTC date methods are used for working with UTC dates (Universal Time Zone dates):
Method Description
JavaScript Booleans
Boolean Values
Very often, in programming, you will need a data type that can only have one of two
values, like
● YES / NO
● TRUE / FALSE
For this, JavaScript has a Boolean data type. It can only take the values true or false.
You can use the Boolean() function to find out if an expression (or a variable) is true:
<!DOCTYPE html>
<html>
<body>
<p>Display the value of Boolean(10 > 9):</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = Boolean(10 > 9);
}
</script>
</body>
</html>
Try it
true
var x = false;
But booleans can also be defined as objects with the keyword new:
<!DOCTYPE html>
<html>
<body>
<p>Never create booleans as objects.</p>
<p>Booleans and objects cannot be safely compared.</p>
<p id="demo"></p>
<script>
var x = false; // x is a boolean
var y = new Boolean(false); // y is an object
document.getElementById("demo").innerHTML = typeof x + "<br>" +
typeof y;
</script>
</body>
</html>
object
What is JSON
JSON is an open standard for exchanging data on the web. It supports data structures
like objects and arrays. So it is easy to write and read data from JSON.
What is JSON
● JSON stands for JavaScript Object Notation.
● JSON is an open standard data-interchange format.
● JSON is lightweight and self describing.
● JSON originated from JavaScript.
● JSON is easy to read and write.
● JSON is language independent.
● JSON supports data structures such as arrays and objects.
Features of JSON
1. Simplicity
2. Openness
3. Self Describing
4. Internationalization
5. Extensibility
6. Interoperability
JSON Example
JSON examples can be created by object and array. Each object can have different data
such as text, number, boolean etc. Let's see different JSON examples using objects and
A JSON object contains data in the form of a key/value pair. The keys are strings and the
values are the JSON types. Keys and values are separated by colon. Each entry
{
"employee": {
"name": "sonoo",
"salary": 56000,
"married": true
}
}
The [ (square bracket) represents the JSON array. A JSON array can have values and
objects.
[
{"name":"Ram", "email":"[email protected]"},
{"name":"Bob", "email":"[email protected]"}
]
JSON Example 1
<employees>
<employee>
<name>Shyam</name>
<email>[email protected]</email>
</employee>
<employee>
<name>Bob</name>
<email>[email protected]</email>
</employee>
<employee>
<name>Jai</name>
<email>[email protected]</email>
</employee>
</employees>
JSON Example 2
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Save", "onclick": "SaveDoc()"}
]
}
}}
JSON Object
JSON object holds key/value pair. Each key is represented as a string in JSON and value
can be of any type. The keys and values are separated by colon. Each key/value pair is
separated by comma.
{
"employee": {
"name": "sonoo",
"salary": 56000,
"married": true
}
}
In the above example, an employee is an object in which "name", "salary" and "married"
are the key. In this example, there are string, number and boolean values for the keys.
{
"name": "sonoo",
"email": "[email protected]"
}
digits (0-9), fractions (.33, .532 etc) and exponents (e, e+, e-,E, E+, E-).
{
"integer": 34,
"fraction": .2145,
"exponent": 6.61789e+0
}
{
"first": true,
"second": false
}
A JSON object can have another object also. Let's see a simple example of a JSON object
having another object.
{
"firstName": "Sonoo",
"lastName": "Jaiswal",
"age": 27,
"address" : {
"streetAddress": "Plot-6, Mohan Nagar",
"city": "Ghaziabad",
"state": "UP",
"postalCode": "201007"
}
The JSON array represents an ordered list of values. JSON array can store multiple
values. It can store string, number, boolean or object in JSON array.
{"employees":[
{"name":"Ram", "email":"[email protected]", "age":23},
{"name":"Shyam", "email":"[email protected]", "age":28},
{"name":"John", "email":"[email protected]", "age":33},
{"name":"Bob", "email":"[email protected]", "age":41}
]}
A common use of JSON is to read data from a web server, and display the data in a web
page.
JSON Example
This example reads a menu from myTutorials.js, and displays the menu in a web page:
<!DOCTYPE html>
<html>
<body>
<div id="id01"></div>
<script>
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i<arr.length; i++) {
out += '<a href="' + arr[i].url + '">' +
arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
<script src="myTutorials.js"></script>
JSON H p Request
A common use of JSON is to read data from a web server, and display the data in a web
page.
JSON Example
This example reads a menu from myTutorials.txt, and displays the menu in a web page:
JSON Example
<!DOCTYPE html>
<html>
<body>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest(); var
url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200)
{ var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<a href="' + arr[i].url + '">' +
arr[i].display + '</a><br>';
}
What is PHP
PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995. PHP
7.4.0 is the latest version of PHP, which was released on 28 November. Some important
points that need to be noticed about PHP are as followed:
● PHP is faster than other scripting languages, for example, ASP and JSP.
● PHP supports several protocols such as HTTP, POP3, SNMP, LDAP, IMAP, and
many more.
● Using PHP language, you can control the user to access some pages of your
website.
● As PHP is easy to install and set up, this is the main reason why PHP is the best
language to learn.
● PHP can handle the forms, such as - collect the data from users using forms, save
it into the database, and return useful information to the user. For example -
Registration form.
PHP Features
PHP is a very popular language because of its simplicity and open source. There are
some important features of PHP given below:
PHP script is executed much faster than those scripts which are wri en in other
languages such as JSP and ASP. PHP uses its own memory, so the server workload and
loading time is automatically reduced, which results in faster processing speed and
be er performance.
Open Source:
PHP source code and software are freely available on the web. You can develop all the
versions of PHP according to your requirement without paying any cost. All its
components are free to download and use.
Embedded:
PHP code can be easily embedded within HTML tags and script.
Platform Independent:
PHP is available for WINDOWS, MAC, LINUX & UNIX operating systems. A PHP
application developed in one OS can be easily executed in other OS also.
Database Support:
PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.
Error Reporting -
PHP has predefined error reporting constants to generate an error notice or warning at
runtime. E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.
PHP allows us to use a variable without declaring its datatype. It will be taken
automatically at the time of execution based on the type of data it contains on its value.
PHP is compatible with almost all local servers used today like Apache, Netscape,
Microsoft IIS, etc.
Security:
Control:
Different programming languages require long scripts or codes, whereas PHP can do
the same work in a few lines of code. It has maximum control over the websites like you
can make changes easily whenever you want.
PHP Echo
PHP echo is a language construct, not a function. Therefore, you don't need to use
parentheses with it. But if you want to use more than one parameter, it is required to
use parenthesis.
PHP echo statements can be used to print the string, multi-line strings, escaping
characters, variable, array, etc. Some important points that you must know about the
echo statement are:
File: echo1.php
<?php
echo "Hello by PHP echo";
?>
File: echo2.php
<?php
echo "Hello by PHP echo
this is multi line
text printed by
PHP echo statement
";
?>
Output:
Hello by PHP echo this is multi line text printed by PHP echo statement
PHP Syntax
A PHP script is executed on the server, and the plain HTML result is sent back to the
browser.
<?php
// PHP code goes here
?>
A PHP file normally contains HTML tags, and some PHP scripting code.
Example
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
Hello World!
In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined
functions are not case-sensitive.
In the example below, all three echo statements below are equal and legal:
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
Hello World!
Hello World!
Hello World!
PHP Comments
Comments in PHP
A comment in PHP code is a line that is not executed as a part of the program. Its only
purpose is to be read by someone who is looking at the code.
Example
<!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment
# This is also a single-line comment
?>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>
Example
Using comments to leave out parts of the code:
<!DOCTYPE html>
<html>
<body>
<?php
// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>
</body>
</html>
The main way to store information in the middle of a PHP program is by using a
variable.
Here are the most important things to know about variables in PHP.
● All variables in PHP are denoted with a leading dollar sign ($).
● The value of a variable is the value of its most recent assignment.
● Variables are assigned with the = operator, with the variable on the left-hand side
and the expression to be evaluated on the right.
● Variables can, but do not need, to be declared before assignment.
● Variables in PHP do not have intrinsic types - a variable does not know in
advance whether it will be used to store a number or a string of characters.
● Variables used before they are assigned have default values.
PHP has a total of eight data types which we use to construct our variables −
The first five are simple types, and the next two (arrays and objects) are compound - the
compound types can package up other arbitrary values of arbitrary type, whereas the
simple types cannot.
Integers
They are whole numbers, without a decimal point, like 4195. They are the simplest
type .they correspond to simple whole numbers, both positive and negative. Integers
can be assigned to variables, or they can be used in expressions, like so −
$int_var = 12345;
$another_int = -12345 + 12345;
Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16) format.
Decimal format is the default, octal integers are specified with a leading 0, and
hexadecimals have a leading 0x.
For most common platforms, the largest integer is (2**31 . 1) (or 2,147,483,647), and the
smallest (most negative) integer is . (2**31 . 1) (or .2,147,483,647).
Doubles
Variable Scope
Scope can be defined as the range of availability a variable has to the program in which
it is declared. PHP variables can be one of four scope types −
● Local variables
● Function parameters
● Global variables
● Static variables
Local Variables
A variable declared in a function is considered local; that is, it can be referenced solely
in that function. Any assignment outside of that function will be considered to be an
entirely different variable from the one contained in the function −
<?php
$x = 4;
function assignx () {
$x = 0;
print "\$x inside function is $x. <br />";
}
assignx();
print "\$x outside of function is $x. <br />";
?>
$x inside function is 0.
$x outside of function is 4.
But in short a function is a small unit of program which can take some input in the
form of parameters and does some processing and may return some value.
Function Parameters
Function parameters are declared after the function name and inside parentheses. They
are declared much like a typical variable would be −
<?php
// multiply a value by 10 and return it to the caller
function multiply ($value) {
$value = $value * 10;
return $value;
}
$retval = multiply (10);
Print "Return value is $retval\n";
?>
This will produce the following result −
Global Variables
In contrast to local variables, a global variable can be accessed in any part of the
program. However, in order to be modified, a global variable must be explicitly
declared to be global in the function in which it is to be modified. This is accomplished,
conveniently enough, by placing the keyword GLOBAL in front of the variable that
should be recognized as global. Placing this keyword in front of an already existing
variable tells PHP to use the variable having that name. Consider an example −
Somevar is 16
Static Variables
The final type of variable scoping that I discuss is known as static. In contrast to the
variables declared as function parameters, which are destroyed on the function's exit, a
static variable will not lose its value when the function exits and will still hold that
value should the function be called again.
You can declare a variable to be static simply by placing the keyword STATIC in front
of the variable name.
<?php
function keep_track()
{ STATIC $count = 0;
$count++;
print $count;
print "<br />";
}
keep_track();
keep_track();
keep_track();
?>
PHP | Loops
Like any other language, loop in PHP is used to execute a statement or a block of
statements, multiple times until and unless a specific condition is met. This helps the
user to save both time and effort of writing the same code multiple times.
1. for loop
2. while loop
3. do-while loop
4. foreach loop
Let us now learn about each of the above mentioned loops in details:
1. for loop: This type of loop is used when the user knows in advance, how
many times the block needs to execute. That is, the number of iterations is
loops. There are three main parameters to the code, namely the initialization,
Syntax:
condition evaluates to true then we will execute the body of the loop and go
to update expression otherwise we will exit from the for loop. For example:
+= 2;
Example:
<?php
// code to illustrate for loop
for ($num = 1; $num <= 10; $num +=
2) {
echo "$num \n";
}
?>
Output:
1
3
5
7
9
Flow Diagram:
Example:
Output:
4
6
8
10
12
Flowchart:
do {
//code is executed
} while (if condition is true);
Example:
Output:
4
6
8
10
12
This code would show the difference between while and do…while loop.
<?php
// PHP code to illustrate the difference of two
loops
$num = 2;
// In case of while
while ($num != 2) {
echo "In case of while the code is skipped";
echo $num, "\n";
}
// In case of do...while
do {
$num++;
echo "The do...while code is executed at least
once ";
} while($num == 2);
?>
Output:
Flowchart:
Output:
10
20
30
40
50
60
Ram
Laxman
Sita
● if statement
● if…else statement
● if…elseif…else statement
● switch statement
if Statement: This statement allows us to set a condition. On being TRUE, the following
block of code enclosed within the if clause will be executed.
Syntax :
if (condition){
// if TRUE then execute this code
}
1.
Example:
<?php
$x = 12;
if ($x > 0) {
echo "The number is
positive";
}
?>
Output:
Flowchart:
if (condition) {
// if TRUE then execute this code
}
else{
// if FALSE then execute this code
}
Example:
<?php
$x = -12;
if ($x > 0) {
echo "The number is
positive";
}
else{
echo "The number is
negative";
}
?>
Output:
Flowchart:
Example:
<?php
$x = "August";
if ($x == "January") {
echo "Happy Republic Day";
}
else{
echo "Nothing to show";
}
?>
Output:
Flowchart:
2. The default statement contains the code that would execute if none of the
cases match.
Syntax:
switch(n) {
Example:
switch($n) {
case "January":
echo "Its January";
break;
case "February":
echo "Its
February";
break;
case "March":
echo "Its March";
break;
case "April":
echo "Its April";
break;
case "May":
echo "Its May";
break;
case "June":
echo "Its June";
break;
case "July":
echo "Its July";
break;
case "August":
echo "Its August";
break;
case "September":
echo "Its
September";
break;
case "October":
echo "Its October";
break;
case "November":
echo "Its
November";
break;
case "December":
echo "Its
December";
break;
Output:
Its February
Flowchart:
Syntax:
Example:
<?php
$x = -12;
if ($x > 0) {
echo "The number is positive \n";
}
else {
echo "The number is negative \n";
}
// This whole lot can be written in a
// single line using ternary operator
echo ($x > 0) ? 'The number is
positive' :
'The number is
negative';
?>
Output:
PHP | Arrays
Arrays in PHP are a type of data structure that allows us to store multiple elements of
similar data type under a single variable thereby saving us the effort of creating a
different variable for every data. The arrays are helpful to create a list of elements of
similar types, which can be accessed using their index or key. Suppose we want to store
five names and print them accordingly. This can be easily done by the use of five
different string variables. But if instead of five, the number rises to a hundred, then it
would be really difficult for the user or developer to create so many different variables.
Here array comes into play and helps us to store every element within a single variable
● Indexed or Numeric Arrays: An array with a numeric index where values are
stored linearly.
These types of arrays can be used to store any type of elements, but an index is always a
number. By default, the index starts at zero. These arrays can be created in two different
ways as shown in the following example:
Output:
Example:
Output:
Associative Arrays
Example:
<?php
// One way to create an associative array
$name_one = array("Zack"=>"Zara",
"Anthony"=>"Any",
"Ram"=>"Rani",
"Salim"=>"Sara",
"Raghav"=>"Ravina");
// Second way to create an associative array
$name_two["zack"] = "zara";
$name_two["anthony"] = "any";
$name_two["ram"] = "rani";
$name_two["salim"] = "sara";
$name_two["raghav"] = "ravina";
// Accessing the elements directly
echo "Accessing the elements directly:\n";
echo $name_two["zack"], "\n";
echo $name_two["salim"], "\n";
echo $name_two["anthony"], "\n";
echo $name_one["Ram"], "\n";
echo $name_one["Raghav"], "\n";
?>
Output:
Example:
Output:
Multi-dimensional arrays are such arrays that store another array at each index instead
of a single element. In other words, we can define multi-dimensional arrays as an array
of arrays. As the name suggests, every element in this array can be an array and they
can also hold other sub-arrays within. Arrays or sub-arrays in multidimensional arrays
can be accessed using multiple dimensions.
Example:
<?php
// Defining a multidimensional array
$favorites = array(
array(
"name" => "Dave Punk",
"mob" => "5689741523",
"email" => "[email protected]",
),
array(
"name" => "Monty Smith",
"mob" => "2584369721",
"email" => "[email protected]",
),
array(
"name" => "John Flinch",
"mob" => "9875147536",
"email" => "[email protected]",
)
);
// Accessing elements
echo "Dave Punk email-id is: " . $favorites[0]["email"],
"\n";
echo "John Flinch mobile number is: " .
$favorites[2]["mob"];
?>
Output:
Example:
Output:
Dave Punk
mob : 2584369721
email : [email protected]
John Flinch
mob : 9875147536
email : johnfl[email protected]
The array() function is an inbuilt function in PHP which is used to create an array.
There are three types of array in PHP:
Prepared By: Prof. Neil Saxena Page 297
297297
● Indexed array: The array which contains numeric index.
Syntax:
Syntax:
<?php
// Create an array
$sub = array("DBMS", "Algorithm", "C++",
"JAVA");
// Find length of array
$len = count( $sub );
// Loop to print array elements
for( $i = 0; $i < $len; $i++) {
echo $sub[$i] . "\n";
}
?>
Output:
<?php
// Declare an associative array
$detail = array( "Name"=>"AIT",
"Address"=>"AHMEDABAD",
"Type"=>"Education
Institute");
// Display the output
var_dump ($detail);
?>
Output: array(3)
{ ["Name"]=>
string(3) "AIT"
["Address"]=>
string(9) "AHMEDABAD"
["Type"]=>
string(19) "Education Institute"
}
Output:
array(2)
{ [0]=>
array(4) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
} [1]=>
array(4)
{ [0]=>
int(5)
[1]=>
int(6)
[2]=>
int(7)
[3]=>
int(8)
}
}
PHP function is a piece of code that can be reused many times. It can take input as an
argument list and return value. There are thousands of built-in functions in PHP.
In PHP, we can define Conditional function, Function within Function and Recursive
function also
Code Reusability: PHP functions are defined only once and can be invoked many
times, like in other programming languages.
Less Code: It saves a lot of code because you don't need to write the logic many times.
By the use of function, you can write the logic only once and reuse it.
We can declare and call user-defined functions easily. Let's see the syntax to declare
user-defined functions.
Syntax
function functionname(){
//code to be executed
Note: Function name must be started with le er and underscore only like other labels
in PHP. It can't be started with numbers or special symbols.
<?php
function sayHello(){
echo "Hello PHP Function";
}
sayHello();//calling function
?>
Output:
We can pass the information in the PHP function through arguments which are
separated by comma.
PHP supports Call by Value (default), Call by Reference, Default argument values
and Variable-length argument list.
Let's see the example to pass a single argument in the PHP function.
File: functionarg.php
<?php
function sayHello($name){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello("Vimal");
sayHello("John");
?>
Output:
Let's see the example to pass two arguments in the PHP function.
File: functionarg2.php
<?php
function sayHello($name,$age){
echo "Hello $name, you are $age years old<br/>";
}
sayHello("Sonoo",27);
sayHello("Vimal",29);
sayHello("John",23);
?>
Output:
Value passed to the function doesn't modify the actual value by default (call by value).
But we can do so by passing value as a reference.
By default, value passed to the function is called by value. To pass value as a reference,
you need to use ampersand (&) symbol before the argument name.
File: functionref.php
<?php
Output:
We can specify a default argument value in function. While calling a PHP function if
you don't specify any argument, it will take the default argument. Let's see a simple
example of using default argument values in PHP function.
File: functiondefaultarg.php
<?php
function sayHello($name="Sonoo"){
echo "Hello $name<br/>";
} sayHello("Rajesh");
sayHello();//passing no value
sayHello("John");
?>
Output:
Hello Rajesh
Hello Sonoo
File: functiondefaultarg.php
<?php
function cube($n){
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>
Output:
Cube of 3 is: 27
PHP Parameterized Function
PHP Parameterized functions are the functions with parameters. You can pass any
number of parameters inside a function. These passed parameters act as variables inside
your function.
They are specified inside the parentheses, after the function name.
The output depends upon the dynamic values passed as the parameters into the
function.
In this example, we have passed two parameters $x and $y inside two functions add()
and sub().
<!DOCTYPE html>
Output:
PHP allows you to call functions by value and reference both. In case of PHP call by
value, actual value is not modified if it is modified inside the function.
In this example, variable $str is passed to the adder function where it is concatenated
with the 'Call By Value' string. But, printing $str variable results 'Hello' only. It is
because changes are done in the local variable $str2 only. It doesn't reflect the $str
variable.
<?php
function adder($str2)
{
$str2 .= 'Call By Value';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Output:
Hello
PHP Call By Reference
In case of PHP call by reference, actual value is modified if it is modified inside the
function. In such a case, you need to use the & (ampersand) symbol with formal
arguments. The & represents reference of the variable.
Example 1
In this example, variable $str is passed to the adder function where it is concatenated
with the 'Call By Reference' string. Here, printing $str variable results 'This is Call By
Reference'. It is because changes are done in the actual variable $str.
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'This is ';
adder($str);
Output:
PHP allows you to define C++ style default argument values. In such a case, if you don't
pass any value to the function, it will use the default argument value.
Let's see the simple example of using PHP default arguments in function.
Example 1
<?php
function sayHello($name="Ram"){
echo "Hello $name<br/>";
} sayHello("Sonoo");
sayHello();//passing no value
sayHello("Vimal");
?>
Output:
Hello Sonoo
Hello Ram
Hello Vimal
PHP Strings
In this chapter we will look at some commonly used functions to manipulate strings.
Example
Example
Example
Example
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
The PHP str_replace() function replaces some characters with some other characters in a
string.
Example
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>
PHP Form Handling
We can create and use forms in PHP. To get form data, we need to use PHP
superglobals $_GET and $_POST.
The form request may be get or post. To retrieve data from a get request, we need to use
$_GET, for post request $_POST.
Let's see a simple example to receive data from get request in PHP.
File: form1.html
<form action="welcome.php" method="get">
Name: <input type="text" name="name"/>
<input type="submit" value="visit"/>
</form>
File: welcome.php
<?php
$name=$_GET["name"];//receiving name field value in $name
variable
echo "Welcome, $name";
?>
Post request is widely used to submit forms that have a large amount of data such as
file upload, image upload, login form, registration form etc.
The data passed through post request is not visible on the URL browser so it is secured.
You can send a large amount of data through post requests.
Let's see a simple example to receive data from a post request in PHP.
File: form1.html
<?php
$name=$_POST["name"];//receiving name field value in $name
variable
$password=$_POST["password"];//receiving password field value in
$password variable
echo "Welcome: $name, your password is: $password";
?>
Output:
A ribute Description
It specifies the encryption type for the form data when the form is
encType
submi ed.
It implies the server not to verify the form data when the form is
novalidate
submi ed.
Controls used in forms: Form processing contains a set of controls through which the
client and server can communicate and share information. The controls used in forms
are:
● Textbox: Textbox allows the user to provide single-line input, which can be
● Textarea: Textarea allows the user to provide multi-line input, which can be
list of values.
● Radio Bu ons: Radio bu ons allow the user to select only one option from
given options.
● Bu ons: Bu ons are the clickable controls that can be used to submit the
form.
Creating a simple HTML Form: All the form controls given above is designed by using
the input tag based on the type a ribute of the tag. In the below script, when the form is
submi ed, no event handling mechanism is done. Event handling refers to the process
done while the form is submi ed. These event handling mechanisms can be done by
using javaScript or PHP. However, JavaScript provides only client-side validation.
Hence, we can use PHP for form processing.
HTML Code:
<!DOCTYPE html>
<html>
<head>
<title>Simple Form Processing</title>
</head>
<body>
<form id="form1" method="post">
FirstName:
<input type="text" name="firstname" required/>
<br>
<br>
LastName
<input type="text" name="lastname" required/>
<br>
<br>
Address
<input type="text" name="address" required/>
<br>
<br>
Email Address:
<input type="email" name="emailaddress" required/>
<br>
<br>
Password:
Form Validation: Form validation is done to ensure that the user has provided the
relevant information. Basic validation can be done using HTML elements. For example,
in the above script, the email address text box is having a type value as “email”, which
prevents the user from entering the incorrect value for an email. Every form field in the
above script is followed by a required a ribute, which will intimate the user not to leave
any field empty before submi ing the form. PHP methods and arrays used in form
processing are:
● $_GET[]: It is used to retrieve the information from the form control through
the parameters sent in the URL. It takes the a ribute given in the url as the
parameter.
● $_POST[]: It is used to retrieve the information from the form control through
the HTTP POST method. IT takes the name a ribute of corresponding form
Form Processing using PHP: Above HTML script is rewri en using the above
mentioned functions and array. The rewri en script validates all the form fields and if
there are no errors, it displays the received information in a tabular form.
<?php
if (isset($_POST['submit']))
{
<head>
<title>Simple Form Processing</title>
</head>
<body>
<h1>Form Processing using PHP</h1>
<fieldset>
<form id="form1" method="post" action="form.php">
<?php
if (isset($_POST['submit']))
{
if (isset($error))
{
echo "<p style='color:red;'>"
. $error . "</p>";
}
}
?>
FirstName:
<input type="text" name="firstname"/>
<span style="color:red;">*</span>
<br>
<br>
</html>
Output:
Note: When the PHP and HTML are coded in a single file, the file should be saved as
PHP. In the form, the value for the action parameter should be a file name.
PHP File Upload
PHP file upload features allow you to upload binary and text files both. Moreover, you
can have the full control over the file to be uploaded through PHP authentication and
file operation functions.
PHP $_FILES
The PHP global $_FILES contains all the information of the file. By the help of $_FILES
global, we can get file name, file type, file size, temp file name and errors associated
with the file.
$_FILES['filename']['name']
$_FILES['filename']['type']
$_FILES['filename']['size']
$_FILES['filename']['tmp_name']
returns the temporary file name of the file which was stored on the server.
$_FILES['filename']['error']
move_uploaded_file() function
Syntax
File: uploadform.html
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'],
$target_path)) {
echo "File uploaded successfully!";
} else{
echo "Sorry, file not uploaded, please try again!";
}
?>
PHP Download File
PHP enables you to download files easily using the built-in readfile() function. The
readfile() function reads a file and writes it to the output buffer.
$context ]] )
File: download1.php
<?php
$file_url = 'http://www.google.com/f.txt';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: utf-8");
header("Content-disposition: attachment; filename=\"" .
basename($file_url) . "\"");
readfile($file_url);
?>
File: download2.php
<?php
$file_url = 'http://www.myremoteserver.com/file.exe';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" .
basename($file_url) . "\"");
readfile($file_url);
?>
The PHP date() function formats a timestamp to a more readable date and time.
Syntax
date(format,timestamp)
Parameter Description
Get a Date
The required format parameter of the date() function specifies how to format the date (or
time).
Here are some characters that are commonly used for dates:
Other characters, like"/", ".", or "-" can also be inserted between the characters to add
additional forma ing.
Example
<!DOCTYPE html>
<html>
<body>
<?php
Today is 2020/11/03
Today is 2020.11.03
Today is 2020-11-03
Today is Tuesday
Use the date() function to automatically update the copyright year on your website:
Example
Get a Time
Here are some characters that are commonly used for times:
The example below outputs the current time in the specified format:
Example
<?php
echo "The time is " . date("h:i:sa");
?>
Note that the PHP date() function will return the current date/time of the server!
If the time you got back from the code is not correct, it's probably because your server is
in another country or set up for a different timezone.
So, if you need the time to be correct according to a specific location, you can set the
timezone you want to use.
The example below sets the timezone to "America/New_York", then outputs the current
time in the specified format:
Example
<?php
date_default_timezone_set("America/New_York");
echo "The time is " . date("h:i:sa");
?>
The PHP mktime() function returns the Unix timestamp for a date. The Unix timestamp
contains the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT)
and the time specified.
Syntax
The example below creates a date and time with the date() function from a number of
parameters in the mktime() function:
Example
<?php
$d=mktime(11, 14, 54, 8, 12, 2014);
echo "Created date is " . date("Y-m-d h:i:sa", $d);
The PHP strtotime() function is used to convert a human readable date string into a
Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT).
Syntax
strtotime(time, now)
The example below creates a date and time from the strtotime() function:
Example
<?php
$d=strtotime("10:30pm April 15 2014");
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>
PHP is quite clever about converting a string to a date, so you can put in various values:
Example
<?php
$d=strtotime("tomorrow");
echo date("Y-m-d h:i:sa", $d) . "<br>";
$d=strtotime("next Saturday");
echo date("Y-m-d h:i:sa", $d) . "<br>";
$d=strtotime("+3 Months");
echo date("Y-m-d h:i:sa", $d) . "<br>";
?>
However, strtotime() is not perfect, so remember to check the strings you put in there.
Regular expressions can be used to perform all types of text search and text replace
operations.
Syntax
In PHP, regular expressions are strings composed of delimiters, a pa ern and optional
modifiers.
$exp = "/AIT/i";
In the example above, / is the delimiter, AIT is the pa ern that is being searched for, and
i is a modifier that makes the search case-insensitive.
The delimiter can be any character that is not a le er, number, backslash or space. The
most common delimiter is the forward slash (/), but when your pa ern contains
forward slashes it is convenient to choose other delimiters such as # or ~.
PHP provides a variety of functions that allow you to use regular expressions. The
preg_match(), preg_match_all() and preg_replace() functions are some of the most
commonly used ones:
Function Description
preg_match() Returns 1 if the pa ern was found in the string and 0 if not
preg_match_all() Returns the number of times the pa ern was found in the
string, which may also be 0
Using preg_match()
The preg_match() function will tell you whether a string contains matches of a pa ern.
Example
<!DOCTYPE html>
<html>
<body>
<?php
$str = "Visit AIT";
$pattern = "/AIT/i";
echo preg_match($pattern, $str);
?>
</body>
</html>
1
Using preg_match_all()
The preg_match_all() function will tell you how many matches were found for a pa ern
in a string.
Example
<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
Using preg_replace()
The preg_replace() function will replace all of the matches of the pa ern in a string with
another string.
Example
<?php
$str = "Visit Microsoft!";
$pattern = "/microsoft/i";
echo preg_replace($pattern, "AIT", $str); // Outputs "Visit AIT!"
?>
Modifier Description
Expression Description
[abc] Find one character from the options between the brackets
Metacharacters
Metacharacter Description
\d Find a digit
Quantifiers
Quantifier Description
Note: If your expression needs to search for one of the special characters you can use a
backslash ( \ ) to escape them. For example, to search for one or more question marks
you can use the following expression: $pa ern = '/\?+/';
Grouping
You can use parentheses ( ) to apply quantifiers to entire pa erns. They also can be used
to select parts of the pa ern to be used as a match.
Example
Use grouping to search for the word "banana" by looking for ba followed by two
instances of na:
<?php
$str = "Apples and bananas.";
$pattern = "/ba(na){2}/i";
echo preg_match($pattern, $str); // Outputs 1
?>
Exception Handling in PHP
An exception is an unexpected program result that can be handled by the program
itself. Exception Handling in PHP is almost similar to exception handling in all
programming languages.
Following are the main advantages of exception handling over error handling
handling code there is always if else block to handle errors. These conditions
and code to handle errors got mixed so that becomes unreadable. With try
● Grouping of error types: In PHP both basic types and objects can be thrown
Following code explains the flow of normal try catch block in PHP:
<?php
Output:
Following code explains the flow of normal try catch and finally block in PHP
<?php
Output:
<?php
class myException extends Exception {
function get_Message() {
// Error message
$errorMsg = 'Error on line '.$this->getLine().
' in '.$this->getFile()
.$this->getMessage().' is number zero';
return $errorMsg;
}
}
function demo($a) {
try {
Output:
Set a Top Level Exception Handler: The set_exception_handler() function set all user defined
functions to all uncaught exceptions.
<?php
// PHP Program to illustrate normal
// try catch block code
if($var < 0) {
// Uncaught Exception
throw new Exception('Uncaught Exception occurred');
}
}
// Uncaught Exception
demo (-3);
?>
Output:
PHP Session
A PHP session is used to store and pass information from one page to another
temporarily (until the user closes the website).
PHP session technique is widely used in shopping websites where we need to store and
pass cart information e.g. username, product code, product name, product price etc
from one page to another.
PHP session creates a unique user id for each browser to recognize the user and avoid
conflict between multiple browsers.
PHP session_start() function is used to start the session. It starts a new or resumes
existing session. It returns an existing session if the session is created already. If a
session is not available, it creates and returns a new session.
Syntax
Example
1. session_start();
PHP $_SESSION
PHP $_SESSION is an associative array that contains all session variables. It is used to
set and get session variable values.
1. $_SESSION["user"] = "Sachin";
1. echo $_SESSION["user"];
File: session1.php
<?php
session_start();
?>
<html>
<body>
<?php
$_SESSION["user"] = "Sachin";
echo "Session information are set successfully.<br/>";
?>
<a href="session2.php">Visit next page</a>
</body>
</html>
File: session2.php
<?php
session_start();
?>
<html>
<body>
<?php
echo "User is: ".$_SESSION["user"];
?>
</body>
</html>
File: sessioncounter.php
<?php
session_start();
File: session3.php
<?php
session_start();
session_destroy();
?>
Example
<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<input type="hidden" id="custId" name="custId" value="3487">
<input type="submit" value="Submit">
</form>
<p><strong>Note:</strong> The hidden field is not shown to the user,
but the data is sent when the form is submitted.</p>
</body>
</html>
A hidden field let web developers include data that cannot be seen or modified by users
when a form is submi ed.
A hidden field often stores what database record that needs to be updated when the
form is submi ed.
Note: While the value is not displayed to the user in the page's content, it is visible (and
can be edited) using any browser's developer tools or "View Source" functionality. Do
not use hidden inputs as a form of security!
Syntax
<input type="hidden">
PHP Cookies
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server embeds
on the user's computer. Each time the same computer requests a page with a browser, it
will send the cookie too. With PHP, you can both create and retrieve cookie values.
Syntax
Only the name parameter is required. All other parameters are optional.
We then retrieve the value of the cookie "user" (using the global variable $_COOKIE).
We also use the isset() function to find out if the cookie is set:
Example
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30),
"/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Note: You might have to reload the page to see the value of the cookie.
Note: The setcookie() function must appear BEFORE the <html> tag.
Note: The value of the cookie is automatically URLencoded when sending the cookie,
and automatically decoded when received (to prevent URLencoding, use setrawcookie()
instead).
Example
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30),
"/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Note: You might have to reload the page to see the new value of the cookie.
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past:
Example
<!DOCTYPE html>
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
</body>
</html>
The following example creates a small script that checks whether cookies are enabled.
First, try to create a test cookie with the setcookie() function, then count the $_COOKIE
array variable:
Example
<!DOCTYPE html>
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
What is a Database?
A database is a separate application that stores a collection of data. Each database has
one or more distinct APIs for creating, accessing, managing, searching, and replicating
the data it holds.
Other kinds of data stores can also be used, such as files on the file system or large
hash tables in memory but data fetching and writing would not be so fast and easy
with those types of systems.
RDBMS Terminology
Before we proceed to explain the MySQL database system, let us revise a few
definitions related to the database.
MySQL Database
MySQL is a fast, easy-to-use RDBMS being used for many small and big businesses.
MySQL is developed, marketed and supported by MySQL AB, which is a Swedish
company. MySQL is becoming so popular because of many good reasons −
All downloads for MySQL are located at MySQL Downloads. Pick the version number
of MySQL Community Server which is required along with the platform you will be
running it on.
The recommended way to install MySQL on a Linux system is via RPM. MySQL AB
makes the following RPMs available for download on its website −
● MySQL − The MySQL database server manages the databases and tables,
controls user access and processes the SQL queries.
● MySQL-client − MySQL client programs, which make it possible to connect to
and interact with the server.
● MySQL-devel − Libraries and header files that come in handy when compiling
other programs that use MySQL.
● MySQL-shared − Shared libraries for the MySQL client.
● MySQL-bench − Benchmark and performance testing tools for the MySQL
database server.
The MySQL RPMs listed here are all built on a SuSE Linux system, but they will
usually work on other Linux variants with no difficulty.
Now, you will need to adhere to the steps given below, to proceed with the installation
−
The above command takes care of installing the MySQL server, creating a user of
MySQL, creating necessary configuration and starting the MySQL server
automatically.
You can find all the MySQL related binaries in /usr/bin and /usr/sbin. All the tables and
databases will be created in the /var/lib/mysql directory.
The following code box has an optional but recommended step to install the remaining
RPMs in the same manner −
The default installation on any version of Windows is now much easier than it used to
be, as MySQL now comes neatly packaged with an installer. Simply download the
installer package, unzip it anywhere and run the setup.exe file.
The default installer setup.exe will walk you through the trivial process and by default
will install everything under C:\mysql.
Test the server by firing it up from the command prompt the first time. Go to the
location of the mysqld server which is probably C:\mysql\bin, and type −
mysqld.exe --console
NOTE − If you are on NT, then you will have to use mysqld-nt.exe instead of
mysqld.exe
If all went well, you will see some messages about startup and InnoDB. If not, you may
have a permissions issue. Make sure that the directory that holds your data is
accessible to whatever user (probably MySQL) the database processes run under.
MySQL will not add itself to the start menu, and there is no particularly nice GUI way
to stop the server either. Therefore, if you tend to start the server by double clicking the
mysqld executable, you should remember to halt the process by hand by using
mysqladmin, Task List, Task Manager, or other Windows-specific means.
After MySQL has been successfully installed, the base tables have been initialized and
the server has been started: you can verify that everything is working as it should be
via some simple tests.
It will produce the following result on Linux. It may vary depending on your
installation −
If you do not get such a message, then there may be some problem in your installation
and you would need some help to fix it.
You can connect to your MySQL server through the MySQL client and by using the
mysql command. At this moment, you do not need to give any password as by default
it will be set as blank.
[root@host]# mysql
It should be rewarded with a mysql> prompt. Now, you are connected to the MySQL
server and you can execute all the SQL commands at the mysql> prompt as follows −
Post-installation Steps
MySQL ships with a blank password for the root MySQL user. As soon as you have
successfully installed the database and the client, you need to set a root password as
given in the following code block −
Now to make a connection to your MySQL server, you would have to use the
following command −
UNIX users will also want to put your MySQL directory in your PATH, so you won't
have to keep typing out the full path everytime you want to use the command-line
client.
If you want to run the MySQL server at boot time, then make sure you have the
following entry in the /etc/rc.local file.
/etc/init.d/mysqld start
MySQL - Administration
First check if your MySQL server is running or not. You can use the following
command to check it −
If your MySql is running, then you will see the mysqld process listed out in your
result. If server is not running, then you can start it by using the following command −
root@host# cd /usr/bin
Now, if you want to shut down an already running MySQL server, then you can do it
by using the following command −
root@host# cd /usr/bin
./mysqladmin -u root -p shutdown
Enter password: ******
For adding a new user to MySQL, you just need to add a new entry to the user table in
the database mysql.
The following program is an example of adding a new user guest with SELECT,
INSERT and UPDATE privileges with the password guest123; the SQL query is −
mysql> SELECT host, user, password FROM user WHERE user = 'guest';
+-----------+---------+------------------+
| host | user | password |
+-----------+---------+------------------+
When adding a new user, remember to encrypt the new password using the
PASSWORD() function provided by MySQL. As you can see in the above example, the
password mypass is encrypted to 6f8c114b58f2ce9e.
Notice the FLUSH PRIVILEGES statement. This tells the server to reload the grant
tables. If you don't use it, then you won't be able to connect to MySQL using the new
user account at least until the server is rebooted.
You can also specify other privileges to a new user by se ing the values of following
columns in the user table to 'Y' when executing the INSERT query or you can update
them later using an UPDATE query.
● Select_priv
● Insert_priv
● Update_priv
● Delete_priv
● Create_priv
● Drop_priv
● Reload_priv
● Shutdown_priv
● Process_priv
● File_priv
● Grant_priv
● References_priv
● Index_priv
● Alter_priv
Another way of adding a user account is by using GRANT SQL command. The
following example will add user zara with password zara123 for a particular database,
which is named as TUTORIALS.
This will also create an entry in the MySQL database table called as user.
NOTE − MySQL does not terminate a command until you give a semicolon (;) at the
end of the SQL command.
In most of the cases, you should not touch this file. By default, it will have the
following entries −
[mysqld]
datadir = /var/lib/mysql
socket = /var/lib/mysql/mysql.sock
[mysql.server]
user = mysql
basedir = /var/lib
[safe_mysqld]
err-log = /var/log/mysqld.log
pid-file = /var/run/mysqld/mysqld.pid
Here, you can specify a different directory for the error log, otherwise you should not
change any entry in this table.
Here is the list of the important MySQL commands, which you will use time to time to
work with MySQL database −
MySQL works very well in combination with various programming languages like
PERL, C, C++, JAVA and PHP. Out of these languages, PHP is the most popular one
because of its web application development capabilities.
PHP provides various functions to access the MySQL database and to manipulate the
data records inside the MySQL database. You would require to call the PHP functions
in the same way you call any other PHP function.
The PHP functions for use with MySQL have the following general format −
mysql_function(value,value,...);
The second part of the function name is specific to the function, usually a word that
describes what the function does. The following are two of the functions, which we
will use in our tutorial −
mysqli_connect($connect);
mysqli_query($connect,"SQL statement");
<body>
<?php
$retval = mysql_function(value, [value,...]);
if( !$retval ) {
die ( "Error: a related error message" );
}
// Otherwise MySQL or PHP Statements
?>
</body>
</html>
MySQL - Connection
You can establish the MySQL database using the mysql binary at the command
prompt.
Example
Here is a simple example to connect to the MySQL server from the command prompt −
This will give you the mysql> command prompt where you will be able to execute any
SQL command. Following is the result of above command −
In the above example, we have used root as a user but you can use any other user as
well. Any user will be able to perform all the SQL operations, which are allowed to that
user.
You can disconnect from the MySQL database any time using the exit command at
mysql> prompt.
mysql> exit
Bye
Syntax
connection mysql_connect(server,user,password,new_link,client_flag);
1 server
Optional − The host name running the database server. If not specified,
then the default value will be localhost:3306.
2 user
Optional − The username accessing the database. If not specified, then the
default will be the name of the user that owns the server process.
4 new_link
5 client_flags
You can disconnect from the MySQL database anytime using another PHP function
mysql_close(). This function takes a single parameter, which is a connection returned
by the mysql_connect() function.
Syntax
bool mysql_close ( resource $link_identifier );
If a resource is not specified, then the last opened database is closed. This function
returns true if it closes the connection successfully otherwise it returns false.
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($conn);
?>
</body>
</html>
Example
PHP uses mysql_query function to create or delete a MySQL database. This function
takes two parameters and returns TRUE on success or FALSE on failure.
Syntax
bool mysql_query( sql, connection );
1 sql
2 connection
Example
<body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
if(! $retval ) {
die('Could not create database: ' . mysql_error());
}
echo "Database TUTORIALS created successfully\n";
mysql_close($conn);
?>
</body>
</html>
You would need special privileges to create or to delete a MySQL database. So,
assuming you have access to the root user, you can create any database using the
mysql mysqladmin binary.
Be careful while deleting any database because you will lose all the data available in
your database.
This will give you a warning and it will confirm if you really want to delete this
database or not.
PHP uses mysql_query function to create or delete a MySQL database. This function
takes two parameters and returns TRUE on success or FALSE on failure.
Syntax
bool mysql_query( sql, connection );
1 sql
2 connection
Example
<html>
<head>
<title>Deleting MySQL Database</title>
</head>
<body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully<br />';
$sql = 'DROP DATABASE TUTORIALS';
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not delete database: ' . mysql_error());
}
echo "Database TUTORIALS deleted successfully\n";
mysql_close($conn);
?>
</body>
</html>
WARNING − While deleting a database using the PHP script, it does not prompt you
for any confirmation. So be careful while deleting a MySQL database.
Once you get connected with the MySQL server, it is required to select a database to
work with. This is because there might be more than one database available with the
MySQL Server.
It is very simple to select a database from the mysql> prompt. You can use the SQL
command used to select a database.
Example
Now, you have selected the TUTORIALS database and all the subsequent operations
will be performed on the TUTORIALS database.
NOTE − All the database names, table names, table fields names are case sensitive. So
you would have to use the proper names while giving any SQL command.
Syntax
bool mysql_select_db( db_name, connection );
1 db_name
2 connection
Example
<html>
<head>
<title>Selecting MySQL Database</title>
<body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db( 'TUTORIALS' );
mysql_close($conn);
?>
</body>
</html>
A database table has its own unique name and consists of columns and rows.
We will create a table named "MyGuests", with five columns: "id", "firstname",
"lastname", "email" and "reg_date":
After the data type, you can specify other optional a ributes for each column:
Each table should have a primary key column (in this case: the "id" column). Its value
must be unique for each record in the table.
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Example (PDO)
<?php
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn = null;
?>
After a database and a table have been created, we can start adding data in them.
The INSERT INTO statement is used to add new records to a MySQL table:
In the previous chapter we created an empty table named "MyGuests" with five
columns: "id", "firstname", "lastname", "email" and "reg_date". Now, let us fill the table
with data.
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
The SELECT statement is used to select data from one or more tables:
The following example selects the id, firstname and lastname columns from the
MyGuests table and displays it on the page:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
First, we set up an SQL query that selects the id, firstname and lastname columns from
the MyGuests table. The next line of code runs the query and puts the resulting data
into a variable called $result.
Then, the function num_rows() checks if there are more than zero rows returned.
If there are more than zero rows returned, the function fetch_assoc() puts all the results
into an associative array that we can loop through. The while() loop loops through the
result set and outputs the data from the id, firstname and lastname columns.
The WHERE clause is used to extract only those records that fulfill a specified
condition.
The following example selects the id, firstname and lastname columns from the
MyGuests table where the last name is "Doe", and displays it on the page:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
First, we set up the SQL query that selects the id, firstname and lastname columns from
the MyGuests table where the last name is "Doe". The next line of code runs the query
and puts the resulting data into a variable called $result.
Then, the function num_rows() checks if there are more than zero rows returned.
If there are more than zero rows returned, the function fetch_assoc() puts all the results
into an associative array that we can loop through. The while() loop loops through the
result set and outputs the data from the id, firstname and lastname columns.
UPDATE table_name
The following examples update the record with id=2 in the "MyGuests" table:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
The following examples delete the record with id=3 in the "MyGuests" table:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
A prepared statement is a feature used to execute the same (or similar) SQL statements
repeatedly with high efficiency.
1. Prepare: An SQL statement template is created and sent to the database. Certain
values are left unspecified, called parameters (labeled "?"). Example: INSERT
INTO MyGuests VALUES(?, ?, ?)
2. The database parses, compiles, and performs query optimization on the SQL
statement template, and stores the result without executing it
3. Execute: At a later time, the application binds the values to the parameters, and
the database executes the statement. The application may execute the statement
as many times as it wants with different values
Compared to executing SQL statements directly, prepared statements have three main
advantages:
● Prepared statements reduce parsing time as the preparation on the query is done
only once (although the statement is executed multiple times)
● Bound parameters minimize bandwidth to the server as you need send only the
parameters each time, and not the whole query
● Prepared statements are very useful against SQL injections, because parameter
values, which are transmi ed later using a different protocol, need not be
The following example uses prepared statements and bound parameters in MySQLi:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$firstname = "Mary";
$lastname = "Moe";
$email = "[email protected]";
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "[email protected]";
$stmt->execute();
In our SQL, we insert a question mark (?) where we want to substitute in an integer,
string, double or blob value.
This function binds the parameters to the SQL query and tells the database what the
parameters are. The "sss" argument lists the types of data that the parameters are. The s
character tells mysql that the parameter is a string.
● i - integer
● d - double
● s - string
● b - BLOB
By telling mysql what type of data to expect, we minimize the risk of SQL injections.
Note: If we want to insert any data from external sources (like user input), it is very
important that the data is sanitized and validated.
The following example uses prepared statements and bound parameters in PDO:
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// insert a row
$firstname = "John";
$lastname = "Doe";
$email = "[email protected]";
$stmt->execute();
What is AJAX?
Classic web pages, (which do not use AJAX) must reload the entire page if the content
should change.
Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook
tabs.
Property Description
Method Description
or not.
void open(method, URL, async, same as above but specifies username and
1. User sends a request from the UI and a javascript call goes to XMLH pRequest
object.
3. Server interacts with the database using JSP, PHP, Servlet, ASP.net etc.
4. Data is retrieved.
5. Server sends XML data or JSON data to the XMLH pRequest callback function.
jQuery
The main purpose of jQuery is to provide an easy way to use JavaScript on your website
to make it more interactive and a ractive. It is also used to add animation.
What is jQuery
jQuery Features
● HTML manipulation
● DOM manipulation
● DOM element selection
● CSS manipulation
● Effects and Animations
● Utilities
● AJAX
● HTML event methods
● JSON Parsing
● Extensibility through plug-ins
Sometimes, a question can arise: what is the need of jQuery or what difference does it
make on bringing jQuery instead of AJAX/ JavaScript? If jQuery is the replacement of
AJAX and JavaScript?
So, you can say that out of the lot of JavaScript frameworks, jQuery is the most popular
and the most extendable. Many of the biggest companies on the web use jQuery.
● Microsoft
● Google
● IBM
● Netflix
jQuery Example
jQuery is developed by Google. To create the first jQuery example, you need to use
JavaScript file for jQuery. You can download the jQuery file from jquery.com or use the
absolute URL of jQuery file.
In this jQuery example, we are using the absolute URL of jQuery file. The jQuery
example is wri en inside the script tag.
File: firstjquery.html
<!DOCTYPE html>
<html>
<head>
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.mi
n.js">
</script>
$(document).ready(function() {
$("p").css("background-color", "cyan");
});
</script>
</head>
<body>
</body>
</html>
Output:
$(document).ready(function() {
$("p").css("color", "red");
});
$(function() {
$("p").css("color", "red");
});
Let's see the full example of jQuery using shorthand notation $().
File: shortjquery.html
<!DOCTYPE html>
<html>
<head>
<title>Second jQuery Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.mi
n.js">
</script>
<script type="text/javascript" language="javascript">
$(function() {
$("p").css("color", "red");
Output:
jQuery Selectors
jQuery Selectors are used to select and manipulate HTML elements. They are a very
important part of jQuery library.
With jQuery selectors, you can find or select HTML elements based on their id, classes,
a ributes, types and much more from a DOM.
In simple words, you can say that selectors are used to select one or more HTML
elements using jQuery and once the element is selected then you can perform various
operation on that.
All jQuery selectors start with a dollar sign and parentheses e.g. $(). It is known as the
factory function.
Every jQuery selector start with thiis sign $(). This sign is known as the factory function.
It uses the three basic building blocks while selecting an element in a given document.
S. Select Description
No or
.
Let's take a simple example to see the use of Tag selector. This would select all the
elements with a tag name
File: firstjquery.html
<!DOCTYPE html>
<html>
<head>
<title>First jQuery Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.mi
n.js">
</script>
<script type="text/javascript" language="javascript">
Output:
Note: 1. All of the above discussed selectors can be used alone or with the combination
of other selectors.
Note: 2. If you have any confliction with the use of dollor sign $ in any JavaScript library
then you can use jQuery() function instead of factory function $(). The factory function
$() and the jQuery function is the same.
The jQuery selectors can be used single or with the combination of other selectors. They
are required at every steps while using jQuery. They are used to select the exact element
that you want from your HTML document.
1) Name: It selects all elements that match with the given element
name.
2) #ID: It selects a single element that matches with the given id.
3) .Class: It selects all elements that matches with the given class.
class,.class $(".primary,.sec It will select all elements with the class "primary" or
ondary") "secondary"
:first-child $("p:first-child") It will select all p elements that are the first child of
their parent
:first-of-type $("p:first-of-type It will select all p elements that are the first p
:last-child $("p:last-child") It will select all p elements that are the last child of
their parent
:last-of-type $("p:last-of-type It will select all p elements that are the last p
:nth-child(n) $("p:nth-child(2) This will select all p elements that are the 2nd child
:nth-of-type( $("p:nth-of-type( It will select all p elements that are the 2nd p
:nth-last-of-t $("p:nth-last-of-t This will select all p elements that are the 2nd p
ype(n) ype(2)") element of their parent, counting from the last child
:only-child $("p:only-child") It will select all p elements that are the only child of
their parent
:only-of-typ $("p:only-of-typ It will select all p elements that are the only child,
parent > $("div > p") It will select all p elements that are a direct child of
parent $("div p") It will select all p elements that are descendants of a
element + $("div + p") It selects the p element that are next to each div
next elements
siblings element
:eq(index) $("ul li:eq(3)") It will select the fourth element in a list (index starts
at 0)
:gt(no) $("ul li:gt(3)") Select the list elements with an index greater than 3
:lt(no) $("ul li:lt(3)") Select the list elements with an index less than 3
:not(selector $("input:not(:em Select all input elements that are not empty
) pty)")
:contains(tex $(":contains('Hel Select all elements which contains the text "Hello"
t) lo')")
element
[a ribute=v $("[href='default. Select all elements with a href a ribute value equal
[a ribute!=v $("[href!='defaul It will select all elements with a href a ribute value
[a ribute$= $("[href$='.jpg']") It will select all elements with a href a ribute value
[a ribute|= $("[title|='Tomo Select all elements with a title a ribute value equal
followed by a hyphen
type="password"
type="checkbox"
:bu on $(":bu on") It will select all input elements with type="bu on"
jQuery - Plugins
A plug-in is a piece of code wri en in a standard JavaScript file. These files provide
useful jQuery methods which can be used along with jQuery library methods.
There are plenty of jQuery plug-in available which you can download from the
repository link at h ps://jquery.com/plugins.
To make a plug-in's methods available to us, we include a plug-in file very similar to
jQuery library file in the <head> of the document.
We must ensure that it appears after the main jQuery source file, and before our
custom JavaScript code.
<body>
.............................
</body>
</html>
This is very simple to write your own plug-in. Following is the syntax to create a a
method −
jQuery.fn.methodName = methodDefinition;
● Any methods or functions you a ach must have a semicolon (;) at the end.
● Your method must return the jQuery object, unless explicitly noted otherwise.
● You should use this.each to iterate over the current set of matched elements - it
produces clean and compatible code that way.
For example, if we write a plugin that we want to name debug, our JavaScript filename
for this plugin is −
jquery.debug.js
The use of the jquery. prefix eliminates any possible name collisions with files intended
for use with other libraries.
Example
Following is a small plug-in to have a warning method for debugging purposes. Keep
this code in jquery.debug.js file −
jQuery.fn.warning = function() {
return this.each(function() {
alert('Tag Name:"' + $(this).prop("tagName") + '".');
});
};
This is paragraph
This is division
Architecture of Web Services
The Web Services architecture describes how to instantiate the elements and implement
the operations in an interoperable manner.
The architecture of web service interacts among three roles: service provider, service
requester, and service registry. The interaction involves the three operations: publish,
find, and bind. These operations and roles act upon the web services artifacts. The web
service artifacts are the web service software module and its description.
The following figure illustrates the operations, roles, and their interaction.
● Service Provider
● Service Requestor
● Service Registry
Service Provider
Service Requestor
Service requestor is the application that is looking for and invoking or initiating an
interaction with a service. The browser plays the requester role, driven by a consumer
or a program without a user interface.
Service Registry
Service requestors find service and obtain binding information for services during
development.
Find: In the find operation, the service requestor retrieves the service description
directly. It can be involved in two different lifecycle phases for the service requestor:
development.
● And, at the runtime to retrieve the service's binding and location description for
invocation.
Bind: In the bind operation, the service requestor invokes or initiates an interaction
with the service at runtime using the binding details in the service description to locate,
contact, and invoke the service.
● Service
● Service Registry
Service Description: The service description comprises the details of the interface and
implementation of the service. It includes its data types, operations, binding
information, and network location. It can also categorize other metadata to enable
discovery and utilize by service requestors. It can be published to a service requestor or
a service registry.
REST stands for REpresentational State Transfer. REST is web standards based
architecture and uses HTTP Protocol. It revolves around resource where every
component is a resource and a resource is accessed by a common interface using HTTP
standard methods. REST was first introduced by Roy Fielding in 2000.
In REST architecture, a REST Server simply provides access to resources and REST
client accesses and modifies the resources. Here each resource is identified by URIs/
global IDs. REST uses various representation to represent a resource like text, JSON,
XML. JSON is the most popular one.
HTTP methods
Following four HTTP methods are commonly used in REST based architecture.
A web service is a collection of open protocols and standards used for exchanging data
between applications or systems. Software applications wri en in various
programming languages and running on various platforms can use web services to
exchange data over computer networks like the Internet in a manner similar to
inter-process communication on a single computer. This interoperability (e.g., between
Java and Python, or Windows and Linux applications) is due to the use of open
standards.
Web services based on REST Architecture are known as RESTful web services. These
webservices uses HTTP methods to implement the concept of REST architecture. A
RESTful web service usually defines a URI, Uniform Resource Identifier a service,
provides resource representation such as JSON and set of HTTP Methods.
In next chapters, we'll create a webservice say user management with following
functionalities −
What is PDO?
PDO refers to PHP Data Object, which is a PHP extension that defines a lightweight
and consistent interface for accessing a database in PHP. It is a set of PHP extensions
which provide a core PDO class and database-specific driver. Each database driver can
expose database-specific features as a regular extension function that implements the
PDO interface.
Note: We cannot perform any type of database function by using the PDO extension
itself. To access a database server, we must use a database-specific PDO driver.
PDO mainly focuses on data access abstraction rather than database abstraction. It
provides data-access abstraction layer, which means, regardless of which database we
are using, we have to use the same functions provided by that database to issue queries
and fetch data. PDO does not provide data abstraction, as it does not rewrite the SQL or
emulate missing features.
PDO is the native database driver. There are some benefits of using PDO that are given
below:
operations.
Installation Process
Note: Here we will discuss the installation process for Windows OS only.
Step 2: Install the XAMPP Server on your system by following these steps.
Step 8: Run the Apache server and MySQL from here (as per the given screenshot).
Step 9: Now, open php.ini from C:/xampp/php/php.ini (where you have installed your
XAMPP) and uncomment the extension "php_pdo_mysql.dll" and "php_pdo.dll" (if
you are working with MySQL database), or "php_pdo_oci.dll" (if you are working with
Oracle database). Now, start working with the database. In PHP 5.1 upper version, it is
already set.