WP Material
WP Material
1 Introduction to WEB
2.2 Page Layout and linking, User centric design, Sitemap, Planning 30
and publishing website,
3 Basics of HTML 42
4 CSS 84
5 Bootstrap 137
6 Client Side Scripting using JavaScript 158
1: Introduction to WEB
1.1 Basics of WWW
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
retrieval and display of text and media to your device.
The building blocks of the Web are web pages which are formated 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.
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' computer, allows users to view the retrieved documents.
All the websites are stored in web servers. Just as someone lives on rent in a house, a
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 for the same.
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
technologies include Hypertext Markup Language (HTML), Hypertext Transfer Protocol
(HTTP) and Web browsers.
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 Chrome, Mozilla Firefox,
Internet Explorer, Safari, and more.
WWW Overview
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
universe of network-accessible information, an embodiment of human knowledge.
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 was created by Timothy Berners Lee in 1989 at CERN in Geneva. The
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.
The following diagram briefly defines evolution of 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
reviews, comments, and feedback.
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
information sharing. Examples of Web 2.0 applications are Youtube, Wiki, Flickr, Facebook,
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
generate and distribute useful content tailored to the needs of users.
Comparison:
WWW Architecture
WWW architecture is divided into several layers as shown in the following diagram:
Identifiers and Character Set
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 writen in human
languages.
Syntax
XML (Extensible Markup Language) helps to define common syntax in semantic web.
Data Interchange
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:
● OWL Lite for taxonomies and simple constraints.
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
querying RDF data and OWL Ontologies.
Proof
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.
WWW Operation
WWW works on a client- server approach. Following steps explains how the web works:
1. User enters the URL (say, htp://www.tutorialspoint.com) of the web page in the
address bar of the web browser.
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
the HTTP connection.
5. Now the web browser receives the web page, It interprets it and displays the
contents of the web page in the web browser’s window.
1.2 Hypertext Transfer Protocol (HTTP):
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 formated and transmited 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
transmits the requested Web Page.
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
carried over TCP/IP to communicate with the server. The server processes the browser's
request and sends a response, and then the connection is closed. Thus, the browser
retrieves content from the server for the user.
2) Request URI
• The uniform resource identifier (URI) is a string to identify the names or resources
on the internet.
• URI is a combination of URL and URN.
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 .
301 Moved The requested page has moved to a new url .
Permanently
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 "htp protocol" version.
Version Not
Supported
• 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.
//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
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
//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>
Web Page
a web page is a document available on the world wide web. Web Pages are stored on a
web server and can be viewed using a web browser.
A web page can contain huge information including text, graphics, audio, video and hyperlinks.
These hyperlinks are the link to other web pages.
Collection of linked web pages on a web server is known as a website. A unique Uniform
It is processed using client side scripting such as JavaScript. And then passed in to
Document Object Model (DOM).
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.
Scripting language is used to create dynamic web pages.
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
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.
2.1 Concepts of Effective Web Design
2.2 Web Design Issues
Browser & Operating Systems
● Web pages are writen 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.
● Different versions of HTML also support different sets of tags.
● 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.
● To make a web page portable, test it on different browsers on different operating
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
another site without looking at the contents of your web page.
Browsers provide temporary memory called cache to store the graphics.
When a user gives the URL of the web page for the first time, the HTML file together with
all the graphics files referred to in a page is downloaded and displayed.
Display Resolution
● Display resolution is another important factor affecting the Web page design, as we
do not have any control on display resolution of the monitors on which the user
views our pages.
● Display or screen resolution is measured in terms of pixels and common resolutions
are 800 X 600 and 1024 X 786.
● We have three choices for Web page design.
● Design a web page with fixed resolution.
● Make a flexible design using an HTML table to fit into different resolutions.
● 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
use centered design to display the page properly.
● (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. It includes all the design aspects such as
● Web site theme
● Web typography
● Graphics
● Visual structure
● Navigation etc…
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, botom and left in this particular order.
The first major area of importance in terms of users viewing patern is the center, then top,
right, botom and left in this particular order.
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
Web site user-centric.
Users either scan the information on the web page to find the section of their interest or
read the information to get details.
Sitemap
Many times Web sites are too complex as there are a large number of sections and each
section contains many pages.
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
about where he/she is and where to go from there.
To make it simple, keep your hierarchy of information to a few levels or provide the
navigation bar on each page to jump directly to a particular 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.
b) Horizontal:
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.
4) Contextual navigation or Ad Hoc Navigation
When the information can’t be fited 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.
Today’s browsers are fully-functional software suites that can interpret and display HTML
Web pages, applications, JavaScript, AJAX and other content hosted on Web servers.
Many browsers offer plug-ins which extend the capabilities of the software so it can display
multimedia information (including sound and video), or the browser can be used to perform
tasks such as videoconferencing, to design web pages or add anti-phishing filters and other
security features to the 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 butons, home buton, refresh and
stop, bookmark option, etc. Every other part, except the window where requested
web page is displayed, comes under it.
2. The Browser Engine: The browser engine works as a bridge between the User
interface and the rendering engine. According to the inputs from various user
interfaces, it queries and manipulates the rendering engine.
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
formated 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:
· Internet Explorer: Trident
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.
The Two-tier architecture is divided into two parts:
On client application side the code is writen 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
1) Client 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,
buton etc.
2) Business layer:
In this layer all business logic writen 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.
Advantages
Disadvantages
1. Increase Complexity/Effort
HTML
Introduction
HTML stands for Hyper Text Markup Language. It is a formating 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
HTML5 2012
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.
Formafling Tags
The following table shows the HTML tags used for formating the text:
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:
<table> </table> Specifies a table.
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"
atribute is the most important atribute of the HTML a tag. and which links to the destination
page or URL.href atribute of HTML anchor tag
The href atribute is used to define the address of the file to be linked. In other words, it
points out the destination page.
If we want to open that link to another page then we can use the target atribute 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 atribute can only be used with the href atribute in the anchor tag.
● If we will not use the target atribute then the link will open on the same page.
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 Image
HTML img tag is used to display images on the web page. HTML img tag is an empty tag
that contains atributes only, closing tags are not used in an HTML image element.
Output:
The src and alt are important atributes of HTML img tag. All atributes of HTML image tag
are given below.
1) src
It is a necessary atribute 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
The alt atribute defines an alternate text for the image, if it can't be displayed. The value
of the alt atribute describes the image in words. The alt atribute is considered good for
SEO prospective.
3) width
It is an optional atribute which is used to specify the width to display the image. It is not
recommended now. You should apply CSS in place of width atribute.
4) height
It h3 the height of the image. The HTML height atribute also supports iframe, image and
object elements. It is not recommended now. You should apply CSS in place of height
atribute.
Example:
1. <img src="animal.jpg" height="180" width="300" alt="animal image">
Use of alt aflribute
We can use alt aflributes with tags. It will display an alternative text in case the image
cannot be displayed on the browser. Following is the example for alt aflribute:
HTML table tag is used to display data in tabular form (row * column). There can be many
columns in a row.
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
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 aflribute 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
the 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 aflribute 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>
<table>
<tr>
<th>1 header</th>
<th>1 header</th>
<th>1 header</th>
</tr>
<tr>
<td>1data</td>
<td>1data</td>
<td>1data</td>
</tr>
<tr>
<td>2 data</td>
<td>2 data</td>
<td>2 data</td>
</tr>
<tr>
<td>3 data</td>
<td>3 data</td>
<td>3 data</td>
</tr>
</table>
</body>
</html>
Output:
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 atribute.
It will divide a cell into multiple rows. The number of divided rows will depend on
rowspan values.
Let's see the example that spans two rows.
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" atribute 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" atributes. By
default, the atributes 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 atribute of the link
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 butons, lists, submit
butons 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 atribute. An input
element can
be of type textfield, checkbox, password, radiobuton, submit buton, and more.
2. Action:
The required action atribute specifies where to send the form-data when a form
Issubmited.
<form action="URL"> Value : URL
Description : Where to send the form data.
3. Method :
The method atribute specifies how to send form-data (the form-data is sent to the
page specified in the action atribute).
<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 atribute specifies a name or a keyword that indicates where to display the
response that is received after submiting 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>
Atributes of HTML Audio Tag
Aflribute Description
controls It defines the audio controls which are displayed with play/pause butons.
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 atributes 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>
Aflribute Description
controls It defines the video controls which are displayed with play/pause butons.
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 atributes.
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 buton to complete the drag
operation.
If you want to make an element draggable, set the draggable atribute 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 geting 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
The Geolocation API works with the navigation.geolocation object. Its read-only property
returns a Geolocation object which identifies the location of the user and can generate a
customized result based on user location.
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>
<script>
var x= document.getElementById("location");
function getlocation() {
if(navigator.geolocation){
alert("your browser is supporting Geolocation API")
}
else
{ alert("Sorry! your browser is not
supporting")
}
}
</script>
</body>
</html>
● error: An error callback function which takes "Position Error" object as input.
Storing data with the help of web storage is similar to cookies, but it is beter and faster than
cookie storage.
● Web Storage can use storage space upto 5MB per domain. (The browser
● 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
There are two types of web storage with different scope and lifetime.
data and is available for every page. But data persist even if the browser is closed
and
stores 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
clearer to both website designers and users. There are some elements like <header>,
<footer>, <nav> and <article> that define the layout of a website.
It is enriched with advanced features which makes it easy and interactive for
designer/developer and users.
● It facilitates you to design beter 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 atributes 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 atributes have been
applications.
● Server-Sent Events − HTML5 introduces events which flow from web server to
the web browsers and they are called Server-Sent Events (SSE).
● 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 without It supports audio and video controls with
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.
Atributes like charset, async and ping Atributes 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
beter 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.
<audio> It is used to play audio files in HTML.
<bdi> The bdi stands for bi-directional isolation. It isolates a part of text that is
formated 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 element or an <hgroup> element), but this is not required.
● The <header> element can also be used to wrap a section’s table of contents, a
search form, or any relevant logos.
● The <header> tag is a new tag in HTML5 and it requires a starting tag as well as an
end tag.
● There can be several <header> elements in one document.
Syntax:
<header> ...</header>
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.
Syntax :
<!DOCTYPE html>
<html>
<head>
<title>footer tag</title>
<style>
.column {
float: left;
width: 27%;
height: 300px;
}
p {
font-size:20px;
font-weight:bold;
}
</style>
</head>
<body>
<footer>
<div class="column">
<p>Company</p>
<ul style="list-style-type:disc">
<li>About Us</li>
<li>Careers</li>
<li>Privacy Policy</li>
<li>Contact Us</li>
</ul>
</div>
<div class="column">
<p>Learn</p>
<ul>
<li>Algorithms</li>
<li>Data Structures</li>
<li>Languages</li>
<li>CS Subjects</li>
<li>Video Tutorials</li>
</ul>
</div>
<div class="column">
<p>Practice</p>
<ul>
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-submited 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 contain each individual piece of content.
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
to screen readers, search engines, and third-party applications.
Note: This tag does not render as anything special in a browser, you have to use CSS for
that.
Default CSS sefling: 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 atributes. 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 puting styles only.
Let’s say you were creating a document about data processing. The following represents a
typical use for the <section> elements.
<section id="preparation" class="imaginaryClass">
<h2>Prepare Data</h2>
<p>Random text Random text Random text...</p>
</section>
<section id="processing">
<h2>Process Prepared Data</h2>
<p>Some More Random text Some More Random text Some More
Random text ...</p>
</section>
<section id="display">
<h2>Processed Data</h2>
<p>Some More Random text Some More Random text Some More
Random text ...</p>
</section>
HTML5 | figure Tag
The <figure> tag in HTML is used to add self-contained content like illustrations,
diagrams, photos or codes listing in a document. It is related to main flow but it can be
used in any position of a document and the figure goes with the flow of the document and
if you remove it then it should not affect the flow of the document. This tag is new in
HTML5.
Syntax:
<figure> Image content... </figure>
Aflributes: It contains mostly two tags which are listed below:
● img src: This tag is used to add image source in the document.
● figcaption: This tag is used to set the caption to the image.
HTML5 | figcaption Tag
he <figurecaption> tag in HTML is used to set a caption to the figure element in a
document. This tag is new in HTML5.
syntax:
<figcaption> Figure caption </figcaption>
4. CSS
Introduction
What is
CSS?
CSS Syntax
Example
<!DOCTYPE html>
<html>
<head>
<style>
p {
color: red;
text-align: center;
}
</style>
</head>
<body>
<p>Hello World!</p>
<p>These paragraphs are styled with CSS.</p>
</body>
</html>
Hello World!
Comments are used to explain the code, and may help when you edit the source
code at a later date.
browsers. 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 atribute.
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>
</body>
</html>
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 atribute 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
- The styles for many documents can not be controlled from one source.
- Selector grouping methods can not be used to handle complex situations.
- 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>
style. Me too!
And me!
The id selector uses the id atribute 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>
#para1 {
text-align: center;
color: red;
}
</style>
</head>
<body>
<p id="para1">Hello World!</p>
<p>This paragraph is not affected by the style.</p>
</body>
</html>
Hello World!
The class selector selects HTML elements with a specific class atribute.
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>
<style>
h1, h2, p {
text-align: center;
color: red;
}
</style>
</head>
<body>
<h1>Hello World!</h1>
<h2>Smaller heading!</h2>
<p>This is a paragraph.</p>
</body>
</html>
Hello World!
Smaller heading!
This is a
paragraph.
CSS Pseudo-classes
Syntax
The syntax of
pseudo-classes:
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:hover MUST come after a:link and a:visited in the CSS definition in order to
be effective.
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:
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>
<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="b">
<h2>text-align: left:</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="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.
text-align: 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: 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;
}
div.c {
text-align: justify; /* For Edge
*/ text-align-last: justify;
}
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".
CSS text-decoration Property
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
text-decoration: overline;
}
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
Definition and Usage
The text-decoration property specifies the decoration added to text, and is a shorthand
property for:
● text-decoration-line (required)
● text-decoration-color
● text-decoration-style
text-decoration: underline;
text-decoration-color: red;
CSS Borders
● 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
border, botom border, and the left border).
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;}
CSS Border Width
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, botom border, and the left border).
Example
p.one {
border-style:
solid;
border-width: 5px;
}
p.two {
border-style: solid;
border-width: medium;
}
p.three {
border-style: solid;
border-width: 2px 10px 4px 20px;
}
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 seting the
margin for each side of an element (top, right, botom, and left).
CSS has properties for specifying the margin for each side of an
● margin-top
● margin-right
● margin-botom
● margin-left
All the margin properties can have the following values:
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:
CSS Padding
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 seting the
padding for each side of an element (top, right, botom, and left).
CSS has properties for specifying the padding for each side of an element:
● padding-top
● padding-right
● padding-botom
● padding-left
Example:
<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 1px solid black;
background-color: lightblue;
padding-top: 50px;
padding-right: 30px;
padding-bottom: 50px;
padding-left: 80px;
}
</style>
</head>
<body>
<h2>Using individual padding properties</h2>
<div>This div element has a top padding of 50px, a right padding of
30px, a bottom padding of 50px, and a left padding of 80px.</div>
</body>
</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.
Now, we will see how to use these properties with examples.
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 −
<html>
<head>
</head>
<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
■ Physics
1. Maths
2. Social Science
3. Physics
a. Maths
b. Social Science
c. Physics
i. Maths
ii. Social Science
iii. Physics
CSS Gradients
CSS gradients let you display smooth transitions between two or more specified
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 {
background-image: linear-gradient(red, yellow);
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
● animation-iteration-count
● animation-direction
● animation-timing-function
● animation-fill-mode
● animation
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).
In the example above we have specified when the style will change by using the keywords
"from" and "to" (which represents 0% (start) and 100% (complete)).
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>
<div class="tooltip"><strong> Welcome to AIT</strong>
<span class="tooltiptext">A solution of all technology.</span>
</div>
</body>
</html>
Botom Tooltip
The botom tooltip specifies that if you move your mouse cursor over the element, the
tooltip information will be displayed on the botom 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>
</body>
</html>
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>
Right Tooltip
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>
CSS Styling Images
Rounded Images
Thumbnail Image:
Example:
img {
border: 1px solid #ddd;
border-radius: 4px;
padding: 5px;
width: 150px;
}
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:
opacity 1
(default)
img {
opacity: 0.5;
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.
A good way to use CSS variables is when it comes to the colors of your design. Instead of
copy and pasting the same colors over and over again, you can place them in variables.
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 :root selector
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>
CSS Flex Container
Parent Element (Container)
The flex container becomes flexible by seting the display property to flex:
.flex-container {
display: flex;
● flex-direction
● flex-wrap
● flex-flow
● justify-content
● align-items
● align-content
The flex-direction property defines in which direction the container wants to stack the flex
items.
.flex-container {
display: flex;
flex-direction: column;
}
.flex-container {
display: flex;
flex-direction: column-reverse;
}
.flex-container {
display: flex;
flex-direction: row;
}
.flex-container {
display: flex;
flex-direction: row-reverse;
}
The flex-wrap Property
The flex-wrap property specifies whether the flex items should wrap or not.
The examples below have 12 flex items, to beter demonstrate the flex-wrap property.
.flex-container {
display: flex;
flex-wrap: wrap;
}
.flex-container {
display: flex;
flex-wrap: nowrap;
}
.flex-container {
display: flex;
flex-wrap: wrap-reverse;
}
The flex-flow Property
The flex-flow property is a shorthand property for seting both the flex-direction and
flex-wrap properties.
.flex-container {
display: flex;
flex-flow: row wrap;
}
The CSS Flexbox Items Properties
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
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):
@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):
Syntax:
[atribute*="value"] {
// CSS property
Example:
<!DOCTYPE html>
<html>
<head>
<style>
Output:
[aflribute^=”str”] Selector: The [atribute^=”value”] selector is used to select those elements
whose atribute 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:
[atribute^="str"] {
// CSS property
}
[aflribute$=”str”] Selector: The [atribute$=”value”] selector is used to select those
elements whose atribute value ends with a specified value str. The following example
selects all elements with a class atribute value that ends with str.
Syntax:
[atribute$="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
add-ons have increased with CSS2 and further expanded with CSS3. CSS3 has
support to add animations to your modern websites.
● CSS3 has compatibility with external font styles through google fonts and typecast.
It was not possible with earlier CSS1 and CSS2.
● The selectors in CSS3 has increased while CSS1 and CSS2 only had simple selectors.
● CSS1 AND CSS2 didn’t have provision to specifically design the web layout. It is
possible with the CSS3 grid system and template layout module. It helped in
creating layouts according to user components.
● CSS3 has now been split into various documents known as modules. Previously it
was all a single document and limited features. The modularisation helped in
working on a particular specification and faster evolution.
● CSS3 is compatible with Internet Explorer 9 whereas CSS1 used to be compatible
with Internet Explorer 3.
● CSS3 supports responsive design. Responsive design is referred to as designing a
website in such a manner that it looks good on all screen sizes. It should not break
or misalign components on changing the screen size.
5.0 Bootstrap
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, butons,
History of Bootstrap
Bootstrap was developed by Mark Oto and Jacob Thornton at Twiter.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 setings, 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 butons, effects and more
responsiveness.
Bootstrap 4 supports some of the latest, stable releases of all major browsers and platforms.
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
First Bootstrap Example
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 atribute 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.
First Bootstrap Example (with responsive fixed width container)
<!DOCTYPE html>
<html lang="en">
<head>
<title>This is a Bootstrap example</title>
<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">
<h1> First Bootstrap web page</h1>
<p>Write your text here..</p>
</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>
Bootstrap Container
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).
Bootstrap:
1. container
2. container-fluid
See the basic layout of a container:
<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
class="col-md-3"style="background-color:lavenderblush;">Vijay</div>
<div
class="col-md-3"style="background-color:lavender;">Kartik</div>
<div
class="col-md-3"style="background-color:lavenderblush;">Ajeet</div>
</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>
Bootstrap Tables
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>
</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>
<!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
1) Bootstrap Vertical Form (Default)
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap example</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap
.min.css"/>
</head>
<body>
<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.
This example is only applied to forms within viewports that are at least 768px wide!
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.
Additional rules for 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">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn
btn-default">Submit</button>
</div>
</div>
</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>
Bootstrap Images
Bootstrap supports images. There are three classes in Bootstrap that can be used to apply
some simple style to the images.
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">
<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>Rounded Corners</h2>
<img src="abc.jpg" class="img-rounded" 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 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
.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.m
in.js"></script>
</body>
</html>
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;
to the image.
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
Text alignment is used to easily realign text to components with text alignment classes
syntax:
wider.</p>
Left aligned text on viewports sized LG (large) or wider.
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.
Processing Requires server interaction. Does not need interaction with the
server.
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
machine(JVM) or browser. as JavaScript is developed for browser
only.
Java program has file extension “.Java” and JavaScript file has file extension
translates source code into bytecodes “.js” and it is interpreted but not
which is executed by JVM(Java Virtual compiled,every browser has the
Machine). Javascript interpreter to execute JS
code.
Java programs use more memory. JavaScript requires less memory
therefore it is used in web
pages.
How do I write JavaScript?
<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 atribute 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 or function names. There are a total of 63 keywords that JavaScript provides to
<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 leter 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";
Incorrect JavaScript
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:
<script>
var data=200;//global variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>
200 200
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:
Data Type Description
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
|| 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";
var line break = "<br />";
result = (typeof b == "string" ? "B
is String" : "B is
Numeric");
docum
ent.w
rite(
"Resu
Numeric"); lt =>
");
docum
ent.w
rite(
resul
t);
docum
ent.w
rite(
lineb
reak)
;
result = (typeof a == "string" ? "A
is String" : "A is
docum
ent.w
rite(
"Resu
lt =>
");
docum
ent.w
rite(
resul
t);
docum
ent.w
rite(
lineb
reak)
;
//-->
</script>
<p>Set the variables to different values and different
operators and then try...</p>
</body>
</html>
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
// string to number
result = Number('324');
console.log(result); // 324
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,
let result;
result = parseInt('20.01');
console.log(result); // 20
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:
<input type = "password">
Message:
<textarea rows="2" cols="50">
</textarea>
<input type = "submit">
</form>
<script>
function inline(){
var password =
document.getElementsByTagName("input")[0].value;
var input = document.getElementsByTagName("textarea")[0];
if (password != ""){
input.value = "Your password has been successfully
submitted.";
}
}
</script>
</body>
</html>
Let's see how this works in a litle more detail. As mentioned above, the JavaScript code in
the <script> element contains the function inline(). The commands in this function will be
executed only when the user clicks the ''Submit'' buton. This is specified in the HTML line
that begins the form:
<form onsubmit="inline(); return false">
The inline() function's purpose is to determine if the user has entered a value in the
''password'' field, and if they have, to alert the message ''Your password has been
successfully submited'' inside the <textarea> element.
Now let's see how to create an HTML document that will look and work the same (as far as
the user is concerned), but will do so using an external JavaScript file.
External JavaScript
This is the HTML document that references the external JavaScript file:
<!DOCTYPE html>
<body>
<form>
Password:
<input type = "password">
Message:
<textarea rows="2" cols="50">
</textarea>
<input type = "submit">
</form>
<script src = "external.js">
</script>
</body>
</html>
And this is the code in the external JavaScript file:
var submitButton = document.getElementsByTagName("input")[1];
submitButton.addEventListener("click", external);
function external(e){
var password =
document.getElementsByTagName("input")[0].value;
var input = document.getElementsByTagName("textarea")[0];
if (password != ""){
input.value = "Your password has been successfully
submitted.";
}
e.preventDefault();
}
Starting with the HTML document, notice that overall it's a smaller document compared to
the first example, because it doesn't need to contain as much information. The two really
important differences are:
● The JavaScript code is stored in the external file external.js and is referenced in
this line: <script src = "external.js">
● The <form> element no longer contains the onsubmit event handler, because this
too is now included in the external JavaScript.
So let's move on to the actual code, in the obviously-named external.js file:
The first line of code identifies the form's ''Submit'' buton and stores it in the submitButon
variable:
var submitButon = document.getElementsByTagName("input")[1];
The next line adds an event listener, so that when the ''Submit'' buton is clicked, it triggers
the external() function:
submitButon.addEventListener("click", external);
The external() function is almost identical to the inline() function in the first example; it
performs the same actions, displaying a message only if the user has entered something in
the password field.
There is only one real difference between the two functions. In the external function, we
included an argument, 'e'. This is an arbitrary value, only so we could atach to it the
preventDefault() method in the function's last line:
e.preventDefault();
This allows the results to remain displayed on the page after the user clicks ''Submit''.
Without this, the results would appear for a split second, then the page would reload.
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 leter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
2. After the first leter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.
Incorrect JavaScript
variables 1. var 123=30;
2. var *aa=320;
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
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
example:
<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
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
JavaScript array is an object that represents a collection of similar types of elements.
1. By array literal
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.write(emp[i] + "<br/>");
}
</script>
directly.
<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>
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
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
provided function conditions.
flatMap() It maps all array elements via mapping function, then flatens 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
new array
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.
JavaScript Functions
JavaScript functions are used to perform operations. We can call a JavaScript
2. Less coding: It makes our program compact. We don’t need to write many lines
//code to be executed
function msg(){
</script>
<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>
<script>
document.write(getInfo());
</script>
object. It 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
arguments.
<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:
JavaScript - if...else Statement
While writing a program, there may be a situation when you need to adopt one out
of a given set of paths. In such cases, you need to use conditional statements that
allow your program to make correct decisions and perform right actions.
actions based on different conditions. Here we will explain the if..else statement.
FlowChart of if-else
The following flow chart shows how the if-else statement works.
JavaScript supports the following forms of if..else statement −
● if statement
● if...else statement
if statement
The if statement is the fundamental control statement that allows JavaScript to make
Syntax
The syntax for a basic if statement is as
follows − 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
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>
<body>
<script type = "text/javascript">
<!--
var age = 15;
Output
The if...else if... statement is an advanced form of if…else that allows JavaScript to
Syntax
The syntax of an if-else-if statement is as
follows − if (expression 1) {
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if expression 3 is true
} else {
Statement(s) to be executed if no expression is true
}
There is nothing special about this code. It is just a series of if statements, where
each if is a part of the else clause of the previous statement. Statement(s) are
executed based on the true condition, if none of the conditions is true, then the else
block is executed.
Example
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
● 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,
● 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
be a situation when you need to come out of a loop without reaching its boflom.
There may also be a situation when you want to skip a part of your code block and
These statements are used to immediately come out of any loop or to start the next
iteration of
any loop respectively.
The break statement, which was briefly introduced with the switch statement, is used
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
<html>
<body>
<script type = "text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
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
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
9
10
Exiting the loop!
Set the variable to a different value and then try...
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
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or
"Cancel" to proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false.
Syntax
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
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box
returns null.
Syntax
window.prompt("sometext","defaultText");
Example
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method).
For example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is template based not class based. Here, we don't create classes to
1. By object literal
2. By creating instance of Object directly (using new keyword)
1. object={property1:value1,property2:value2. propertyN:valueN}
JavaScript.
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
need to add property in the function with the same name as method.
<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>
Object Model (DOM). In fact, the web browser creates a DOM of the webpage when
the page is loaded. The DOM model is created as a tree of objects like this:
How to use DOM and Events
Using DOM, JavaScript can perform multiple tasks. It can create new elements
and aflributes, change the exis+ting elements and aflributes and even remove
existing elements and aflributes. JavaScript can also react to existing events
<html>
<head>
<title>DOM!!!</title>
</head>
<body>
<h1 id="one">Welcome</h1>
<p>This is the welcome message.</p>
<h2>Technology</h2>
<p>This is the technology section.</p>
<script type="text/javascript">
var text = document.getElementById("one").innerHTML;
alert("The first heading is " + text);
</script>
</body>
</html>
Welcome
Technology
This is the technology section.
getElementsByTagName
Example
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 " +
paragraphs[1].innerHTML);
document.getElementById("second").innerHTML = "The original
message is changed.";
</script>
</body>
</html>
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()
{
alert("You clicked me!!!");
}
</script>
</body>
</html>
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:
hflps%3A%2F%2Fw3Google.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car
%3Dsaab
Decoded URI: hflps://Google.com/my test.asp?name=ståle&car=saab
Syntax
decodeURIComponent(uri)
Parameter Values
Parameter Description
Technical Details
Example
Encode a URI:
var uri = "my test.asp?name=ståle&car=saab";
var res = encodeURI(uri);
my%20test.asp?name=st%C3%A5le&car=saab
Syntax
encodeURI(uri)
Parameter Values
Parameter Description
Technical Details
Encode a URI:
Syntax
encodeURIComponent(uri)
Parameter Values
Parameter Description
Technical Details
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
Syntax
eval(string)
Parameter Values
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>
strings. 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
● If the string begins with "0", the radix is 8 (octal). This feature is deprecated
● If the string begins with any other value, the radix is 10
Note: If the first character cannot be converted to a number, parseInt() returns NaN.
of 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
processing will be faster than server-side validation. Most of the web developers
Through JavaScript, we can validate name, password, email, date, mobile numbers
can’t be empty and the password can’t be less than 6 characters long.
Here, we are validating the form on form submit. The user will not be forwarded to
<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/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
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)){
<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("passwordloc").innerHTML=
" <img src='unchecked.gif'/> Password must be at least 6
char long";
status=false;
}else{
document.getElementById("passwordloc").innerHTML=" <img
src='checked.gif'/>";
}
return status;
}
</script>
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("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 ||
dotposition+2>=x.length){
alert("Please enter a valid e-mail address \n
atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="#" onsubmit="return
validateemail();">
Email: <input type="text" name="email"><br/>
RegExp Object
Syntax
/patern/modifiers;
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Regular Expressions</h2>
<p>Click the button to do a case-insensitive search for "AIT" in a
string.</p>
<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>
string. Try it
AIT
Example explained:
Modifiers
Modifiers are used to perform case-insensitive and global searches:
Modifier Description
Brackets
Expression Description
[^0-9] Find any character NOT between the brackets (any non-digit)
Metacharacters
\d Find a digit
Quantifiers
Quantifier Description
Property Description
<!DOCTYPE html>
<html>
<body>
string. 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.
When javascript code is included in HTML, js react over these events and allow
the execution. This process of reacting over the events is called Event Handling.
For example, when a user clicks over the browser, add js code, which will
Mouse events:
Keyboard events:
Keydown & onkeydown & When the user press and then release
Keyup onkeyup the key
Form events:
Window/Document events
load onload When the browser finishes the loading of the page
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">
<!--
function clickevent()
{
document.write("This is JavaTpoint");
}
//-->
</script>
<form>
<input type="button" onclick="clickevent()" value="Who's this?"/>
</form>
</body>
</html>
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";
}
//-->
</script>
</body>
</html>
Keydown Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{
docum
ent.g
} etEle
//--> mentB
yId("
input
1");
alert
("Pre
ssed
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.
By something here we mean a function execution. If we want to execute a function
right 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
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
Code #2:
<script>
</script>
Output:
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 to do something with that inside our code.
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.floor(4.9); // returns 4
Math.floor(4.7); // returns 4
Math.floor(4.4); // returns 4
Math.floor(4.2); // returns 4
Math.floor(-4.2); // returns -5
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:
Angle in radians = Angle in degrees x PI / 180.
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
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 gefling 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
● YES / NO
● ON / OFF
● 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
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
arrays.
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":[
{"name":"Shyam", "email":"[email protected]"},
{"name":"Bob", "email":"[email protected]"},
{"name":"Jai", "email":"[email protected]"}
]}
<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
}
}
"married" are the key. In this example, there are string, number and boolean values
{
"name": "sonoo",
"email": "[email protected]"
}
can be 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"
}
}
JSON Array
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.
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}
]}
JSON Multidimensional Array
]
JSON Function Files
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>
</body>
</html>
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>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
Server Side Programming with PHP
What is PHP
PHP is an open-source, interpreted, and object-oriented scripting language that can be
executed at the server-side. PHP is well suited for web development. Therefore, it is
used to develop web applications (an application that executes on the server and
generates the dynamic page.).
PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995. PHP
7.4.1 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:
Performance:
PHP script is executed much faster than those scripts which are writen 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
beter 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.
A Helpful PHP Community:
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:
<?php
echo "Hello by PHP echo";
?>
Output:
<?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.
Below, we have an example of a simple PHP file, with a PHP script that uses a built-in
PHP function "echo" to output the text "Hello World!" on a web page:
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!
Note: However; all variable names are case-sensitive!
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.
commenting: 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>
<?php
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>
</body>
</html>
Example
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 does a good job of automatically converting types from one to another when
necessary.
● PHP variables are Perl-like.
PHP has a total of eight data types which we use to construct our variables −
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
They like 3.14159 or 49.1. By default, doubles print with the minimum number of
decimal places needed. For example, the code −
<?php
$many = 2.2888800;
$many_2 = 2.2111200;
$few = $many + $many_2;
print("$many + $many_2 = $few <br>");
?>
It produces the following browser output −
2.28888 + 2.21112 = 4.5
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 />";
?>
This will produce the following result −
$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 −
<?php
$somevar = 15;
function addit() {
GLOBAL $somevar;
$somevar++;
print "Somevar is $somevar";
}
addit();
?>
This will produce the following result −
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();
?>
1
2
3
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
known beforehand. These types of loops are also known as entry-controlled
loops. There are three main parameters to the code, namely the initialization,
the test condition and the counter.
Syntax:
+= 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:
while loop: The while loop is also an entry control loop like for loops i.e., it first checks
the condition at the start of the loop and if it's true then it enters the loop and executes
the block of statements, and goes on executing it as long as the condition holds true.
Syntax:
Example:
<?php
// PHP code to illustrate
while loops
$num = 2;
Output:
4
6
8
10
12
Flowchart:
do-while loop: This is an exit control loop which means that it first enters the loop,
executes the statements, and then checks the condition. Therefore, a statement is
executed at least once on using the do…while loop. After executing once, the program
is executed as long as the condition holds true.
Syntax:
do {
//code is executed
} while (if condition is true);
Example:
<?php
// PHP code to illustrate
do...while loops
$num = 2;
do {
$num += 2;
echo $num, "\n";
} while ($num < 12);
?>
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:
foreach loop: This loop is used to iterate over arrays. For every counter of the loop,
an array element is assigned and the next counter is shifted to the next element.
Syntax:
foreach (array_element as value) {
//code to be executed
}
Example:
$arr = array (10, 20, 30, 40, 50,
<?php
60);
Output:
10
20
30
40
50
60
Ram
Laxman
Sita
● if statement
● if…else statement
● if…elseif…else statement
● switch statement
Let us now look at each one of these in details:
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:
Prepared By: Dr. . Ajay N. Upadhyaya & Prof. Heena Panjwani Page 281
if…else Statement: We understood that if a condition will hold i.e., TRUE, then the
block of code within if will be executed. But what if the condition is not TRUE and we
want to perform an action? This is where else comes into play. If a condition is TRUE
then if block gets executed, otherwise else block gets executed.
Syntax:
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:
if…elseif…else Statement: This allows us to use multiple if…else statements. We use
this when there are multiple conditions of TRUE cases.
Syntax:
if (condition) {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
else {
// if FALSE then execute this code
}
Example:
<?php
$x = "August";
if ($x == "January") {
echo "Happy Republic Day";
}
else{
echo "Nothing to show";
}
?>
Output:
Flowchart:
switch Statement: The “switch” performs in various cases i.e., it has various cases to
which it matches the condition and appropriately executes a particular case block. It first
evaluates an expression and then compares with the values of each case. If a case
matches then the same case is executed. To use switch, we need to get familiar with
two different keywords namely, break and default.
1. The break statement is used to stop the automatic control flow into the next
Syntax:
switch(n) {
case statement1:
code to be executed if n==statement1;
break;
case statement2:
code to be executed if n==statement2;
break;
case statement3:
code to be executed if n==statement3;
break;
case statement4:
code to be executed if n==statement4;
break;
......
default:
code to be executed if n != any case;
Example:
<?php
$n = "February";
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;
echo "Doesn't
default:
exist";
}
?>
Output:
Its February
Flowchart:
Ternary Operators
In addition to all these conditional statements, PHP provides a shorthand way of writing
if…else, called Ternary Operators. The statement uses a question mark (?) and a colon
(:) and takes three operands: a condition to check, a result for TRUE and a result for
FALSE.
Syntax:
this; 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
and also allows easy access using an index or a key. An array is created using an array()
function in PHP.
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:
<?php
Output:
Example:
<?php
// Creating an indexed array
$name_one = array("Zack", "Anthony", "Ram", "Salim",
"Raghav");
// One way of Looping through an array using foreach
echo "Looping using foreach: \n";
foreach ($name_one as $val){
echo $val. "\n";
}
// count() function is used to count
// the number of elements in an array
$round = count($name_one);
echo "\nThe number of elements are $round \n";
// Another way to loop through the array using for
echo "Looping using for: \n";
for($n = 0; $n < $round; $n++){
echo $name_one[$n], "\n";
}
?>
Output:
Associative Arrays
These types of arrays are similar to the indexed arrays but instead of linear storage,
every value can be assigned with a user-defined key of string type.
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:
<?php
// Creating an associative array
$name_one = array("Zack"=>"Zara", "Anthony"=>"Any",
"Ram"=>"Rani", "Salim"=>"Sara",
"Raghav"=>"Ravina");
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:
<?php
// Defining a multidimensional array
$favorites = array(
"Dave Punk" => array(
"mob" => "5689741523",
"email" => "[email protected]",
),
"Dave Punk" => array(
"mob" => "2584369721",
"email" => "[email protected]",
),
"John Flinch" => array(
"mob" => "9875147536",
"email" => "[email protected]",
)
);
// Using for and foreach in nested form
$keys = array_keys($favorites);
for($i = 0; $i < count($favorites); $i++) {
echo $keys[$i] . "\n";
foreach($favorites[$keys[$i]] as $key =>
$value) {
echo $key . " : " . $value . "\n";
}
echo "\n";
}
?>
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:
● Indexed array: The array which contains numeric index.
Syntax:
Syntax:
in PHP:
<?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:
DBMS
Algorithm
C++
JAVA
<?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 Functions
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 lefler 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:
Hello
Sonoo
Hello Vimal
Hello John
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.
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello
'; adder($str);
echo $str;
?>
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
Hello John
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>
<html>
<head>
<title>Parameter Addition and Subtraction Example</title>
</head>
<body>
<?php
//Adding two numbers
function add($x, $y) {
$sum = $x + $y;
echo "Sum of two numbers is = $sum <br><br>";
}
add(467, 943);
//Subtracting two numbers
function sub($x, $y) {
$diff = $x - $y;
echo "Difference between two numbers is = $diff";
}
sub(943, 467);
?>
</body>
</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.
examples. 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);
echo $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
<?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
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:
It specifies the encryption type for the form data when the form is
encType
submited.
It implies the server not to verify the form data when the form is
novalidate
submited.
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
of given options.
● Buflons: Butons 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 atribute of the tag. In the below script, when the form is
submited, no event handling mechanism is done. Event handling refers to the process
done while the form is submited. 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:
<input type="password" name="password" required/>
<br>
<br>
<input type="submit" value="Submit”/>
</form>
</body>
</html>
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 atribute, which will intimate the user not to leave
any field empty before submiting the form. PHP methods and arrays used in form
processing are:
Form Processing using PHP: Above HTML script is rewriten using the above
mentioned functions and array. The rewriten 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']))
{
if ((!isset($_POST['firstname']))
|| (!isset($_POST['lastname'])) ||
(!isset($_POST['address'])) ||
(!isset($_POST['emailaddress'])) ||
(!isset($_POST['password']))
|| (!isset($_POST['gender'])))
{
$error = "*" . "Please fill all the
} required fields";
else
{
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$address = $_POST['address'];
$emailaddress =
$_POST['emailaddress'];
} $password = $_POST['password'];
} $gender = $_POST['gender'];
?>
<html>
<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>
Last Name:
<input type="text" name="lastname"/>
<span style="color:red;">*</span>
<br>
<br>
Address:
<input type="text" name="address"/>
<span style="color:red;">*</span>
<br>
<br>
Email:
<input type="email" name="emailaddress"/>
<span style="color:red;">*</span>
<br>
<br>
Password:
<input type="password" name="password"/>
<span style="color:red;">*</span>
<br>
<br>
Gender:
<input type="radio"
value="Male"
name="gender"> Male
<input type="radio"
value="Female"
name="gender">Female
<br>
<br>
<input type="submit"
name="submit" /> value="Submit"
</form>
</fieldset>
<?php
if(isset($_POST['submit']))
{
if(!isset($error))
{
echo"<h1>INPUT RECEIVED</h1><br>";
echo "<table border='1'>";
echo "<thead>";
echo
"<th>Parameter</th>";
echo "<th>Value</th>";
echo "</thead>";
echo "<tr>";
echo "<td>First Name</td>";
echo "<td>".$firstname."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Last Name</td>";
echo "<td>".$lastname."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Address</td>";
echo "<td>".$address."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Email Address</td>";
echo "<td>" .$emailaddress."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Password</td>";
echo "<td>".$password."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Gender</td>";
echo "<td>".$gender."</td>";
echo "</tr>";
echo "</table>";
}
}
?>
</body>
</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 allows you to upload single and multiple files through a few lines of code only.
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
The move_uploaded_file() function moves the uploaded file to a new location. The
move_uploaded_file() function checks internally if the file is uploaded through the POST
request. It moves the file if it is uploaded through the POST request.
Syntax
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 ]] )
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 formating.
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>
</body>
</html>
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
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!
Get Your Time Zone
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 optional timestamp parameter in the date() function specifies a timestamp. If omited,
the current date and time will be used (as in the examples above).
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 patern and optional
modifiers.
$exp = "/AIT/i";
In the example above, / is the delimiter, AIT is the patern 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 leter, number, backslash or space. The
most common delimiter is the forward slash (/), but when your patern 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 patern was found in the string and 0 if not
preg_match_all() Returns the number of times the patern was found in the
string, which may also be 0
preg_replace() Returns a new string where matched paterns have been
replaced with another string
Using preg_match()
The preg_match() function will tell you whether a string contains matches of a patern.
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 patern in
a string.
Example
<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
echo preg_match_all($pattern, $str); // Outputs 4
?>
Using preg_replace()
The preg_replace() function will replace all of the matches of the patern 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: $patern = '/\?+/';
Grouping
You can use parentheses ( ) to apply quantifiers to entire paterns. They also can be
used to select parts of the patern 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
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 {
// Check if
if($a == 0) {
throw new myException($a);
}
}
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:
Before try block
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
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";
Example: Get information
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();
if (!isset($_SESSION['counter'])) {
$_SESSION['counter'] = 1;
} else {
$_SESSION['counter']++;
}
echo ("Page Views: ".$_SESSION['counter']);
?>
File: session3.php
<?php
session_start();
session_destroy();
?>
HTML <input type="hidden">
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>
Definition and Usage
A hidden field let web developers include data that cannot be seen or modified by users
when a form is submited.
A hidden field often stores what database record that needs to be updated when the
form is submited.
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
<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
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
Enabled
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?
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.
Installing MySQL on Linux/UNIX
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 −
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 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.
[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 −
[root@host]# mysqladmin -u root password "new_password";
Now to make a connection to your MySQL server, you would have to use the
following command −
/etc/init.d/mysqld start
Also,you should have the mysqld binary in the /etc/init.d/ directory.
MySQL - Administration
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
./safe_mysqld &
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: ******
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 |
+-----------+---------+------------------+
| localhost | guest | 6f8c114b58f2ce9e |
+-----------+---------+------------------+
1 row in set (0.00 sec)
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 seting 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.
NOTE − MySQL does not terminate a command until you give a semicolon (;) at the
end of the SQL command.
[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.
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");
The following example shows a generic syntax of PHP to call any MySQL function.
<html>
<head>
<title>PHP with MySQL</title>
</head>
<body>
<?php
$retval = mysql_function(value, [value,...]);
if( !$retval ) {
die ( "Error: a related error message" );
}
// Otherwise MySQL or PHP Statements
?>
</body>
</html>
MySQL - Connection
Example
Here is a simple example to connect to the MySQL server from the command prompt
Enter password:******
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.
3 passwd
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.
Example
Try the following example to connect to a MySQL server −
<html>
<head>
<title>Connecting MySQL Server</title>
</head>
<body>
<?php
$dbhost = 'localhost:3306';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($conn);
?>
</body>
</html>
Example
Here is a simple example to create a database called TUTORIALS −
Enter password:******
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 ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully<br />';
$sql = 'CREATE DATABASE TUTORIALS';
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not create database: ' . mysql_error());
}
echo "Database TUTORIALS created successfully\n";
mysql_close($conn);
?>
</body>
</html>
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.
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';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
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.
Example
Here is an example to select a database called TUTORIALS −
Enter password:******
mysql> use TUTORIALS;
Database changed
mysql>
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>
</head>
<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 atributes for each column:
● NOT NULL - Each row must contain a value for that column, null values are not
allowed
● DEFAULT value - Set a default value that is added when no other value is passed
● UNSIGNED - Used for number types, limits the stored data to positive numbers
and zero
● AUTO INCREMENT - MySQL automatically increases the value of the field by 1
each time a new record is added
● PRIMARY KEY - Used to uniquely identify the rows in a table. The column with
PRIMARY KEY seting is often an ID number, and is often used with
AUTO_INCREMENT
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
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
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:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
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();
?>
PHP MySQL Select Data
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 {
echo "0 results";
}
$conn->close();
?>
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.
records.
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.
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);
}
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
PHP MySQL Delete Data
The DELETE statement is used to delete records from a table:
DELETE FROM table_name
WHERE some_column = some_value
Notice the WHERE clause in the DELETE syntax: The WHERE clause specifies which
record or records that should be deleted. If you omit the WHERE clause, all records will
be deleted!
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.
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:
Example (PDO with Prepared Statements)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
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
asynchronous or not.
XMLHtpRequest 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 XMLHtpRequest 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 atractive. It is also used to add animation.
What is jQuery
jQuery is a small, light-weight and fast JavaScript library. It is cross-platform and
supports different types of browsers. It is also referred as ?write less do more?
because
it takes a lot of common tasks that requires many lines of JavaScript code to accomplish,
and binds them into methods that can be called with a single line of code whenever
needed. It is also very useful to simplify a lot of the complicated things from JavaScript,
like AJAX calls and DOM manipulation.
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 writen inside the script tag.
<!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");
});
</script>
</head>
<body>
<p>The first paragraph is selected.</p>
<p>The second paragraph is selected.</p>
<p>The third paragraph is selected.</p>
</body>
</html>
Output:
selected.
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, atributes, 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.
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">
$(document).ready(function() {
$("p").css("background-color", "pink");
});
</script>
</head>
<body>
<p>This is first paragraph.</p>
<p>This is second paragraph.</p>
<p>This is third paragraph.</p>
</body>
</html>
Test it Now
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
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.
S.N Selector
Description o.
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"
element $("p") It will select all p elements.
: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
: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
[atribute=v $("[href='default. Select all elements with a href atribute value equal
[atribute!=v $("[href!='defaul It will select all elements with a href atribute value
[atribute$= $("[href$='.jpg']") It will select all elements with a href atribute value
[atribute|= $("[title|='Tomo Select all elements with a title atribute value equal
followed by a hyphen
[atribute^= $("[title^='Tom']" Select all elements with a title atribute value
type="password"
type="checkbox"
jQuery - Plugins
A plug-in is a piece of code writen 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 htps://jquery.com/plugins.
We must ensure that it appears after the main jQuery source file, and before our
custom JavaScript code.
<body>
.............................
</body>
</html>
jQuery.fn.methodName = methodDefinition;
● Any methods or functions you atach 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.
● Prefix the filename with jquery, follow that with the name of the plugin and
conclude with .js.
● Always atach the plugin to jQuery directly instead of $, so users can use a
custom alias via noConflict() method.
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") + '".');
});
};
Here is the example showing usage of warning() method. Assuming we put
jquery.debug.js file in same directory of html page.
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src =
"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.j
s">
</script>
<script src = "jquery.debug.js" type = "text/javascript">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("div").warning();
$("p").warning();
});
</script>
</head>
<body>
<p>This is paragraph</p>
<div>This is division</div>
</body>
</html>
This would alert you with following result −
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.
There are three roles in web service architecture:
● 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: A service is an interface described by a service description. The
service description is the implementation of the service. A service is a software
module
deployed on network-accessible platforms provided by the service provider. It interacts
with a service requestor. Sometimes it also functions as a requestor, using other Web
Services in its implementation.
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.
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.
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.
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 3: Select the components which you want to install and click on the Next buton.
Step 4: Create the new folder with the name xampp at the location where you want to
install XAMPP.
Step 5: Click on Next here and move forward. Installation of the XAMPP server will
start from here.
Step 6: XAMPP is installed successfully. Click on Finish buton.
Step 7: Select the preferred Language.
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.