Web Designing and Development
Web Designing and Development
DEVELOPMENT
1
Sr.No. Index
1. WEB PROGRAMMING
1.1 WWW
1.2 Web Browser
1.3 URL
1.4 DNS
1.5 Website
1.6 Web Page
1.6.1 Static Web Page
1.6.2 Dynamic Web Page
1.6.3 Differences between Static & Dynamic Page
1.7 Web Development Process
1.8 Script
1.8.1 Client Side Scripting
1.8.2 Server Side Scripting
1.9 How the web works?
1.9.1 HTTP Request
1.9.2 HTTP Response
1.10 Web Server
1.10.1 Apache Web Server
1.11 HTTP Protocol
1.11.1 Features of HTTP
1.12 HTTPS Protocol
1.13 FTP
1.13.1 Advantages of FTP
1.14 Web Hosting
1.14.1 Types of Web Hosting Services
1.15 Document Root
3 JAVASCRIPT
3.1 Javascript
3.2 Features of Javascript
3.3 History of Javascript
3.4 Application of Javascript
3.5 Javascript Example
3.6 Javascript Variables
3.7 Javascript Operators
3.8 Conditional Statements
3.9 Looping Statements
3.10 Javascript break & continue
3.11 Dialog Boxes
3.12 Javascript Array
3.13 Javascript Functions
3.14 Built in Functions
3.14.1 String Function
3.14.2 Math Function
3.14.3 Array Function
3.15 Date Methods
3.16 JS Events
3.17 Document Object Model
3.18 Javascript Form Validation
5 PHP CONCEPTS
5.1 Arrays
5.1.1 Types of Array
5.1.2 Functions of Array
5.2 User Defined Function
5.3 Variable Scope
5.4 String Functions
5.5 Math Functions
5.6 Date Functions
5.7 File Functions
6 ADVANCED PHP
6.1 GET & POST Method
6.2 The REQUEST Variable
6.3 PHP Cookies
6.4 PHP Session
6.5 MySQL
6.6 PHP+MySQL Database System
5
6.7 Database
6.8 RDBMS Terminology
6.9 MySQLi
6.9.1 MySQLi Database
6.10 PHP Regular Expressions
6.10.1 Types of Regular Expressions
6.11 File Uploading
6.12 Sending Mail
6.13 AJAX
6
1. WEB PROGRAMMING
1.1 WWW:
The World Wide Web (WWW) is combination of all resources and users
on the Internet that are using the Hypertext Transfer Protocol (HTTP).
A broader definition comes from the World Wide Web Consortium
(W3C): "The World Wide Web is the universe of network-accessible
information, an embodiment (example) of human knowledge."
The Web, as it's commonly known, is often confused with the internet.
Although the two are intricately (complexly) connected, they are
different things. The internet is, as its name implies, a network -- a vast,
global network that incorporates a multitude of lesser networks.
As such, the internet consists of supporting infrastructure and other
technologies. In contrast, the Web is a communications model that,
through HTTP, enables the exchange of information over the internet.
Tim Berners-Lee is the inventor of the Web and the director of the W3C,
the organization that oversees its development. Berners-Lee
developed hypertext, the method of instant cross-referencing that
supports communications on the Web, making it easy to link content on
one web page to content located elsewhere.
The introduction of hypertext revolutionized the way people used the
internet.
In 1989, Berners-Lee began work on the first World Wide
Web server at CERN. He called the server "httpd” and dubbed the
first client "WWW.”
Originally, WWW was just a WYSIWYG (“What You See Is What You
Get”) hypertext browser/editor that ran in the NeXTStep environment.
The World Wide Web has been widely available since 1991.
1.3 URL:
1.4 DNS :
8
Each device connected to the Internet has a unique IP address which
other machines use to find the device.
DNS servers eliminate the need for humans to memorize IP addresses in
octal format such as 192.168.1.1 (in IPv4), or more complex newer
alphanumeric IP addresses in hexadecimal format such as
2001:0db8:85a3:0000:0000:8a2e:0370:7334 (in IPv6).
1.5 Website :
1.6 WebPage:
Web page is a document available on world wide web. Web Pages are
stored on web server and can be viewed using a web browser.
A web page can contain huge information including text, graphics, audio,
video and hyper links. These hyper links are the link to other web pages.
Web page can be categorized in following 2 types :
o Static Web Page
o Dynamic Web Page
9
1.6.1 Static Web Pages
As appearing from the word static that static webpage or flat page
means a webpage in which all the information and material is
presented before users as it is exactly stored. Static web page shows
same information and data to all users.
Static Web pages display the exact same information whenever
anyone visits it. Static Web pages do not have to be simple plain text.
They can feature detailed multimedia design and even videos.
However, every visitor to that page will be received by the exact same
text, multimedia design or video every time he visits the page until
you alter that page's source code.
Static web pages are useful for those materials and contents that are
rarely need to be revised or updated. There are many advantage of
static web page in sense that they are quick and cheap to develop and
there hosting is also inexpensive.
Dynamic web page is that kind of web page, which each time shows
different content and materials to its viewer whenever visited by user.
It randomly changes according to time, accessing and interaction by the
users.
10
Dynamic Web pages are capable of producing different content for
different visitors from the same source code file. The website can display
different content based on what operating system or browser the visitor
is using, whether she is using a PC or a mobile device, or even the source
that referred the visitor. A dynamic Web page is not necessarily better
than a static Web page.
Client side scripting and server side scripting are two kinds of dynamic
web pages. In client side scripting web pages change according to your
action in web page. In this system you can download the content and
after modifying it can upload the same. In server side scripting web
pages changes whenever a web page is loaded.
In static web pages the theme and content of web pages remained fixed
and in dynamic web pages they changed according to run time.
Browsing and loading of static web pages are quicker than dynamic web
pages because unlike dynamic web pages they do not required the request
of server.
Changing the content in static web pages is a difficult task because you have
to develop and upload a new page while in dynamic web pages server
application do this automatically.
If file extension of a URL is in .htm or .html then it is a static web pages.
While if it is in .php, .asp and .jsp then it is the example of dynamic web pages.
Static web pages are created through HTML language while dynamic web
11
pages are created by the usage of PHP, JavaScript and Action script
languages.
Static web pages plan is an easy and cheap method if you wants to create a
static and non- updating web pages. While dynamic web pages method is
advisable if you have plan to update the content and material frequently.
2) Planning:
At this stage of the website development cycle, the developer creates
the data that allow a customer to judge how the entire site will look like.
Based on the information that was gathered together in the previous
phase, the sitemap is created.
The sitemap should describe the relations between the main areas of
your website. Such representation could help understand how usable
the final product will be.
It can show you the “relationship” between the different pages of a
website, so you can judge how easy it will be for the end-user to find the
required information or service if he starts from the main page.
The main reason behind the sitemap creation is to build a user-friendly
and easy to navigate website.
The other important thing is select technology stack – programming
language, frameworks, CMS that you’re going to use.
Estimated time: from 2 to 6 weeks
3) Design:
During the design phase, your website takes shape. All the visual content,
such as images, photos, and videos is created at this step.
Once again, all the info that was gathered through the first phase is crucial.
The customer and target audience must be kept in mind while you work on
a design.
The website layout is result of a designer’s work. It can be a graphic sketch
or an actual graphic design.
13
The primary function of the layout is to represent information structure,
visualize the content, and demonstrate basic functionality. Layouts contain
colors, logos, images & can give a general understanding of future product.
After that, the customer can review the layout and send you his feedback. If
the client is not sure about some aspects of your design, you should change
the layout and send it back to him. This cycle should be repeated until the
customer is completely satisfied.
Estimated time: from 4 to 12 weeks
5) Coding:
At this step, you can finally start creating the website itself. Graphic
elements that have been designed during the previous stages should be
used to create an actual website.
Usually, the home page is created first, and then all sub-pages are added,
according to the website hierarchy that was previously created in the form
of a sitemap.
Frameworks and CMS should be implemented to make sure that the server
can handle the installation and set-up smoothly.
All static web page elements that were designed during mock-up & layout
creation should be created and tested. Then, special features & interactivity
should be added. A deep understanding of every website development
technology that you’re going to use is crucial at this phase.
When you use CMS for site creation, you can also install CMS plugins at this
step if there’s a need. The other important step is SEO (Search Engine
Optimization). SEO is the optimization of website elements ( e.g., title,
14
description, keyword) that can help your site achieve higher rankings in the
search engines. And, once again, valid code is pretty important for SEO.
Estimated time: from 6 to 15 weeks
7) Maintenance:
What’s important to remember is that a website is more of a service
than a product. It’s not enough to “deliver” a website to a user.
You should also make sure that everything works fine, and everybody is
satisfied and always be prepared to make changes in another case.
Feedback system added to the site will allow you to detect possible
problems the end-users face.
The highest priority task, in this case, is to fix the problem as fast as you
can. If you won’t, you may find one day that your users prefer to use
another website rather than put up with the inconvenience.
The other important thing is keeping your website up to date. If you use
a CMS, regular updates will prevent you from bugs and decrease security
risks.
Estimated time: ongoing
1.8 Scripts
A script is a set of instructions. For Web pages they are instructions either
to the Web browser (client-side scripting) or to the server (server-side
scripting).
3. the page is displayed on the browser with any scripts running during or
after display
So client-side scripting is used to make Web pages change after they arrive
at the browser. It is useful for making pages a bit more interesting and user-
friendly. It can also provide useful gadgets such as calculators, clocks etc.
Client-side scripts depend on the user's computer. If that computer is slow
they may run slowly. They may not run at all if the browser does not
understand the scripting language.
PHP, JSP and ASP.net are the main technologies for server-side scripting.
The script is interpreted by the server meaning that it will always work the
same way. Server-side scripts are never seen by the user (so they can't copy
your code). They run on the server and generate results which are sent to
16
the user. Running all these scripts puts a lot of load onto a server but none
on the user's system.
18
HTTP Status codes with reason phrase:
1. "100": Continue
A web server is server software, that can satisfy client HTTP requests on
the public World Wide Web or also on private LANs and WANs.
The primary function of a web server is to store, process and deliver web
pages to clients.
This primary function definition was good a few decades ago but nowadays
it is better to use the terms of Web contents and / or Web resources
instead of Web Pages because it cover all kind of contents that can be
delivered to clients by web server.
20
Examples of Web contents may be HTML files, XHTML files, image files,
style sheets, scripts, other types of generic files that may be downloaded
by clients, etc…
A user agent, commonly a web browser or web crawler, initiates
communication by making a request for a specific resource using HTTP and
the server responds with the content of that resource or an error message
if unable to do so.
Commonly used web servers,
For PHP: Apache
For ASP: IIS
For JSP: Tomcat, Glassfish
The Apache HTTP Server ("httpd") was launched in 1995 and it has been
the most popular web server on the Internet since April 1996.
We can download and install apache web server separately from
http://httpd.apache.org/download.cgi
We can also download Apache web server with bundle like XAMPP, WAMP
or LAMP.
XAMPP is the most popular PHP development environment consist
of Apache, MariaDB, PHP, Perl and many other packages.
WAMP is popular PHP development environment for Windows OS.
LAMP is popular PHP development environment for Linux based OS.
We are going to use XAMPP bundle as it has installable versions of
Windows as well as Linux.
We can download XAMPP and install XAMPP from
https://www.apachefriends.org/index.html
21
configure the XAMPP
Sometimes we need to change the server configuration in some specific
conditions like,
Port is occupied
To add/load modules
To change max upload size
To change root directory
Etc…
We can configure Apache server using httpd.conf file located at
xampp/apache/conf folder.
We can configure some parameters of the server using php.ini file located
at xampp/php folder.
Important settings in httpd.conf file are,
Changing port number for apache : to change the port number for
apache go to httpd.conf file and change Listen:80 to any other
available port number, we can also change port for https using httpd-
ssl.conf file.
Loading/Unloading Modules in apache : to load/unload modules in
apache we can go to httpd.conf and remove/add the comment
code(#) from the module we want to load/unload.
Changing Root Directory: to change root directory we can change
DocumentRoot and <Directory> tag to point new directory.
Important settings in php.ini file are,
22
upload_max_filesize setting is for the maximum allowed size for
uploaded files in the scripts.
post_max_size setting is for the maximum allowed size of POST data
that PHP will accept.
error_reporting = E_ALL & ~E_NOTICE setting has default values as
E_ALL and ~E_NOTICE which shows all errors except notices.
max_execution_time = 30, Maximum execution time is set to
seconds for any script to limit the time in production servers.
mysql.default_host = hostname setting is done to connect to MySQL
with default server if no other server host is mentioned.
mysql.default_user = username setting is done to connect MySQL
with default username, if no other name is mentioned.
mysql.default_password = password setting is done to connect
MySQL with default password if no other password is mentioned.
It is a protocol used to access the data on the World Wide Web (www).
The HTTP protocol can be used to transfer the data in the form of
plain text, hypertext, audio, video, and so on.
HTTP is similar to the FTP as it also transfers the files from one
host to another host. But, HTTP is simpler than FTP as HTTP uses
only one connection, i.e., no control connection to transfer the
files.
o Connectionless protocol:
23
HTTP is a connectionless protocol. HTTP client initiates a request and
waits for a response from the server. When the server receives the
request, the server processes the request and sends back the
response to the HTTP client after which the client disconnects the
connection. The connection between client and server exist only
during the current request and response time only.
o Media independent:
HTTP protocol is a media independent as data can be sent as long
as both the client and server know how to handle the data content.
It is required for both the client and server to specify the content
type in MIME-type header.
o Stateless:
HTTP is a stateless protocol as both the client and server know each
other only during the current request. Due to this nature of the
protocol, both the client and server do not retain the information
between various requests of the web pages.
24
highly sensitive. Banking websites are common examples of
HTTPS.
1.13 FTP
It is mainly used for transferring the web page files from their
creator to the computer that acts as a server for other
computers on the internet.
FTP Access:
The use of FTP lets you upload files from your local computer to your web
server. If you build your website using your own HTML files, you can
transfer the files from your computer to the web server through FTP,
allowing your website to be accessed through the internet.
1.14.1 Types of Web Hosting Services
26
2.) Shared hosting
Shared hosting is perfect for entry-level website hosting. This is where
your website will be stored on the same server as multiple other websites.
With a shared hosting plan, all domains share the same server resources,
such as RAM (Random Access Memory) and CPU (Central Processing Unit).
However, because all resources are shared, the cost of shared hosting
plans are relatively low, making them an excellent option for website
owners in their beginning stages.
Shared hosting plans are ideal for website owners that do not receive a
large amount of web traffic.
VPS hosting is unique because each website is hosted within its own space
on the server, though it still shares a physical server with other users.
While VPS hosting provides website owners with more customization and
storage space, they’re still not able to handle incredibly high traffic levels
or spikes in usage meaning that the site performance can still be affected
by other sites on the server
Dedicated servers cost are one of the most expensive web hosting
options. Typically, they are used by website owners with high levels of
website traffic, and those who are in need of complete control of their
servers. In addition, a high level of technical expertise is required for the
27
installation and ongoing management of the server.
Cloud-based hosting is scalable, meaning your site can grow over time,
using as many resources as it requires and while the website owner only
pays for what they need.
Although there are many different options to choose from when it comes
to web hosting, it all comes down to choosing a plan that fits your needs.
Each plan caters to the specifications of different groups and realizing
what your needs in a website are will help you ensure that you’re choosing
the right plan for you and your business.
7.) Collocation
Instead of keeping servers in-house or at a private data center, you may
choose to “co- locate” your equipment by renting space in a collocation
center. The center will provide the power, bandwidth, IP address and
cooling systems that your server requires. Space is rented out in racks and
cabinets.
28
some include CGI access and more. The drawback to most free hosting
services is that they are funded by advertising that appears on your site,
so free web hosting so generally best for personal, rather than business,
websites.
9) Paid Hosting
With paid hosting, you pay a fee for space and services on a web hosting
provider's server. Monthly fees can range from a few dollars to several
hundred dollars. Obviously, the more you pay, the more features you
should have at your disposal. Services can include CGI access, database
support, ASP, ecommerce, SSL, additional space on the server, extra
bandwidth, and more.
One widely used application is shared web hosting. The price for shared
web hosting is lower than for a dedicated web server because many
customers can be hosted on a single server. It is also very common for a
single entity to want to use multiple names on the same machine so that
the names can reflect services offered rather than where those services
happen to be hosted.
There are two main types of virtual hosting, name-based and IP-based.
Name-based virtual hosting uses the host name presented by the client.
This saves IP addresses and the associated administrative overhead but
the protocol being served must supply the host name at an appropriate
point. In particular, there are significant difficulties using name-based
virtual hosting with SSL/TLS. IP-based virtual hosting uses a separate IP
address for each host name, and it can be performed with any protocol
but requires a dedicated IP address per domain name served. Port-based
virtual hosting is also possible in principle but is rarely used in practice
because it is unfriendly to users.
29
Name-based and IP-based virtual hosting can be combined: a server may have
multiple IP addresses and serve multiple names on some or all of those IP
addresses. This technique can be useful when using SSL/TLS with wildcard
certificates. For example, if a server operator had two certificates, one for
*.example.com and one for *.example.net, the operator could serve
foo.example.com and bar.example.com off the same IP address but would need
a separate IP address for baz.example.net.
11) Multi-Homing
2. IPv6 multi-homing:
If you log into your host you might see a number of directories as shown
below:
Remember, every host is different, so yours will probably not look exactly like
the picture above. Yours is quite likely to have a completely different set of
folders.
In the example shown above, the document root is the "www" directory,
but of course your host may well use a different folder. Some of the more
common alternatives are:
Htdocs
httpdocs
html
public_html
31
web
empty — no value (such as GoDaddy-hosted sites)
Your host may even have several folders nested inside each other, one of
which is the document root. In the example above the document root was:
/www/
Your addon and subdomain names will be rooted to their own folders inside
public_html.
After you create an Addon domain (or subdomain), you can find the Document
Root inside cPanel.
Your host's technical support should have sent you this information when your
first signed up for their services. If necessary, please contact them to find out
your document root.
To further complicate matters, not all hosts refer to this folder as the
document root! They might instead call it:
Start directory
Home directory
Web publishing
Directory Remote
Root
32
2. HTML and CSS
2.1 HTML :
HTML stands for Hyper Text Markup Language and is used to create
web pages.
Hypertext is a way of organizing information so readers can choose their
own path through the material. Instead of clicking through sequentially
organized pages, a hypertext user clicks specially highlighted text, called
a hyperlink (or just a link for short), to go directly to information of
interest.
Markup Language you simply “mark up” a text document with tags that
tell a Web browser how to structure and display it.
HTML originally was developed with the intent of defining the structure
of documents (headings, paragraphs, lists, and so forth) to facilitate the
sharing of scientific information between researchers.
The name of the source file has to end with the extension : “.htm” or
“.html “.
33
2.4 Advantages of HTML
Easy to use.
Support on almost every browser.
Widely used on almost every website.
Free of cost.
Easy to learn and code even novice programmer.
2.6.1 TAGS
Tags are instructions that are embedded into the text of the documents.
An HTML tag is a signal to a browser that it should do something other
than just through text up on the screen.
Syntax : < TAG > … … … … </TAG >
Note: Tags START with an open angle bracket (<) and END with close
angle bracket (>).
1. Paired Tags :
The Tags written along with a companion tag is called PAIRED TAG.
For example,
The <B> tag with its companion tag </B>.
The text between this both tag are written in BOLD.
The effect of paired tag is applied only to the text they contain.
The OPENING tag activates the effect & the CLOSING tag closes the effect.
34
2. Singular Tags:
This tag is also known as STAND-ALONE tags.
A singular tags does not have a companion tag.
2.6.3 ATTRIBUTES
For example :
<IMG src=“filename.jpg” height=”500px” width=”100%”>
Here <IMG> tag tells a web browser to display a graphical image but
which image? Then src attribute give picture file path information and
display that picture in the browser.
35
<body></body>
The <body> tag defines the document's body. The <body> element contains
all the contents of an HTML document, such as text, hyperlinks, images,
tables, lists, etc.
<title></title>
The <title> tag is required in all HTML documents and it defines the title of
the document. The <title> element:
a) defines a title in the browser toolbar .
b) provides a title for the page when it is added to favorites .
c) displays a title for the page in search-engine results .
<!-- -->
The comment tag is used to insert comments in the source code. Comments
are not displayed in the browsers. You can use comments to explain your code,
which can help you when you edit the source code at a later date. This is
especially useful if you have a lot of code.
Example :
<!--This is a comment. Comments are not displayed in the browser-->
<h1></h6>
The <h1> to <h6> tags are used to define HTML headings. <h1> defines the
most important heading. <h6> defines the least important heading.
Example :
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<p>
The <p> tag defines a paragraph. Browsers automatically add some space
(margin) before and after each <p> element.
Attributes
Attribute Value Description
<Pre></Pre>
The <pre> tag defines preformatted text. Text in a <pre> element is displayed
in a fixed-width font (usually Courier), and it preserves both spaces and line
breaks.
<B></B>
The <b> tag specifies bold text.
Example: <p>This is normal text - <b>and this is bold text</b>.</p>
<U></U>
The <u> tag represents some text that should be stylistically different from
normal text, such as misspelled words or proper nouns in Chinese.
Example :<p>This is a <u>paragraph</u>.</p>
<I></I>
The <i> tag defines a part of text in an alternate voice or mood. The content of
the <i> tag is usually displayed in italic. The <i> tag can be used to indicate a
37
technical term, a phrase from another language, a thought, or a ship name,
etc.
Example :<p>He named his car <i>The lightning</i>, because it was very
fast.</p>
<tt></tt>
The <tt> tag defines teletype text.
Example :<p><tt>Teletype text</tt></p>
<sub></sub>
The <sub> tag defines subscript text. Subscript text appears half a character
below the normal line, and is sometimes rendered in a smaller font. Subscript
text can be used for chemical formulas, like H2O.
Example :
<strike></strike>
The <strike> tag defines strikethrough text.
Example :
<p>Version 2.0 is <strike>not yet available!</strike> now available!</p>
<sup></sup>
The <sup> tag defines superscript text. Superscript text appears half a
character above the normal line, and is sometimes rendered in a smaller font.
Example :
<p>This text contains <sup>superscript</sup> text.</p>
<Big></Big>
The <big> tag defines bigger text.
Example :<p><big>Bigger text</big></p>
38
<Strong></Strong>
The <strong> tag is a phrase tag. It defines important text.
Example :<strong>Strong text</strong>
<Small></Small>
The <small> tag defines smaller text (and other side comments).
Example :College<small>of Information & Technology </small>
<font></font>
The <font> tag specifies the font face, font size, and color of text.
Attributes
Attribute Value Description
Example :
<font size="3" color="#0000FF">This is some text!</font>
<font size="3" color="rgb(255,0,0)">This is some
text!</font>
<font size="3" color="red">This is some
text!</font>
<blink></blink>
The HTML Blink Element (<blink>) is a non-standard element causing the
enclosed text to flash slowly.
39
Example: <blink> Example of blink tag.</blink>
<marquee></marquee>
The HTML <marquee> element is used to insert a scrolling area of text.
Attribute Value Description
Behavior Scroll Sets how the text is scrolled within the marquee.
Possible values are scroll, slide and alternate. If no
Slide
value is specified, the default value is scroll.
Alternate
Example:
1. <marquee>This text will scroll from right to left</marquee>
2. <marquee direction="up">This text will scroll from bottom to
top</marquee>
3. <marquee direction="down" width="250" height="200"
behavior="alternate">
<marquee behavior="alternate">This text will bounce</marquee>
</marquee>
Example:
<ol type=i> <ol start="50">
<li>Coffee</li> <li>Coffee</li>
<li>Tea</li> <li>Tea</li>
<li>Milk</li> <li>Milk</li>
</ol> </ol>
41
<il></li>
The <li> tag defines a list item. The <li> tag is used in ordered lists(<ol>),
unordered lists (<ul>).
2.Unordered List : <ul></ul>
The <ul> tag defines an unordered (bulleted) list. Use the <ul> tag together
with the <li> tag to create unordered lists.
Attribute Value Description
The <dl> tag defines the description list, the <dt> tag defines the term (name),
and the <dd> tag describes each term.
Example: <dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>
Href URL Specifies the URL of the page the link goes
to
42
Target _blank Specifies where the linked
_self document is to be loaded
_top
_parent
frame_name
Example :
Both examples above are using an absolute URL (a full web address) in
the href attribute.
A local link (a link to a page within the same website) is specified with
a relative URL (without the "https://www" part):
Example:
<h2>Absolute URLs</h2>
<a href="https://www.google.com/">Google</a>
<h2>Relative URLs</h2>
<a href="html_images.php">HTML Images</a>
<a href="/css/default.php">CSS Tutorial</a>
Use mailto: inside the href attribute to create a link that opens the user's email
program (to let them send a new email):
43
2.10.5 Button as a Link
To use an HTML button as a link, you have to add some JavaScript code.
JavaScript allows you to specify what happens at certain events, such as a click
of a button:
Example:
2.10.6 <Link>
The <link> tag defines the relationship between a document and an external
resource.
The <link> tag is most used to link to style sheets.
Attribute Value Description
Example :
<head>
<link rel="stylesheet" type="text/css" href="theme.css">
</head>
44
© copyright © ©
® registered trademark ® ®
45
2.12.1 Use an Image as a Link
To use an image as a link, just put the <img> tag inside the <a> tag:
Example :
<a href="default.php">
<img src="smiley.gif" alt="HTML
tutorial" style="width:42px;height:42px;">
</a>
Relative Path : A relative file path points to a file relative to the current page.If
you have your images in a sub-folder, you must include the folder name in
the src attribute:
Example :
Path Description
Example :
The HTML <map> tag defines an image map. An image map is an image with
clickable areas. The areas are defined with one or more <area> tags.
Try to click on the computer, phone, or the cup of coffee in the image below:
Example:
<html>
<body>
<h2>Image Maps</h2>
<p>Click on the computer, the phone, or the cup of coffee to go to a new page
and read more about the topic:</p>
<map name="workmap">
<area shape="rect" coords="34,44,270,350" alt="Computer"
href="computer.htm">
<area shape="rect" coords="290,172,333,250" alt="Phone"
href="phone.htm">
47
<area shape="circle" coords="337,300,44" alt="Cup of coffee"
href="coffee.htm">
</map>
</body>
</html>
How Does it Work?
The idea behind an image map is that you should be able to perform different
actions depending on where in the image you click.
To create an image map you need an image, and some HTML code that
describes the clickable areas.
Border “1” Specifies whether the table cells should have borders
or not
Cellpadding Pixels Specifies the space between the cell wall and the cell
content
Cellspacing Pixels Specifies the space between cells
48
<tr></tr>
The <tr> tag defines a row in an HTML table.
A <tr> element contains one or more <th> or <td> elements.
49
Bgcolor rgb(x,x,x) Specifies the background color of a header cell
#xxxxxx
colorname
he <td> tag defines a standard cell in an HTML table. The text in <td> elements
are regular and left-aligned by default.
Example:
<table>
<tr>
<th>Sr.</th><th>Name</th>
</tr>
<tr>
<td>1</td><td>ABC</td>
</tr>
</table>
<caption>
The <caption> tag defines a table caption. The <caption> tag must be inserted
immediately after the <table> tag.
Example : <table>
<caption>Monthly savings</caption>
<tr>
<th>Sr.</th><th>Name</th>
50
</tr>
<tr>
<td>1</td><td>ABC</td>
<td>2</td><td>XYZ</td>
</tr>
</table>
<table>
<tr>
<th>ABC</th><th>XYZ</th>
</tr>
<tr>
<table>
<tr>
<th>Sr.</th><th>Name</th>
</tr>
<tr>
<td>1</td><td>ABC</td>
<td>2</td><td>XYZ</td>
</tr>
</table>
</tr>
</table>
Cell padding is the space between the cell edges and the cell content.
By default the padding is set to 0.
51
Example:
<table border="2px" cellspacing="10" height="10px" width="10px"
bgcolor="cyan">
-->
<tr>
<th>Product</th>
</tr>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>abc</td>
<td>20</td>
</tr>
</table>
HTML tables can have cells that spans over multiple rows and/or columns.
To make a cell span over multiple columns, use the colspan attribute:
Example:
<table>
<tr>
<th colspan="2">Name</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>43</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>57</td>
</tr>
</table>
52
Name Age
Jill Smith 43
Eve Jackson 57
To make a cell span over multiple rows, use the rowspan attribute:
Example:
<table>
<tr>
<th>Name</th>
<td>Jill</td>
</tr>
<tr>
<th rowspan="2">Phone</th>
<td>555-1234</td>
</tr>
<tr>
<td>555-8745</td>
</tr>
</table>
Name Jill
555-1234
Phone
555-8745
2.16 FRAMES:
<frameset></frameset>
53
Rows pixels Specifies the number and size of rows in a
%,* frameset
<frame></frame>
The <frame> tag defines one particular window (frame) within a <frameset>.
Each <frame> in a <frameset> can have different attributes, such as border,
scrolling, the ability to resize, etc.
2.17 FORM
<form></form>
HTML forms are used to pass data to a server. An HTML form can contain input
elements like text fields, checkboxes, radio-buttons, submit buttons and more.
A form can also contain select lists, textarea, fieldset, legend, and label
elements. The <form> tag is used to create an HTML form:
<form>
input elements
:
</form>
Attributes of form
Action
The action attribute specifies where to send the form-data when a form
is submitted.
Syntax: <form action="URL">
Possible values for URL:
o An absolute URL - points to another web site (like action =
"http://www.example.com/example.htm")
o A relative URL - points to a file within a web site (like
action="example.php")
Enctype
The enctype attribute specifies how the form-data should be encoded
when submitting it to the server.
Syntax: <form enctype="value">
Note: The enctype attribute can be used only if method="post".
55
Method
• The method attribute specifies how to send form-data (the form-data is sent
to the page specified in the action attribute).
• Syntax: <form method="get|post">
Name
The name attribute specifies the name of a form.
The name attribute is used to reference elements in a JavaScript, or to
reference form data after a form is submitted.
Syntax: <form name = "text">
o text - Specifies the name of the form
Target
The target attribute specifies a name or a keyword that indicates where
to display the response that is received after submitting the form.
Syntax: <form target="_blank|_self|_parent|_top">
INPUT ELEMENTS
The most important form element is the <input> element. The <input>
element is used to select user information. An <input> element can vary in
many ways, depending on the type attribute. An <input> element can be of
type text field, checkbox, password, radio button, submit button, and more.
1. Text Fields
<input type="text"> defines a one-line input field that a user can
enter text into:
Example:
<form>
56
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
</form>
2. Password Field
<input type="password"> defines an input field in which text is
covered by bullets.
Example:
<form>
Password: <input type="password" name="pwd">
</form>
3. Radio Buttons
<input type="radio"> defines a radio button. Radio buttons let a user select
ONLY ONE of a limited number of choices:
Example:
<form>
<input type="radio" name="gender" value="male">Male<br>
<input type="radio" name="gender" value="female">Female
</form>
4. Checkboxes
<input type="checkbox"> defines a checkbox. Checkboxes let a user select
ZERO or MORE options of a limited number of choices.
Example:
<form>
<input type="checkbox" name="vehicle" value="Bike">I have
a bike<br><input type="checkbox" name="vehicle"
value="Car">I have a car
</form>
5. Submit Button
<input type="submit"> defines a submit button. A submit button is used to
send form data to a server. The data is sent to the page specified in the
form's action attribute. The file defined in the action attribute usually does
something with the received input:
Example:
<form name="input" action="test2.html" method="get">
Username: <input type="text" name="user">
57
<input type="submit" value="Submit">
</form>
6. Button
The button INPUT tag gives you a way to create simple input buttons with
custom text. It is similar to the INPUT submit tag but is slightly more
flexible. Example:
<form>
<input type="button" value="this is a text button">
</form>
7. File
The file INPUT tag provides a file upload form box for HTML forms. It allows
you to solicit files from your readers such as images or video.
Syntax
<input accept="file_extension|audio/*|video/*|image/*|media_type">
Tip: To specify more than one value, separate the values with a comma
(e.g. <input accept="audio/*,video/*,image/*" />.
Attribute Values
Value Description
file_extension Specify the file extension(s) (e.g: .gif, .jpg, .png, .doc) the user can
pick from
Example:
<form enctype="multipart/form-data">
58
<input type="file" accept="image/*">
</form>
8. Hidden
The hidden INPUT tag allows HTML form developers to store information
for delivery with the form data that is invisible to the form users. The
hidden form fields are used to save state in multi-page forms, collect cookie
data to deliver to the form, and just store data beyond what the customer
fills in.
Example:
<form><input type="hidden" name="date-submitted" value="2010-12-10">
</form>
9. Reset
The reset INPUT tag sets the form back to its initial state when the form
was loaded. In most forms this means that it clears the contents of the
form, but if the form started out with preloaded contents, that is what will
display when the reset button is clicked.
Example:
<form>
<input type="reset">
</form>
10. Dropdown
<select>
The <select> element is used to create a drop-down list. The <option>
tags inside the <select> element define the available options in the list.
<option>
The <option> tag defines an option in a select list. <option> elements go
inside a <select> or <datalist> element.
Example:
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
59
11. <textarea>
The <textarea> tag defines a multi-line text input control. A text area can
hold an unlimited number of characters, and the text renders in a fixed-
width font (usually Courier). The size of a text area can be specified by
the cols and rows attributes
Attribute Value Description
Example:
<textarea rows="4" cols="50">
Welcome to our College. It provides education and placement facilities.
</textarea>
60
HTML Form Example:
<html>
<head>
<title>FORM</title>
</head>
<body bgcolor="black" text="cyan">
<form action="a.html" name="registraton" method="POST"><!--GET-->
<fieldset>
<legend align="center">Registration Form</legend>
<label>Name:</label>
<input type="text" size="40" placeholder="Enter Your Name here..."
name="nm"/>
<br/>
Password:
<input type="password"name="pw"/>
<br/>
Email :
<input type="Email"name="email"/>
<br/>
Gender:
<input type="radio" name="rbt_gender" value="male"/>Male
<input type="radio" name="rbt_gender" value="female"/>Female
<br/>
Hobby:
<input type="checkbox" name="chk_tv" value="tv"/>TV
<input type="checkbox" name="chk_dance" value="Dance"/>Dance
<input type="checkbox" name="chk_sing" value="sing"/>Singing
<br/>
61
Address:
<textarea cols="20" rows="5" name="address">
</textarea>
<br/>
City:
<select name="dd_city">
<option value="">--select city--</option>
<option value="Rajkot">Rajkot</option>
<option value="surat">Surat</option>
<option value="vapi">Vapi</option>
</select>
<br/>
Upload Photo:
<input type="file"/>
<br/>
Date Of Birth:
<input type="date"/>
<br/>
Time:
<input type="time"/>
<br/>
Number:
<input type="number" max="10" min="1"/>
<br/>
Range:
<input type="range"max="10" min="1"/>
<br/>
color:
<input type="color"/>
62
<br/>
Search:
<input type="search"/>
<br/>
<input type="reset" name="btn_reset" value="reset"/>
<br/>
<br/><input type="button" value="OK"/>
<br/><input type="button" value="done"/>
<input type="submit" name="btn_submit" value="submit form"/>
<br/>
</form>
</body>
</html>
2.18 HTML5
HTML5 is the latest and most enhanced version of HTML.
HTML5 is a co-operation between the World Wide Web Consortium
(W3C) and the Web Hypertext Application Technology Working Group
(WHATWG).
63
All HTML documents must start with a <!DOCTYPE> declaration.
<body>
<header>......</header>
<nav>......</nav>
<article>
<section> ......</section>
</article>
<aside>......</aside>
<footer>......</footer>
</body>
</html>
Using Object
The <object> tag can also define a container for external (non-HTML) content.
e.g.: <object height="50" width="100" data=" Song1.mp3"></object>
Using Hyperlink
e.g.: <a href="Song1.mp3">Play the sound</a>
64
Audio Controls
To play an audio file in webpage, use the <audio> element.
The controls attribute adds audio controls, like play, pause, and volume.
The <source> element allows you to specify alternative audio files which
the browser may choose from.
supported audio formats: MP3, WAV, and OGG
Example:
<!DOCTYPE html>
<html>
<body>
<audio controls>
<source
src="E:\songs\poem.mp3"> </audio>
</body>
</html>
Video Controls
To show a video in HTML, use the <video> element
The controls attribute adds video controls, like play, pause, and volume.
65
2.21 List of HTML5 Elements:
<datalist> Together with the a new list attribute for input can be used
to make comboboxes
66
<output> Represents some type of output, such as from a calculation
done through scripting.
· autocomplete
· autofocus
· form
· formaction
· formmethod
· formnovalidate
· formtarget
· height and width
· list
· min and max
· multiple
· pattern (regexp)
· placeholder
· required
· step
· autocomplete
· novalidate
1. autocomplete attribute
· A form or input field should have autocomplete on or off.
2. novalidate attribute
· The form data should not be validated when it submitted.
· User can enter any value.
Example:
<form novalidate>
3. autofocus attribute
The input field should automatically get focused (selected for input)
when the page loads.
Example:
<form>
68
</form>
4. form attribute id
It allows user to reference a specific form by its ID on any orphaned field.
Example:
<body>
<form id="reg_form">
<p>The "Last name" field is outside the form, but still part of
the form.</p>
5. formaction attribute
· It specifies where to send the form-data when a form is
submitted.
· The formaction attribute overrides the action attribute of the
<form>.
· It is used with type="submit" and type="image".
69
Example:
<form action="Form1.html">
First name: <input type="text" name="fname"><br>
6. formmethod attribute
It overrides a form's method (get or post) with the specified method.
Example:
<form action="/action_page.php" method="get">
First name: <input type="text" name="fname" ><br>
Last name : <input type="text" name="lname"><br>
<input type="submit" value="Submit using GET">
<input type="submit" formmethod="post" value="Submit using
POST"> </form>
7. formtarget attribute
</form>
8. formnovalidate attribute
Removes all validation of the <form>.
Example:
<form>
E-mail: <input type="email" name="userid"><br>
</form>
The height and width attributes are used with <input type=”image”>
Example:
<form action="/action_page.php">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
71
<input type="image" src="arrow.png" alt="Submit" width="48"
height="48">
</form>
10.list attribute
The list attribute refers to a <datalist>. When page loads it looks like a
textbox.
After selecting, it will display a listbox.
Example:
<form>
<input list="browsers" name="browser">
<datalist id="browsers">
<option value="Internet Explorer" >
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
</form>
72
11. min and max attributes
· It specify the minimum and maximum values for an <input>
element.
· It works with the following input types:
number, range, date, datetime-local, month, time and week.
Example:
<form>
Enter a date after 1980-01-15:
<input type="date" name="bday" min="1980-01-15"><br>
Enter a month before january, 2015:
12.multiple attribute
· It allows user to enter more than one value in the <input>
element.
· It works with the following input types: email, and file.
Example:
<form>
73
13.pattern attribute
· It allows us to define our own rule to validate the input value using
Regular Expressions (RegEx). Again, if the value does not match the
specified pattern, the input will throw an error.
Example:
<form>
Country code:
<input type="text" pattern="[A-Za-z]{3}" title="Three letter country code">
<input type=”password” pattern=”.{8}” title=”min 8 character password”>
<input type="submit">
</form>
It displays a hint that describes the expected value of an input field. (e.g.,
you click on the field, and you begin to type, the text simply disappears.)
Example:
<form>
<input type="text" name="fname" value="First name"><br>
<input type="password" name="pwd" placeholder="Password">
<input type="submit">
</form>
74
15. required attribute
The input field must be filled out before submitting the form.
Example:
<form>
16.step attribute
75
2.22.1 Web Form (HTML5 Input Types):
· color
· date
· time
· datetime-local
· week
· month
· number
· range
· email
· search
· tel
· url
<form action="action.php">
Select your favourite colour:
<input type="color" name="favcolor" value="#ff0000">
<input type="submit">
</form>
76
2. Input Type Date
Example:
<form>
Birthdate:
<input type="date" name="bday">
<input type=”submit”>
</form>
The <input type="time"> allows the user to select a time (no time zone).
Example:
<form>
Select a time:
77
<input type="time" name="usr_time" value="12:05”>
</form>
Example:
<form>
Birthday (date and time):
Example:
<form>
Select a week:
78
6. Input Type Month
Example:
<form>
Joining (month and year):
<input type="month"
name="jmonth"> </form>
Example:
<form>
Enter number:
<input type="number" name="num" ><br>
Between 1 to 100 :
79
8. Input Type Range
Example:
<form method="get">
Points:
</form>
Output:
Example:
<form>
E-mail : <input type="email" name="email">
<input type="submit">
80
</form>
<input type="search"> is used for search fields (a search field behaves like a
regular text field).
<form>
</form>
Example:
<form>
</form>
81
2.23 Cascading Style Sheet
CSS stands for Cascading Style Sheets. It is a style sheet language which is
used to describe the look and formatting of a document written in markup
language. It provides an additional feature to HTML.
It is generally used with HTML to change the style of web pages and user
interfaces. It can also be used with any kind of XML documents including
plain XML, SVG and XUL.
CSS is used along with HTML and JavaScript in most websites to create user
interfaces for web applications and user interfaces for many mobile
applications.
82
Comments are ignored by browsers.
It begins with a / (forward slash) and than an * (asterisks) then the comment,
then the closing tag will * (asterisks) then the / (forward slash).
Example:
/*This Comment line*/
2.27 CSS Syntax
A CSS rule set contains a selector and a declaration block.
Selector: Selector indicates the HTML element you want to style. It could be any tag
like <h1>,<title> etc.
2. font-size: 11 px;
Value: Values are assigned to CSS properties. In the above example, value
"yellow" is assigned to color property.
83
2.28 Types of CSS
There are three Types of CSS.
1. Inline CSS
2. Internal CSS
3. External CSS
1) Inline CSS
We can apply CSS in a single element by inline CSS technique.
The inline CSS is also a method to insert style sheets in HTML document. This
method mitigates some advantages of style sheets so it is advised to use this
method sparingly.
If you want to use inline CSS, you should use the style attribute to the relevant tag.
Example:
<p style="color:blue">Hello CSS</p>
2) Internal CSS
Internal CSS is used to apply CSS on a single document or page. It can affect all
the elements of the page. It is written inside the style tag within head section of
html.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: linen;
}
h1 {
color: red;
margin-left: 80px;
}
</style>
</head>
84
<body>
<h1>The internal style sheet is applied on this heading.</h1>
<p>This paragraph will not be affected.</p>
</body>
</html>
3) External CSS
The external style sheet is generally used when you want to make changes on
multiple pages. It is ideal for this condition because it facilitates you to change
the look of the entire web site by changing just one file.
It uses the <link> tag on every pages and the <link> tag should be put inside the head
section.
Example:
Index.html
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<h1> Welcome </h1>
</body>
The external style sheet may be written in any text editor but must be saved
with a .css extension. This file should not contain HTML elements.
Let's take an example of a style sheet file named "mystyle.css".
File: mystyle.css
body {
background-color: lightblue;
}
h1 {
color: navy;
margin-left: 20px;
}
85
2.29 CSS Selector
CSS selectors are used to select the content you want to style. Selectors are
the part of CSS rule set. CSS selectors select HTML elements according to its id,
class, type, attribute etc.
There are several different types of selectors in CSS.
1. CSS Element Selector
2. CSS Id Selector
4. Universal Selector
2) CSS Id Selector
86
The id selector selects the id attribute of an HTML element to select a
specific element. An id is always unique within the page so it is chosen
to select a single, unique element.
It is written with the hash character (#), followed by the id of the element.
Let’s take an example with the id "para1".
o Each element can have only one ID
o Each page can have only one element with that ID
<html>
<head>
<style>
#para1 {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<p id="para1">Hello</p>
<p>This paragraph will not be affected.</p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
87
<style>
.center {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<h1 class="center">This heading is blue and center-aligned.</h1>
<p class="center">This paragraph is blue and center-aligned.</p>
</body>
</html>
88
Example:
<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>
3. CSS Font size: This property is used to increase or decrease the size of the font.
4. CSS Font style: This property is used to make the font bold, italic or oblique.
89
5. CSS Font variant: This property creates a small-caps effect.
90
</head>
<body>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<p>This is a paragraph.</p>
</body>
</html>
<!DOCTYPE html>
<html>
91
<head>
<style>
body {
font-size: 100%;
}
h1 { font-family: sans-serif; }
h2 { font-family: serif; }
p { font-family: monospace; }
}
</style>
</head>
<body>
<h1>This heading is shown in sans-serif.</h1>
<h2>This heading is shown in serif.</h2>
<p>This paragraph is written in monospace.</p>
</body>
</html>
92
Smaller use to display comparatively smaller text size.
SYNTAX Font-size:<value>
Example:
<html>
<head>
<title>Practice CSS font-size property</title>
</head>
<body>
<p style="font-size:xx-small;"> This font size is extremely small.</p>
<p style="font-size:x-small;"> This font size is extra small</p>
<p style="font-size:small;"> This font size is small</p>
<p style="font-size:medium;"> This font size is medium. </p>
<p style="font-size:large;"> This font size is large. </p>
<p style="font-size:x-large;"> This font size is extra large. </p>
<p style="font-size:xx-large;"> This font size is extremely large. </p>
<p style="font-size:smaller;"> This font size is smaller. </p>
<p style="font-size:larger;"> This font size is larger. </p>
<p style="font-size:200%;"> This font size is set on 200%. </p>
<p style="font-size:20px;"> This font size is 20 pixels. </p>
</body>
</html>
93
SYNTAX Font-style:<value>
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-size: 100%;
}
h2 { font-style: italic; }
h3 { font-style: oblique; }
h4 { font-style: normal; }
</style>
</head>
<body>
<h2>This heading is shown in italic font.</h2>
<h3>This heading is shown in oblique font.</h3>
<h4>This heading is shown in normal font.</h4>
</body>
</html>
SYNTAX Font-variant:<value>
Possible value Normal
94
small-caps
<!DOCTYPE html>
<html>
<head>
<style>
p { font-variant: small-caps; }
h3 { font-variant: normal; }
</style>
</head>
<body>
<h3>This heading is shown in normal font.</h3>
<p>This paragraph is shown in small font.</p>
</body>
</html>
Syntax Font-weight:<value>
95
Normal
Possible value
bold
bolder
lighter
100
200
300
400
500
600
700
800
900
default Value Normal
Apply to All text base elements
<!DOCTYPE html>
<html>
<body>
<p style="font-weight:bold;">This font is bold.</p>
<p style="font-weight:bolder;">This font isbolder.</p>
<p style="font-weight:lighter;">This font is lighter.</p>
<p style="font-weight:100;">This font is 100 weight.</p>
<p style="font-weight:200;">This font is 200 weight.</p>
<p style="font-weight:300;">This font is 300 weight.</p>
<p style="font-weight:400;">This font is 400 weight.</p>
<p style="font-weight:500;">This font is 500 weight.</p>
<p style="font-weight:600;">This font is 600 weight.</p>
<p style="font-weight:700;">This font is 700 weight.</p>
<p style="font-weight:800;">This font is 800 weight.</p>
<p style="font-weight:900;">This font is 900 weight.</p>
</body>
</html>
96
6) Font:
The CSS font property is a shorthand property for setting font-family, font-
size, font- variant, font-style and font-weight. This saves time and space.
EXAMPLE:
<html>
<head>
<style>
P{
font-family:arial;
font-size:30px;
font-weight:300
}
h1 {font: italic 800}
1. Color
The color property is used to set the color of the text. The color can be specified by:
Name - a color name, like "red"
97
RGB - an RGB value, like "rgb(255,0,0)" Hex - a hex value, like "#ff0000“
Example:
<p style="color:#00ff00;">text color property</p>
2. Text-align
The text-align property is used to set the horizontal alignment of a text.
Example
<h1 style=”text-align:right”>text align property</h1>
98
3. Text-transform
The text-transform property is used to specify uppercase and lowercase letters in a
text.
Example:
<h1 style=”text-transform:capitalize”>
text transform property
</h1>
SYANTAX text-transform: <value>;
Possible None
Value Capitalize- first character of each word is capital
Uppercase
Lowercase
Default Value None
4. Text-decoration
The text-decoration property is used to set or remove decorations from text.
Example
<h1 style=“text-decoration: underline”> text- decoration property
</h1>
5. Text-indent
It is used for indenting the first line of text.
99
Example
<p style=“text-indent: 50px”>text indent property</p>
6. Word-spacing
It is used to specify the space between each word.
Example
<h1 style=“word-spacing:10px”>Word Spacing property</h1>
7. letter-spacing
It is used to specify the space between each letters of the words.
Example
<p style=“letter-spacing:10px”>letter Spacing property</p>
100
Apply to All elements
Example P{ letter-spacing: 50px;}
8.Line-height
It sets the distance between the line.
Example
<h1 style=“Line-height:10px”>line-height property</h1>
1.Background-color:
You can specifically declare a color for the background of any
element. The background color can be specified by:
name - a color name, like "red"
RGB - an RGB value, like "rgb(255,0,0)"
Hex - a hex value, like "#ff0000“
Example
<body style=“background-color:#e0ffff”>
101
SYNTAX Background-color: <value>
Color can be red, blue, green, etc.
Possible value
RGB value
Initial Value None
Apply to All elements
1. Background-image
The background-image property specifies an image to use as the background
of an element. By default, the image is repeated so it covers the entire
element.
Example
Body{background-image:url(‘Sunset.jpg’)}
2. Background-repeat
You can set if an image set as a background of an element is to repeat
(across=x and/or down=y) the screen.
102
Apply to All elements
3. Background-attachment
You can set whether the background scrolls with the page or is fixed when
the user scrolls down the page.
4. Background-position
You can position an image used for the background of an element
103
center center
center bottom (Note:If you only specify one
keyword, the other value will be "center")
5. CSS background
The property is shorthand and used to specify Background-
attachment,Background-repeat, Background-color, Background-
image, Background-position values.
ordered list - the list items are marked with numbers or letters
104
1. List-style-image
It is used to specify an image for list item bullets.
You can create your own bullets to use within your lists.
2. List-style-position
The list-style-position property specifies the indentation of a list. "outside" is the
default value. The "inside" value further indents the list.
3. List-style-type
• The list-style-type specifies the type of list-item marker in a list of
ordered and unordered lists.
• There are a lot of choices for values:
circle, disc, lower-greek, lower-alpha, upper-latin etc...
105
SYNTAX list-style-type: <value>;
Disc
Possible value
Circle
Square
decimal
decimal leading zero
lower-roman
upper-roman
lower-greek
lower-alpha
lower-latin
upper-alpha
upper-latin
none
default Value Disc
Apply to List item elements(<ol> / <ul> / <li>)
Example <ul> { list-style-type: square;}
4. List-style
• The CSS list-style property is shorthand for specifying styles for list items.
Possible values list-style-type, list-style-position, list-style-image.
• Specify all the list properties in one declaration.
106
2.34 CSS Margin Properties
The margin clears an area around an element (outside the border).
The margin does not have a background color, and is completely transparent.
The top, right, bottom, and left margin can be changed independently
using separate properties.
Margin individual sides
Margin-top:10px;
Margin-right:15px;
Margin-bottom:15px;
Margin-left:10px
107
Number
Possible value
Percentage(%)
Auto
default Value None
Apply to All elements
Example H1{margin: 10px 10px 10px 10px;}
108
2.35 CSS Padding Properties
The CSS Padding property is used to define the space
between the element content and the element border.
The CSS padding properties are used to generate space around
content.
The padding clears an area around the content (inside the border)
of an element.
CSS has properties for specifying the padding for each side of an
element
110
o all four padding are 25px
111
border-style: dotted solid double;
o top border is dotted
o right and left borders are solid
o bottom border is double
<style>
p{
border-top-style: dotted;
border-right-style: solid;
border-bottom-style: dotted;
border-left-style: solid;
}
</style>
Note: None of the OTHER CSS border properties described below will have
ANY effect unless the border-style property is set!
112
SYNTAX Border-top: <value>
Color codes
Possible value
Rgb
default Value None
Apply to All elements
Example P{border-top: red}
113
Possible value Color codes
Rgb
default Value None
Apply to All elements
Example P{border-left: red}
Example:
<style>
p { border: 5px solid red; }
</style>
114
CSS Border-width property
The border-width property specifies the width of the four borders. The
width can be set as a specific size (in px,pt,cm etc.)
The width can be set as a specific size (in px, pt, cm, etc) or by usingone
of the three pre-defined values: thin, medium, or thick.
The border-width property can have from one to four values (top
border, right border, bottom border, left border)
Example:
<style>
p {border-style: dotted; border-width: 10px;}
</style>
<div class="myDiv">
<h2>This is a heading in a div element</h2>
<p>This is some text in a div element.</p>
</div>
</body>
</html>
<p>In this example, we remove the bullets from the list, and its default
padding and margin.</p>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
</body>
</html>
<html>
<head>
<style>
ul {
117
list-style-type: none;
margin: 0;
padding: 0;
width: 200px;
background-color: #f1f1f1;
}
li a {
display: block;
color: #000;
padding: 8px 16px;
text-decoration: none;
}
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
118
<li><a href="#about">About</a></li>
</ul>
</body>
</html>
One way to build a horizontal navigation bar is to specify the <li> elements as
inline, in addition to the "standard" code from the previous page:
Example:
<html>
<head>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
}
li {
float: left;
}
li a {
display: block;
padding: 8px;
119
background-color: #dddddd;
}
</style>
</head>
<body>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
</body>
</html>
2.39 Bootstrap
Bootstrap is a free front-end framework for faster and easier web
development
Bootstrap includes HTML and CSS based design templates for typography,
forms, buttons, tables, navigation, modals, image carousels and many
other, as well as optional JavaScript plugins.
Bootstrap also gives you the ability to easily create responsive
designs.
Steps
1. Add the HTML5 doctype
<!DOCTYPE html>
2. Bootstrap 3 is mobile-first
<meta name="viewport" content="width=device-width, initial-scale=1">
3. Containers
The .container class provides a responsive fixed width container
The .container-fluid class provides a full width container, spanning the
entire width of the viewport.
Linking file
120
<linkrel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7
/css/bootstrap.min.css">
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
Grid Classes
The Bootstrap grid system has four classes:
121
Ex. <p class="text-muted">This text is muted.</p>
2.44 Jumbotron
A jumbotron indicates a big box for calling extra attention to some special
content or information.
A jumbotron is displayed as a grey box with rounded corners. It also enlarges the
font sizes of the text inside it.
Ex :
<div class="jumbotron">
<p>Bootstrap is the most popular HTML, CSS, and JS framework for
developingresponsive, mobile-first projects on the web.</p>
</div>
122
2.45PageHeader
A page header is like a section divider.The .page-header class adds a horizontal
line under the heading
Ex:
<div class="page-header">
<h1>Example Page Header</h1>
</div>
2.46 Wells
The .well class adds a rounded border around an element with a gray
background colorand some padding. Change the size of the well by adding
the .well-sm class for small wells or .well-lg class for large wells
Ex: <div class="well">Basic Well</div>
2.47 Alerts
Bootstrap provides an easy way to create predefined alert messagesAlerts are
created with the .alert class, followed by one of the four contextual
classes .alert-success, .alert-info, .alert-warning or .alert-danger
Ex:
<div class="alert alert-success">
<strong>Success!</strong> Indicates a successful or positive action.
</div>
To close the alert message, add a .alert-dismissible class to the alert
container.
2.48 Buttons
To achieve the button styles above, Bootstrap has the following classes:
.btn
.btn-default
.btn-primary
.btn-success
.btn-info
.btn-warning
.btn-danger
.btn-link
The classes that define the different sizes are:
• .btn-lg
• .btn-md
• .btn-sm
123
• .btn-xs
Active/Disabled Buttons
A button can be set to an active (appear pressed) or a disabled (unclickable)
state:
The class .active makes a button appear pressed, and the class .disabled makes
a button unclickable:
Ex. <button type="button" class="btnbtn-default">Default</button>
Button Groups
Use a <div> element with class .btn-group to create a button group. Use the
class .btn-group-vertical to create a vertical button group
Ex:
<div class="btn-group">
<button type="button" class="btnbtn-primary">Apple</button>
<button type="button" class="btnbtn-primary">Samsung</button>
</div>
2.49 Glyphicons
Bootstrap provides 260 glyphicons from the Glyphicons Halflings set.Glyphicons
can be used in text, buttons, toolbars, navigation, forms, etc.
Ex .Envelope glyphicon: envelope ,Printglyphicon: print
<p>Print icon: <span class="glyphiconglyphicon-print"></span></p>
2.50 Badges
Badges are numerical indicators of how many items are associated with a link
Ex:
<a href="#">News <span class="badge">5</span></a><br>
<a href="#">Comments <span class="badge">10</span></a><br>
2.51 Labels
Use the .label class, followed by one of the six contextual classes .label-
default, .label-primary, .label-success, .label-info, .label-warning or .label-
danger, within a <span> element
Ex:
<span class="label label-default">Default Label</span>
124
2.52 Progress Bar
A progress bar can be used to show a user how far along he/she is in a process.
<div class="progress">
<div class="progress-bar progress-bar-striped active" role="progressbar" aria-
valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width:40%">
40%
</div>
</div>
2.53 Pagination
If you have a web site with lots of pages, you may wish to add some sort of
pagination to each page.
Ex. <ul class="pagination">
<li><a href="#">1</a></li>
<li class="active"><a href="#">2</a></li>
<li><a href="#">3</a></li>
</ul>
2.54 Breadcrumbs
Another form for pagination, is breadcrumbs:
<ul class="breadcrumb">
<li><a href="#">Home</a></li>
<li><a href="#">Private</a></li>
<li><a href="#">Pictures</a></li>
<li class="active">Vacation</li>
</ul>
2.55 Pager
Pager provides previous and next buttons (links).
<ul class="pager">
<li class="previous"><a href="#">Previous</a></li>
<li class="next"><a href="#">Next</a></li>
</ul>
2.56 Dropdown
A dropdown menu is a toggleable menu that allows the user to choose one value
from a predefined list
<div class="dropdown">
<button class="btnbtn-primary dropdown-
125
toggle" type="button" datatoggle="dropdown">Dropdown Example
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="#">HTML</a></li>
<li><a href="#">CSS</a></li>
<li><a href="#">JavaScript</a></li>
</ul>
</div>
2.57 Collapsible
Collapsibles are useful when you want to hide and show large amount of
content
Ex .
<button type="button" class="btnbtn-info" data-toggle="collapse" data-
target="#demo">Simple collapsible</button>
<div id="demo" class="collapse">
Lorem ipsum dolor sit amet, consecteturadipisicingelit, sed do
eiusmodtemporincididuntutlaboreetdolore magna aliqua. Utenim ad minim
veniam,quisnostrud exercitation ullamcolaboris nisi utaliquip ex
eacommodoconsequat.
</div>
2.58 Menus
Most web pages have some kind of a menu.
<ul class="nav nav-tabs">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Menu 1</a></li>
<li><a href="#">Menu 2</a></li>
<li><a href="#">Menu 3</a></li>
</ul>
127
Use a <div> element with the .media class to create a container for media
objects.
Use the .media-left class to align the media object (image) to the left, or
the .media-right class to align it to the right.
Text that should appear next to the image, is placed inside a container with
class="media-body".class .media-heading for headings.
Ex.
<div class="media">
<div class="media-leftmedia-top">
<img src="img_avatar1.png" class="media-object" style="width:60px">
</div>
<div class="media-body">
<h4 class="media-heading">Media Top</h4>
<p>Lorem ipsum...</p>
</div>
</div>
129
3.JAVASCRIPT
3.1 JavaScript
JavaScript (js) is a light-weight object-oriented programming language
which is used by several websites for scripting the WebPages.
It is an interpreter, full-fledged programming language that enables
dynamic interactivity on websites when applied to an HTML document. It
was introduced in the year 1995 for adding programs to the WebPages in
the Netscape Navigator browser.
Since then, it has been adopted by all other graphical web browsers. With
JavaScript, users can build modern web applications to interact directly
without reloading the page every time.
The traditional website uses JS to provide several forms of interactivity
and simplicity.
Although, JavaScript has no connectivity with Java programming
language. The name was suggested and provided in the times when Java
was gaining popularity in the market.
In addition to web browsers, databases such as CouchDB and MongoDB
uses JavaScript as their scripting and query language.
130
In 1993, Mosaic, the first popular web browser, came into existence. In
the year 1994, Netscape was founded by Marc Andreessen. He realized
that the web needed to become more dynamic.
Thus, a 'glue language' was believed to be provided to HTML to make web
designing easy for designers and part-time programmers.
Consequently, in 1995, the company recruited Brendan Eich intending to
implement and embed Scheme programming language to the browser.
But, before Brendan could start, the company merged with Sun
Microsystems for adding Java into its Navigator so that it could compete
with Microsoft over the web technologies and platforms.
Now, two languages were there: Java and the scripting language. Further,
Netscape decided to give a similar name to the scripting language as
Java's. It led to 'Javascript'.
Finally, in May 1995, Marc Andreessen coined the first code of Javascript
named 'Mocha'. Later, the marketing team replaced the name with
'LiveScript'.
But, due to trademark reasons and certain other reasons, in December
1995, the language was finally renamed to 'JavaScript'. From then,
JavaScript came into existence.
3.4 Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:
o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box,
confirm dialog box and prompt dialog box),
o Displaying clocks etc.
131
1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar(
$ ) sign.
2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different
variables.
Output
30
1. Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on the
operands. The following operators are known as JavaScript arithmetic
operators.
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
/ Division 20/10 = 2
133
% Modulus (Remainder) 20%10 = 0
2. Comparison Operators
The JavaScript comparison operator compares the two operands. The
comparison operators are as follows:
3. Bitwise Operators
The bitwise operators perform bitwise operations on operands. The
bitwise operators are as follows:
4. Logical Operators
The following operators are known as JavaScript logical operators.
Operator Description Example
5. Assignment Operators
The following operators are known as JavaScript assignment operators.
= Assign 10+10 = 20
135
-= Subtract and assign var a=20; a-=10; Now a = 10
6. Special Operators
The following operators are known as JavaScript special operators.
Operator Description
Conditional Operator returns value based on the condition. It
(?:) is like if- else.
Comma Operator allows multiple expressions to be evaluated
, as single statement.
136
4. switch case statement
1. If statement
It evaluates the content only if expression is true. The signature of JavaScript if
statement is given below.
if(expression){
//content to be evaluated
}
Example
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
Output
value of a is greater than 10
2. If...else Statement
It evaluates the content whether condition is true of false. The syntax of
JavaScript if-else statement is given below.
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
Example
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
137
}
else{
document.write("a is odd number");
}
</script>
Output
a is even number
3. If...else if statement
It evaluates the content only if expression is true from several expressions. The
signature of JavaScript if else if statement is given below.
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else{
//content to be evaluated if no expression is true
}
Example
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
138
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
Output
a is equal to 20
4. Switch Case
The JavaScript switch statement is used to execute one code from multiple
expressions. It is just like else if statement that we have learned in previous page. But
it is convenient than if..else..if because it can be used with numbers, characters etc.
The Syntax of JavaScript switch statement is given below.
switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......
default:
code to be executed if above values are not matched;
}
Example
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
139
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>
Output
B Grade
1. For loop
The JavaScript for loop iterates the elements for the fixed number of times. It should
be used if number of iteration is known. The syntax of for loop is given below.
for (initialization; condition; increment)
{
code to be executed
}
Example
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
140
}
</script>
Output:
1
2
3
4
5
141
do{
code to be executed
}while (condition);
Example
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
Output:
21
22
23
24
25
example:
<script>
var person = {fname:"John", lname:"Doe", age:25};
var text = "";
var x;
for (x in person) {
text += person[x] + " ";
}
</script>
142
3.10 JavaScript Break and Continue
The break statement "jumps out" of a loop.
The continue statement "jumps over" one iteration in the loop.
3. JavaScript Labels
To label JavaScript statements you precede the statements with a label name and a
colon:
label:
statements
The break and the continue statements are the only JavaScript statements that can
"jump out of" a code block.
Syntax:
break labelname;
continue labelname;
The continue statement (with or without a label reference) can only be used to
skip one loop iteration.
143
The break statement, without a label reference, can only be used to jump out of a
loop or a switch.
With a label reference, the break statement can be used to jump out of any code
block:
Continue Example
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var text = "";
var i;
for (i = 0; i < 5; i++) {
if (i === 3) {
continue;
}
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
</script>
Output:
The number is 0
The number is 1
The number is 2
The number is 4
Break Example
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var text = "";
var i;
for (i = 0; i < 5; i++) {
if (i === 3) {
break;
}
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
144
}
</script>
Output:
The number is 0
The number is 1
The number is 2
Syntax
alert(message);
Example
<html>
<head>
<script type="text/javascript">
function show() {
alert("It is an Alert dialog box");
}
</script>
</head>
<body>
<center>
<h1>Hello Students</h1>
145
<h2>Welcome to World</h2>
<p>Click the following button </p>
<input type="button" value="Click Me" onclick="show();" />
</center>
</body>
</html>
Syntax
confirm(message);
Example
<html>
<head>
<script type="text/javascript">
function show() {
var con = confirm ("It is a Confirm dialog box");
if(con == true) {
document.write ("User Want to continue");
}
else {
document.write ("User does not want to continue");
}
}
</script>
</head>
<body>
<center>
146
<h1>Hello Students</h1>
<h2>Welcome to World</h2>
<p>Click the following button </p>
<input type="button" value="Click Me" onclick="show();" />
</center>
</body>
</html>
1. array literal
The syntax of creating array using array literal is given below:
var arrayname=[value1,value2.....valueN];
148
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
Output
Arun
Varun
John
3. array constructor (new keyword)
Here, you need to create instance of array by passing arguments in constructor so
that we don't have to provide value explicitly.
The example of creating object by array constructor is given below.
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
Output
Jai
Vijay
Smith
Function Example
Let’s see the simple example of function in JavaScript that does not has arguments.
Function Without Arguments
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
1. By string literal
The string literal is created using double quotes. The syntax of creating string using
string literal is given below:
var stringname="string value";
Example
<script>
var str="This is string literal";
document.write(str);
</script>
Output:
This is string literal
2. By string object (using new keyword)
The syntax of creating string object using new keyword is given below:
var stringname=new String("string literal");
Here, new keyword is used to create instance of
string.
Example
<script>
var stringname=new String("hello javascript string");
document.write(stringname);
</script>
Output:
151
hello javascript string
String Functions
1. charAt(index)
The JavaScript String charAt() method returns the character at the given index.
<script>
var str="javascript";
document.write(str.charAt(2));
</script>
Output:
V
2. concat(str)
The JavaScript String concat(str) method concatenates or joins two strings.
<script>
var s1="javascript ";
var s2="concat example";
var s3=s1.concat(s2);
document.write(s3);
</script>
Output:
javascript concat example
3. indexOf(str)
The JavaScript String indexOf(str) method returns the index position of the given
string.
<script>
var s1="javascript from Students indexof";
var n=s1.indexOf("from");
document.write(n);
</script>
Output:
11
4. lastIndexOf(str)
152
The JavaScript String lastIndexOf(str) method returns the last index position of the
given string.
<script>
var s1="javascript from Students indexof";
var n=s1.lastIndexOf("java");
document.write(n);
</script>
Output:
16
5. toLowerCase()
The JavaScript String toLowerCase() method returns the given string in lowercase
letters.
<script>
var s1="JavaScript toLowerCase Example";
var s2=s1.toLowerCase();
document.write(s2);
</script>
Output:
javascript tolowercase example
6. toUpperCase()
The JavaScript String toUpperCase() method returns the given string in uppercase
letters.
<script>
var s1="JavaScript toUpperCase Example";
var s2=s1.toUpperCase();
document.write(s2);
</script>
Output:
JAVASCRIPT TOUPPERCASE EXAMPLE
7. slice(beginIndex, endIndex)
153
The JavaScript String slice(beginIndex, endIndex) method returns the parts of string
from given beginIndex to endIndex. In slice() method, beginIndex is inclusive and
endIndex is exclusive.
<script>
var s1="abcdefgh";
var s2=s1.slice(2,5);
document.write(s2);
</script>
Output:
Cde
8. trim()
The JavaScript String trim() method removes leading and trailing whitespaces from the
string.
<script>
var s1=" javascript trim ";
var s2=s1.trim();
document.write(s2);
</script>
Output:
javascript trim
9. split()
It splits a string into substring array,then returns that newly created array.
<script>
var str="This is Students website";
document.write(str.split(" ")); //splits the given string.
</script>
10. valueOf()
valueOf() method is used to find out the primitive value of String object.
<script>
var str="Students";
document.writeln(str.valueOf());
</script>
154
Output:
Students
11. toString()
toString() method returns a string representing the calling object. In other words, this
method provides a string representation of the object and treats same as the valueof()
method.
<script>
var str="Students";
document.writeln(str.toString());
</script>
Output:
Students
3.14.2Math Functions
The JavaScript math object provides several constants and methods to perform
mathematical operation. Unlike date object, it doesn't have constructors.
1. sqrt(n)
The JavaScript math.sqrt(n) method returns the square root of the given number.
Example
Square Root of 17 is: <span id="p1"></span>
<script>
document.getElementById('p1').innerHTML=Math.sqrt(17);
</script>
Output:
Square Root of 17 is: 4.123105625617661
2. random()
The JavaScript math.random() method returns the random number between 0 to 1.
Example
Random Number is: <span id="p2"></span>
<script>
document.getElementById('p2').innerHTML=Math.random
(); </script>
Output:
Random Number is: 0.8503284715996762
155
3. pow(m,n)
The JavaScript math.pow(m,n) method returns the m to the power of n that is m n.
Example
3 to the power of 4 is: <span id="p3"></span>
<script>
document.getElementById('p3').innerHTML=Math.pow(3,4);
</script>
Output:
3 to the power of 4 is: 81
4. floor(n)
The JavaScript math.floor(n) method returns the lowest integer for the given number.
For example 3 for 3.7, 5 for 5.9 etc.
Example
Floor of 4.6 is: <span id="p4"></span>
<script>
document.getElementById('p4').innerHTML=Math.floor(4.6);
</script>
Output:
Floor of 4.6 is: 4
5. ceil(n)
The JavaScript math.ceil(n) method returns the largest integer for the given number.
For example 4 for 3.7, 6 for 5.9 etc.
Example
Ceil of 4.6 is: <span id="p5"></span>
<script>
document.getElementById('p5').innerHTML=Math.ceil(4.6);
</script>
Output:
Ceil of 4.6 is: 5
6. round(n)
The JavaScript math.round(n) method returns the rounded integer nearest for the
given number. If fractional part is equal or greater than 0.5, it goes to upper value 1
otherwise lower value 0. For example 4 for 3.7, 3 for 3.3, 6 for 5.9 etc.
Example
Round of 4.3 is: <span id="p6"></span><br>
156
Round of 4.7 is: <span id="p7"></span>
<script>
document.getElementById('p6').innerHTML=Math.round(4.3);
document.getElementById('p7').innerHTML=Math.round(4.7);
</script>
Output:
Round of 4.3 is: 4
Round of 4.7 is: 5
7. abs(n)
The JavaScript math.abs(n) method returns the absolute value for the given number.
For example 4 for -4, 6.6 for -6.6 etc.
Example
Absolute value of -4 is: <span id="p8"></span>
<script>
document.getElementById('p8').innerHTML=Math.abs(-4);
</script>
Output:
Absolute value of -4 is: 4
8. min()
min() method compares the given numbers and returns the minimum value.
Example
<script>
document.writeln(Math.min(22,34,12,15)+"<br>");
document.writeln(Math.min(-10,-24,-12,-20));
</script>
Output:
12
1.-24
9. max()
max() method compares the given numbers and returns the maximum value.
Example
<script>
document.writeln(Math.max(22,34,12,15)+"<br>");
document.writeln(Math.max(-10,-24,-12,-20));
157
</script>
Output:
34
-10
1. concat()
concat() method combines two or more arrays and returns a new string. This method
doesn't make any change in the original array.
Example
<script>
var arr1=["C","C++","Python"];
var arr2=["Java","JavaScript","Android"];
var result=arr1.concat(arr2);
document.writeln(result);
</script>
Output:
C,C++,Python,Java,JavaScript,Android
2. find()
find() method returns the first element of the given array that satisfies the provided
function condition.
Example
<script>
var arr=[5,22,19,25,34];
var result=arr.find(x=>x>20);
document.writeln(result)
</script>
Output:
22
3. findIndex()
findIndex() method returns the index of first element of the given array that satisfies
the provided function condition. It returns -1, if no element satisfies the condition.
Example
158
<script>
var arr=[5,22,19,25,34];
var result=arr.findIndex(x=>x>20);
document.writeln(result)
</script>
Output:
1
4. indexOf()
indexOf() method is used to search the position of a particular element in a given
array. This method is case-sensitive.
The index position of first element in an array is always start with zero. If an element
is not present in an array, it returns -1.
Example
<script>
var arr=["C","C++","Python","C++","Java"];
var result= arr.indexOf("C++");
document.writeln(result);
</script>
Output:
1
5. isArray()
isArray() method is used to test whether the value passed is an array. If it finds the
passed value is an array, it returns True. Otherwise, it returns False.
Example 1
<script>
document.write(Array.isArray(1,2,3,4)); //Testing the passed values.
</script>
Example 2
<script>
var arr=new Array(1,2,34,4,5);
document.write(Array.isArray(arr)); //It will return true.
</script>
159
6. join()
The JavaScript array join() method combines all the elements of an array into a string
and return a new string. We can use any type of separators to separate given array
elements.
Example
<script>
var arr=["AngularJs","Node.js","JQuery"]
var result=arr.join()
document.write(result);
</script>
7. lastIndexOf()
The JavaScript array lastIndexOf() method is used to search the position of a particular
element in a given array. It behaves similar to indexOf() method with a difference that
it start searching an element from the last position of an array.
The lastIndexOf() method is case-sensitive. The index position of first character in a
string is always start with zero. If an element is not present in a string, it returns -1.
Example
<script>
var arr=["C","C++","Python","C++","Java"];
var result= arr.lastIndexOf("C++");
document.writeln(result);
</script>
Output:
3
8. pop()
pop() method removes the last element from the given array and return that
element. This method changes the length of the original array.
Example
<script>
var arr=["AngularJS","Node.js","JQuery"];
document.writeln("Orginal array: "+arr+"<br>");
document.writeln("Extracted element: "+arr.pop()+"<br>");
document.writeln("Remaining elements: "+ arr);
160
</script>
Output:
Orginal array: AngularJS,Node.js,JQuery
Extracted element: JQuery
Remaining elements: AngulaJS,Node.js
9. push()
push() method adds one or more elements to the end of the given array. This method
changes the length of the original array.
Example
<script>
var arr=["AngularJS","Node.js"];
arr.push("JQuery");
document.writeln(arr);
</script>
Output:
AngularJS,Node.js,JQuery
10. reverse()
reverse() method changes the sequence of elements of the given array and returns the
reverse sequence. In other words, the arrays last element becomes first and the first
element becomes the last. This method also made the changes in the original array.
Example
<script>
var arr=["AngulaJS","Node.js","JQuery"];
var rev=arr.reverse();
document.writeln(rev);
</script>
Output:
JQuery,Node.js,AngulaJS
11. shift()
shift() method removes the first element of the given array and returns that element.
This method changes the length of the original array.
Example
<script>
161
var arr=["AngularJS","Node.js","JQuery"];
var result=arr.shift();
document.writeln(result);
</script>
Output:
AngularJS
12. slice()
slice() method extracts the part of the given array and returns it. This method doesn't
change the original array.
Example
<script>
var arr=["AngularJS","Node.js","JQuery","Bootstrap"]
var result=arr.slice(1,2);
document.writeln(result);
</script>
Output:
Node.js
13. sort()
sort() method is used to arrange the array elements in some order. By default, sort()
method follows the ascending order.
Example
<script>
var arr=["AngularJS","Node.js","JQuery","Bootstrap"]
var result=arr.sort();
document.writeln(result);
</script>
Output:
AngularJS,Bootstrap,JQuery,Node.js
14. unshift()
unshift() method adds one or more elements in the beginning of the given array and
returns the updated array. This method changes the length of the original array.
162
Example
<script>
var arr=["AngularJS","Node.js"];
var result=arr.unshift("JQuery");
document.writeln(arr);
</script>
Output:
JQuery,AngularJS,Node.js
Output:
Today's day: 16
Example 2
<script>
var date=new Date("August 15, 1947 20:22:10");
document.writeln(date.getDate())
</script>
Output:
15
2. getDay()
getDay() method returns the value of day of the week for the specified date on the
basis of local time. The value of the day starts with 0 that represents Sunday.
Example
<script>
var day=new Date();
163
document.writeln(day.getDay());
</script>
Output:
1
3. getHours()
getHours() method returns the hour for the specified date on the basis of local time.
Example
<script>
var hour=new Date();
document.writeln(hour.getHours());
</script>
Output:
15
4. getMilliseconds()
getMilliseconds() method returns the value of milliseconds in specified date on the
basis of local time.
Example
<script>
var milli =new Date();
document.writeln(milli.getMilliseconds());
</script>
Output:
238
5. getMinutes()
getMinutes() method returns the minutes in the specified date on the basis of
local time.
Example
<script>
var min=new Date();
document.writeln(min.getMinutes());
</script>
Output:
164
9
6. getMonth()
getMonth() method returns the integer value that represents month in the specified
date on the basis of local time. The value returned by getMonth() method starts with 0
that represents January.
Example
<script>
var date=new Date();
document.writeln(date.getMonth()+1);
</script>
Output:
7
7. getSeconds()
getSeconds() method returns the seconds in the specified date on the basis of local
time.
Example
<script>
var sec=new Date();
document.writeln(sec.getSeconds());
</script>
Output:
56
8. setHours()
setHours() method is used to set the hour for the specified date on the basis of
local time.
Example
<script>
var hours=new Date();
document.writeln("Current Hour : "+hours.getHours()+"<br>");
hours.setHours(8);
document.writeln("Updated Hour : "+hours.getHours());
165
</script>
Output:
Current Hour : 13
Updated Hour : 8
9. setMilliseconds()
setMilliseconds() method is used to set the milliseconds for a specified date on the
basis of local time.
Example
<script>
var ms=new Date();
document.writeln("Current millisecond : "+ms.getMilliseconds()+"<br>");
ms.setMilliseconds(825);
document.writeln("Updated millisecond : "+ms.getMilliseconds());
</script>
Output:
Current millisecond : 750
Updated millisecond : 825
10. setMinutes()
setMinutes() method is used to set the minutes for a specified date on the basis of
local time.
Example
<script>
var minutes=new Date();
document.writeln("Current Minute : "+minutes.getMinutes()+"<br>");
minutes.setMinutes(32);
document.writeln("Updated Minute : "+minutes.getMinutes());
</script>
Output:
Current Minute : 57
Updated Minute : 32
166
11. toDateString()
toDateString() method returns the date portion of a Date object in the form of string.
Example
<script>
var date=new Date();
document.writeln(date.toDateString());
</script>
Output:
Tue Aug 07 2018
12. toISOString()
toISOString() method returns the string representation of the Date object. The
returned string is in the form of simplified extended ISO format, which is always 24 or
27 characters long.
Example
<script>
var date=new Date();
document.writeln(date.toISOString());
</script>
Output:
2018-08-09T13:01:38.116Z
13. toString()
toString() method returns a Date object in the form of string.
Example
<script>
var date=new Date();
document.writeln(date.toString());
</script>
Output:
Tue Aug 07 2018 16:57:22 GMT+0530 (India Standard Time)
14. toTimeString()
toTimeString() method returns the time portion of a Date object in the form of string.
Example
<script>
167
var time=new Date();
document.writeln(time.toTimeString());
</script>
Output:
10:19:29 GMT+0530 (India Standard Time)
3.16 JS Events
The change in the state of an object is known as an Event. In html, there are various
events which represents 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. Thus, js handles the HTML events via Event Handlers.
For example, when a user clicks over the browser, add js code, which will execute
the task to be performed on the event.
Some of the JAVASCRIPTS events and their event handlers are:
1. Mouse events:
168
mousemove onmousemove When the mouse movement takes place.
2. Keyboard events:
Event Event
Performed Handler Description
Keydown & onkeydown & When the user press and then
Keyup onkeyup release the key
3. Form events:
Event
Performed Event Description
Handler
4. Window/Document events
Examples
1.Click Event
<html>
<head> Javascript Events </head> <body>
<script language="Javascript" type="text/Javascript">
function clickevent()
{
document.write("At College ");
}
</script>
<form>
<input type="button" onclick="clickevent()" value="Where are you?"/> </form>
</body>
</html>
2.MouseOver Event
<html>
<head>
<h1> Javascript Events </h1> </head>
<body>
<script language="Javascript" type="text/Javascript">
function mouseoverevent()
{
alert("Welcome to World College");
}
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>
3.Focus Event
<html>
<head> Javascript Events</head> <body>
<h2> Enter something here</h2>
170
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
function focusevent()
{
document.getElementById("input1").style.background=" aqua";
}
</script>
</body>
</html>
4.Keydown Event
<html>
<head> Javascript Events</head> <body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
</script>
</body>
</html>
5.Load event
<html>
6.MouseOut Event
<html>
<head>
<h1> Javascript Events </h1> </head>
<body>
<script language="Javascript" type="text/Javascript">
function mouseoutevent()
{
alert("Welcome to World College");
171
}
</script>
<p onmouseout="mouseoutevent()"> Keep cursor over me</p>
</body>
</html>
7.MouseDown Event
<html>
<head>
<h1> Javascript Events </h1> </head>
<body>
<script language="Javascript" type="text/Javascript"> function myfunction()
{
alert("Welcome to World College");
}
</script>
<p onmouseout="myfunction()"> Keep cursor over me</p> </body>
</html>
8.Mouseup Event
<html>
<head>
<h1> Javascript Events </h1> </head>
<body>
<script language="Javascript" type="text/Javascript">
function myfunction()
{
alert("Welcome to World College");
}
</script>
<p onmouseup="myfunction()"> Keep cursor over me</p>
</body>
</html>
9.MouseMove Event
<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script language="Javascript" type="text/Javascript">
function myfunction()
172
{
alert("Welcome to World College");
}
</script>
<p onmousemove="myfunction()"> Keep cursor over me</p>
</body>
</html>
10.KeyUp Event
<html>
<head> Javascript Events</head>
<body>
11.Submit Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<form method="post" action="#" onsubmit="myFunction()">
<input type="text" id="input1" />
<input type="submit" value="press">
</form>
<script>
function myFunction()
{
document.getElementById("input1");
alert("Form submited");
}
</script>
</body>
173
</html>
12.Blur Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onblur="blurevent()"/>
<script>
function blurevent()
{
document.getElementById("input1").style.background=" red";
}
</script>
</body>
</html>
13.Change Event
<html>
<body>
select city: <select onchange="myFunction(this.value)">
<option>rajkot</option>
<option>surat</option>
<option>ahmedabad</option>
<option>vadodara</option>
</select>
<script>
function myFunction(val) {
alert("The value changed. The new value is: " + val);
}
</script>
</body>
</html>
14.Unload Event
<html>
<body onunload="myFunction()">
<h1>Welcome to my Home Page</h1>
<p>Close this window or press F5 to reload the page.</p> <p><strong>Note:</strong>
Due to different browser settings, this event may not always work as expected.</p>
<script>
function myFunction()
174
{ alert("Thank you ");
}
</script>
</body>
</html>
15.Resize Event
<html>
<body onresize="myFunction()">
<h1>Welcome to my Home Page</h1>
<script>
function myFunction()
{
alert("window resize");
}
</script>
</body>
</html>
According to W3C - "The W3C Document Object Model (DOM) is a platform and
language-neutral interface that allows programs and scripts to dynamically access and
update the content, structure, and style of a document."
Properties of document object
Let's see the properties of document object that can be accessed and modified by
the document object.
Method Description
write("string") writes the given string on the doucment.
175
writes the given string on the doucment with
writeln("string") newline character at the end.
In this example, we are going to get the value of input text by user. Here, we are using
document.form1.name.value to get the value of name field. Here, document is the
root element that represents the html document.
form1 is the name of the form.
name is the attribute name of the input text.
value is the property, that returns the value of the input text.
Let's see the simple example of document object that prints name with welcome
message.
<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>
176
It is important to validate the form submitted by the user because it can have
inappropriate values. So, validation is must to authenticate user.
JavaScript provides facility to validate the form on the client-side so data processing
will be faster than server-side validation. Most of the web developers prefer JavaScript
form validation.
Through JavaScript, we can validate name, password, email, date, mobile numbers and
more fields.
<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>
178
var password=document.f1.password.value;
var status=false;
if(name.length<1){
document.getElementById("nameloc").innerHTML=
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>
<form name="f1" action="#" onsubmit="return validate()">
<table>
<tr><td>Enter Name:</td><td><input type="text"
name="name"/> <span id="nameloc"></span></td></tr>
<tr><td>Enter Password:</td><td><input type="password"
name="password"/> <span id="passwordloc"></span></td></tr>
<tr><td colspan="2"><input type="submit" value="register"/></td></tr>
</table>
</form>
<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/>
<input type="submit" value="register">
</form>
180
4.Introduction to PHP as Programming Language
PHP
• PHP is a server side scripting that was designed for creating dynamic websites.
• PHP script runs on a web server.
• PHP is loosely type language because it converts a data type of variable
automatically.
• PHP is powerful scripting language that can be run in the command line of any
computer with PHP installed.
• However, PHP alone isn't enough in order to build dynamic web sites.
182
Apache
• To use PHP on a web site, you need a server that can process PHP scripts. Apache is
a free web Server that, once installed on a computer, allows developers to test PHP
scripts locally; this makes it an invaluable piece of your local development
environment.
• Like all web servers, Apache accepts an HTTP request and serves an HTTP response.
• Apache is open source free software distributed by the Apache Software
Foundation.
MySQL
• Additionally, dynamic websites are dependent on stored information that can be
modified quickly and easily; this is the main difference between a dynamic site and a
static HTML site.
• However, PHP doesn't provide a simple, efficient way to store data. This is where a
relational database management system like MySQL comes into play.
• PHP provides native support for it and the database is free, open-source project. •
MySQL is a relational database management system (DBMS). Essentially, this means
that MySQL allows users to store information in a table-based structure, using rows
and columns to organize different pieces of data.
184
</script>
This syntax is removed after PHP 7.0.0.
4. ASP style tags
<%
echo "Hello World";
%>
This syntax is removed after PHP 7.0.0.
Echo
INPUT OUTPUT
echo(“Hello World”); Hello World
echo "Hello World"; Hello World
echo "Hello", "World"; Hello World
echo("Hello", "World"); Invalid Argument
• The command print is very similar to echo, with two important differences:
o print can accept only one argument.
o print returns a value, which represents whether the print statement succeeded.
• The value returned by print will be 1 if the printing was successful and 0 if
unsuccessful.
For example, the following two lines will print exactly the same thing: print("3.14159
"); //print a string
print(3.14159); //print a number
Compound data
Compound data is data that can contain more than one value.
Special data
• Finally, PHP supports two special data types, so called because they don't contain
scalar or compound data as such, but have a specific meaning:
Gettype
• This function is use to get the type of the variable that means this function will
return the type of the PHP variable.
• Syntax: gettype(arg)
• The above function will return a string representing the type of arg: integer, float,
187
string, array, and object, NULL or unknown type.
Example:
<?php
$a=10;
echo gettype($a);
$b="rahul";
echo gettype($b);
?>
Output:
integer string
settype
• The settype() function is used to set the type of a variable.
• Syntax: settype(var_name, var_type)
• var_name: The variable being converted.
• var_type: Type of the variable. Possible values: boolean, integer, float, string, array,
object, null.
Example:
$a=65;
settype($a, "string");
casting
• If you want to change type temporary, i.e., want to use inside an expression, you
can use type casting.
• Syntax: (type)$variable
• Where type is a type of variable you wish to cast to.
Example:
$var1= 10; //integer
188
$var2= (string) $var1; // Svarl is now set to 10 (string)
Logical Operators
• The PHP logical operators are used to combine conditional statements.
Assignment Operators
• The PHP assignment operators are used with numeric values to write a value to a
variable. The basic assignment operator in PHP is "=". It means that the left operand
set to the value of the assignment expression on the right.
String Operators
• PHP has two operators that are specially designed for strings.
189
Increment / Decrement Operators
• The PHP increment operators are used to increment a variable's value.
• The PHP decrement operators are used to decrement a variable's value.
Conditional Operator
• There is one more operator called conditional operator. This first evaluates an
expression for a true or false value and then execute one of the two given statements
depending upon the result of the evaluation. The conditional operator has this syntax:
Example:
<?php
$number = 21;
$result= ($number % 2 == 0) ? "Number is Even" : "Number is Odd";
echo $result;
?>
Output:
Number is Odd
Comparison Operators
• The PHP comparison operators are used to compare two values (number or string):
190
Bitwise Operators
• Bitwise operators allow evaluation and manipulation of specific bits within an
integer.
191
Default is false.
Example 1:
o The example below creates a constant with a case-sensitive name.
<?php
define("GREETING", "PHP is a scripting language");
echo GREETING;
?>
Output: PHP is a scripting language
Example 2:
o The example below creates a constant with a case-insensitive name.
<?php
define("GREETING", "PHP is a scripting language ", true);
echo greeting;
?>
Output:
PHP is a scripting language
constant() function
• The constant() function returns the value of a constant.
• Syntax: constant(constant)
o Constant: Required. Specifies the name of the constant.
Example:
<?php
define("GREETING", "Hello you! How are you today?");
echo constant("GREETING");
?>
Output: Hello you! How are you today?
192
4.15 Flow control statements
• Conditional statements are used to perform different actions based on different
conditions.
• In PHP we have the following conditional statements:
o if statement - executes some code only if a specified condition is true
o if...else statement - executes code if a condition is true and another code if the
condition is false
o if...elseif....else statement - specifies a new condition to test, if the first condition is
false
o switch statement - selects one of many blocks of code to be executed
4.15.1 if Statement
• The if statement is used to execute some code only if a specified condition is true.
• Syntax:
if (condition)
{
code to be executed if condition is true;
}
• Example:
<?php
$number = 20;
if ($number % 2 == 0)
echo "Number is Even";
if ($number % 2 != 0)
echo "Number is Odd";
?>
Output: Number is Even
193
}
else
{
code to be executed if condition is false;
}
• Example:
<?php
$number = 20;
if ($number % 2 == 0)
echo "Number is Even";
else
echo "Number is Odd";
?>
Output:
Number is Even
Example: <?php
$a=6;
switch($a)
{
case 1: echo "Monday"; break;
case 2: echo "Tuesday"; break;
case 3: echo "Wednesday"; break;
case 4: echo "Thursday"; break;
case 5: echo "Friday"; break;
case 6: echo "Saturday"; break;
case 7: echo "Sunday"; break;
default: echo "Wrong Choice";
}
Output: Saturday
195
4.16 Loops
• You want the same block of code to run over and over again. Instead of adding
several almost equal code-lines in a script, we can use loops to perform a task like
this.
• Loops execute a block of code while the specified condition is true.
In PHP, we have the following looping statements:
o while - loops through a block of code as long as the specified condition is true.
o do...while - loops through a block of code once, and then repeats the loop as long
as the specified condition is true.
o for - loops through a block of code a specified number of times.
o foreach - loops through a block of code for each element in an array.
196
condition, and repeat the loop while the specified condition is true.
• Syntax:
do
{
code to be executed;
} while (condition is true);
• Example:
<?php
$x = 1;
do
{
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
Output:
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
198
<?php
$i = 0;
while ($i<100)
{
if ($i > 5)
break;
echo $i." ";
$i=$i+1;
}
?>
Output: 0 1 2 3 4 5 6
• Example (Continue):
The following code prints the number 0 to 9, except 5.
<?php
for ($i = 0; $i<10; $i++)
{
if ($i == 5)
{
continue;
}
echo $i." ";
}
?>
Output: 012346789
199
5.PHP CONCEPTS
5.1 Arrays
• An array is a single variable that can hold more than one value at once.
• You can think of an array as a list of values.
• Each value within an array is called an element, and each element is referenced by
its own index, which is unique to that array.
• To access an elements value – whether you are creating, reading, writing, or
deleting the element you use that elements index.
200
5.1.2 Functions of array:
Length of an Array
•The count() function is used to return the length (the number of elements) of an
array.
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
Output: 3
Output: B
201
• In Numeric Array you can use for, while or do while loop to iterate through each
element in array because in numeric array key values are consecutive.
Changing Elements
• You can also change value of element using index.
Example:
<?php
$myarray=array("Apache", "MySQL", "PHP");
$myarray[1]="Oracle";
for($i=0; $i<3; $i++)
{
echo $myarray[$i]."<br>";
}
?>
Output: Apache Oracle PHP
Add Elements to Array
• The array_push() function inserts one or more elements to the end of an array.
Syntax: array_push(array,value1, value2...)
o array: Required. Specifies an array.
o value1: Required. Specifies the value to add.
o value2: Optional. Specifies the value to add.
Example:
<?php
$myarray=array("Apache", "MySQL", "PHP");
print_r($myarray);
echo '<br>";
$myarray[]="Oracle";
print_r($myarray);
202
echo "<br>";
array_push($myarray,"Java",".Net");
print_r($myarray);
?>
Output: Array ( [0] => Apache [1] => MySQL [2] =>PHP)
Array ( [0] => Apache [1] => MySQL [2] => PHP [3] => Oracle )
Array ( [0] => Apache [1] => MySQL [2] => PHP (3] => Oracle [4] => Java [5] =>.Net)
Output:
Array ( [0] => red [1] => green)
Searching Element
• The array_search() function search an array for a value and returns the key.
• Syntax: array_search(value,array,strict)
o value: Required. Specifies the value to search for.
o array: Required. Specifies the array to search in.
o strict: Optional. If this parameter is set to TRUE, then this function will search for
identical elements in the array.
Example: <?php
$a=array("A"=>"5","B"=>5);
echo array_search(5,$a);
echo array_search(5,$a,true);
?>
Output:
A
B
• The in_array() function searches an array for a specific value.
• Syntax: in_array(search,array, type)
o search: Required. Specifies the what to search for
o array: Required. Specifies the array to search
o type: Optional. If this parameter is set to TRUE, the in_array() function searches for
the specific type in the array.
Example:
204
<?php
$people=array("Peter", "Joe", "Glenn", 23);
if (in_array("23",$people))
{
echo "Match found<br>";
}
else
{
echo "Match not found<br>";
}
if (in_array("23", $people, TRUE))
{
echo "Match found<br>";
}
else
{
echo "Match not found<br>";
}
?>
Output:
Match found
Match not found
Sorting Array
• sort() - sort arrays in ascending order
• rsort() - sort arrays in descending order
• asort() - sort associative arrays in ascending order, according to the value
• ksort() - sort associative arrays in ascending order, according to the key
205
• arsort() - sort associative arrays in descending order, according to the value
• krsort() - sort associative arrays in descending order, according to the key
Example: <?php
$srtArray=array(2,8,9,5,6,3);
for ($i=0; $i<count($srtArray); $i++)
{
for ($j=0; $j<count($srtArray); $j++)
{
if ($srtArray[$j] > $srtArray[$i])
{
$tmp = $srtArray[$i];
$srtArray[$i] = $srtArray[$j];
$srtArray[$j] = $tmp;
}
}
}
foreach($srtArray as $item)
{
echo $item."<br>\n";
}
?>
Output: 235 6 8 9
206
Output: 235689
2) Associative Array
• The associative part means that arrays store element values in association with key
values rather than in a strict linear index order.
• If you store an element in an array, in association with a key, all you need to retrieve
it later from that array is the key value.
• Key may be either numeric or string.
• You can use array() function to create associative array.
• Syntax: $array_name=array(key1=>value1, key2=>value2...... keyN => valueN);
• There are two ways to create an associative array:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
OR
$age["Peter"] = "35";
$age["Ben"] = "37";
$age["Joe"] = "43";
You can refer to individual element of an array in PHP using its key value. Example:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Ben:"$age["Ben");
?>
Output: Ben:37
• In associative array you cannot use for, while or do...while loop to iterate through
each element in array because in Associative array key value are not consecutive.
• So you have to use foreach loop.
Example: <?php
$myarray=array("Name"=>"James", "Age"=>25, "Gender"=>"Male");
foreach($myarray as $item) {
207
echo $item."<br>";
?>
Output: James
25
Male
3) Multidimensional Array
• Earlier, we have described arrays that are a single list of key/value pairs.
• However, sometimes you want to store values with more than one key.
• This can be stored in multidimensional arrays.
• A multidimensional array is an array containing one or more arrays.
• PHP understands multidimensional arrays that are two, three, four, five, or more
levels deep.
• First, take a look at the following table:
Example:
<?php
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
);
for ($row = 0; $row < 3; $row++)
{
echo "<br>";
for ($col = 0; $col < 3; $col++)
{
echo $cars($row][$col]." ";
}
208
}
5.2 User Defined Functions
• Besides the built-in PHP , we can create our own .
• A function is a block of statements that can be used repeatedly in a program.
• A function will not execute immediately when a page loads.
• A function will be executed by a call to the function.
Create a User Defined Function
• A user defined function declaration starts with the word "function".
• Syntax:
function functionName()
{
Code to be executed;
}
Example: <?php
function write Msg()
{
echo "Hello world!";
}
writeMsg(); // call the function
?>
Output: Hello world!
Call-by-Value (Pass-by-Value)
• The default behavior for user-defined in PHP is call-by-value.
• Call by value means passing the value directly to a function. The called function uses
the value in a local variable; any changes to it do not affect the source variable.
Example:
<?php
function swap($num1, $num2)
{
$temp = $num1;
$num1=$num2;
$num2=$temp;
}
$num1=10;
$num2=20;
echo "Before Swap"."<br>";
echo "num1="$num1.'<br>";
echo "num2=".$num2."<br>";
swap($num1,$num2);
echo "After Swap","<br>";
echo "num1=".$num1.'<br>";
210
echo "num2="$num 2.5<br>";
Output:
Before Swap num1=10 num2=20
After Swap num1=10 num2=20
Call-by-Reference (Pass-by-Reference)
• Call by reference means passing the address of a variable where the actual value is
stored.
• The called function uses the value stored in the pass address; any changes to it do
affect the source variable.
Example:
<?php
function swap(&$num1, &$num2)
{
$temp = $num1;
$num1=$num2;
$num2=$temp;
}
$num1=10;
$num2=20;
echo "Before Swap"."<br>";
echo "num1="$num1.'<br>";
echo "num2="$num2."<br>";
swap($num1,$num2);
echo "After Swap"."<br>";
echo "num1="$num1."<br>";
echo "num2="$num 2."<br>";
?>
Output:
Before Swap num1=10 num2=20
After Swap num1=20 num2=10
Global Variable :
• A variable declared outside a function has a global scope and can only be accessed
outside a function.
• The global keyword is used to access a global variable from within a function.
• To do this, use the global keyword before the variables (inside the function). global
$x;
Example:
<?php
$x = 5; // global scope
function myTest()
{
}
myTest();
echo "Variable x outside function is: $x";
?>
Output:
Variable x outside function is: 5
Static Variable
212
• Normally, when a function is completed/executed, all of its variables are deleted.
• However, sometimes we want a local variable not to be deleted. We need it for a
further job.
To do this, use the static keyword when you first declare the variable.
Example:
<?php
function myTest()
{
static $x = 0;
echo $x;
$x++;
}
myTest();
echo "<br>";
myTest();
echo "<br>";
myTest();
?>
Output:
0
1
2
• Then, each time the function is called, that variable will still have the information it
contained from the last time the function was called.
ord
strtolower
• Converts a string to lowercase letters.
• Syntax: strtolower(string)
Example:
<?php
echo strtolower("HELLO");
?>
Output:
hello
strtoupper
• Converts a string to uppercase letters.
• Syntax: strtoupper(string)
Example:
<?php
echo strtoupper("hello");
214
?>
Output: HELLO
strlen
• Returns the length of a string.
• Syntax: strlen(string)
Example:
<?php
echo strlen("hello hi");
?>
Output: 8
Itrim
• Removes whitespace or other predefined characters from the left side of a string.
• Syntax: Itrim(string,charlist)
o charlist: Optional. Specifies which characters to remove from the string. o If
omitted, all of the following characters are removed:"\0" - NULL, "\t" – tab, "\n" - new
line,
"\XOB" - vertical tab, "\r" - carriage return, "" - white space. Example: <?php
$str="Hello"; echo Itrim($str, "H").'<br>"; $str=" Hello";
echo Itrim($str); ?> Output: ello Hello
rtrim
• Removes whitespace or other predefined characters from the right side of a string.
• Syntax: rtrim(string, charlist)
o charlist: Optional. Specifies which characters to remove from the string.
o If omitted, all of the following characters are removed:
"10" - NULL,
"\t" – tab,
"\n" - new line,
"\XOB" - vertical tab,
"\r" - carriage return,
"" - white space.
Example:
<?php
$str="Hello";
echo rtrim($str,"o").'<br>";
$str="Hello";
echo rtrim($str);
215
?>
Output: Hell Hello
trim
• Removes whitespace and other predefined characters from both sides of a string.
• Syntax: trim(string,charlist)
o charlist: Optional. Specifies which characters to remove from the string.
o If omitted, all of the following characters are removed:"\0" – NULL, "\t" – tab, "\n" –
new line, "\XOB" - vertical tab, "\r" - carriage return,"" - white space. Example:
<?php
$str="Hello";
echo trim($str,"o").'<br>";
$str=" Hello ";
echo trim($str);
?>
Output: Hell Hello
substr
• Returns a part of a string.
• Syntax: substr(string,start,length)
o start: Required. Specifies where to start in the string.
A positive number - Start at a specified position in the string.
A negative number - Start at a specified position from the end of the string.
0- Start at the first character in string.
o length: Optional. Specifies the length of the returned string.
Default is to the end of the string.
A positive number - The length to be returned from the start parameter.
Negative number - The length to be returned from the end of the string.
Example:
<?php
// Positive numbers:
216
echo substr("Hello world",0,10)."<br>";
echo substr("Hello world",1,8)."<br>";
echo substr("Hello world",0,5).'<br>";
echo substr("Hello world",6,6).'<br>";
echo "<br>";
// Negative numbers:
echo substr("Hello world",0,-1).'<br>";
echo substr("Hello world",-10,-2).'<br>";
echo substr("Hello world",0,-6).'<br>";
?>
Output:
Hello worl
ello wor
Hello
world
Hello worl
ello wor
Hello
strcmp
• Compares two strings (case-sensitive).
• strcmp function returns 0 - if the two strings are equal, negative - if string1 is less
than string2 and positive - if string1 is greater than string2.
• Syntax: strcmp(string1, string2)
Example:
<?php
echo strcmp("Hello world!","Hello world!").'<br>"; // the two strings are equal echo
strcmp("Hello world!","Hello")."<br>"; // string1 is greater than string2 echo
strcmp("Hello world!","Hello world! Hello!"); // string1 is less than string 2
Output:
0
7
-7
strcasecmp
• Compares two strings (case-insensitive)
• strcasecmp function returns: 0 - if the two strings are equal, negative - if string1 is
less than string2 and positive - if string1 is greater than string2.
• Syntax: strcasecmp(string1, string2)
217
Example:
<?php
echo strcasecmp("Hello world!","HELLO WORLD!").'<br>";
// The two strings are equal
echo strcasecmp("Hello world!", "HELLO")."<br>";
// String1 is greater than string 2
echo strcasecmp("Hello world!","HELLO WORLD! HELLO!");
// String1 is less than string2 ?>
Output:
0
7
-7
strpos
• Finds the position of the first occurrence of a string inside another string. (case-
sensitive)
• Syntax: strpos(string,find,start)
o string: Required. Specifies the string to search.
o find: Required. Specifies the string to find.
o start: Optional. Specifies where to begin the search.
Example:
<?php
echo strpos("hello","e");
echo strpos("hello","1");
echo strpos("hellohello","T",5);
?>
Output:
1
2
7
218
strrpos
• Finds the position of the last occurrence of a string inside another string. (case-
sensitive)
• Syntax: strrpos(string, find,start)
o string: Required. Specifies the string to search.
o find: Required. Specifies the string to find.
o start: Optional. Specifies where to begin the search.
Example:
<?php
echo strrpos("hello","l");
echo strrpos("hellohello","I", 5);
?>
Output:
3
5
strrpos
• Finds the position of the first occurrence of a string inside another string. (case-
insensitive)
• Syntax- stripos(string, find, start)
o string: Required. Specifies the string to search.
o find: Required. Specifies the string to find.
o start: Optional. Specifies where to begin the search.
Example:
<?php
echo stripos("hello","L");
echo stripos("hellohello", "L",4); ?>
Output:
2
219
7
strripos
• Finds the position of the last occurrence of a string inside another string. (case-
insensitive)
• Syntax:- strrpos(string, find,start)
o string: Required. Specifies the string to search.
o find: Required. Specifies the string to find.
o start: Optional. Specifies where to begin the search.
Example:
<?php
echo strripos("hello", "L");
echo strripos("hellohello","L",4);
?>
Output:
3
8
strstr
• Searches for the first occurrence of a string inside another string. (case-sensitive)
• Syntax: strstr(string,search, before_search)
o string: Required. Specifies the string to search.
o search: Required. Specifies the string to search for. If this parameter is a
number, it will search for the character matching the ASCII value of the number.
o before_search: Optional. A boolean value whose default is "false". If set to
"true", it returns the part of the string before the first occurrence of the search
parameter.
Example:
<?php
echo strstr("Hello world!",111);
220
echo strstr("Hello world!","wo");
echo strstr("Hello world!","world", true);
?>
Output:
o world!
world!
Hello
stristr
• Searches for the first occurrence of a string inside another string. (case-insensitive)
• Syntax: stristr(string,search)
o string: Required. Specifies the string to search.
o search: Required. Specifies the string to search for. If this parameter is a
number, it will search for the character matching the ASCII value of the number.
o before_search: Optional. A boolean value whose default is "false". If set to
"true", it returns the part of the string before the first occurrence of the search
parameter.
Example:
<?php
echo stristr("Hello world!",87);
echo stristr("Hello world!","WO");
echo stristr("Hello world!","WORLD", true);
?>
Output: world! world! Hello
str_replace
• Replaces some characters in a string (case-sensitive).
• Syntax: str_replace(find,replace,string,count)
o find: Required. Specifies the value to find
o replace: Required. Specifies the value to replace the value in find
221
o string: Required. Specifies the string to be searched
o count: Optional. A variable that counts the number of replacements Example:
<?php
echo str_replace("world","Peter","Hello world!");
?>
Output: Hello Peter!
strrev
• Reverses a string.
• Syntax: strrev(string)
Example:
<?php
echo strrev("hello");
?>
Output: olleh
222
Syntax: ceil(number)
Example: <?php
echo ceil(0.60).'<br>";
echo ceil(5)."<br>";
echo ceil(-4.9);
?>
Output:
1
5
-4
floor
• Rounds a number DOWN to the nearest integer, if necessary.
• Syntax: floor(number)
Example:
<?php
echo floor(0.60)."<br>";
echo floor(5).'<br>";
echo floor (4.9);
?>
Output:
0
5
4
round
• Rounds a floating-point number.
• Syntax: round(number,precision)
o precision: Optional. The number of digits after the decimal point
223
Example: <?php
echo round(5.335,2).'<br>";
echo round(0.49);
?>
Output:
5.34
0
fmod
• Returns the remainder (modulo) of x/y.
Syntax: fmod(x,y)
Example: <?php
echo fmod(5,2);
?>
Output: 1
min
• Returns the number with the lowest value from specified numbers.
• Syntax: min(x1,x2,X3...) Or min(array_values)
Example:
<?php
echo min(-2,4,-6,8,10). "<br>";
echo min(array(4,6,8,10));
?>
Output:
-6
4
max
• Returns the number with the highest value from specified numbers.
224
• Syntax: max(x1,x2,X3...) Or max(array_values)
Example:
<?php
echo max(-2,4,-6,8,10). "<br>";
echo max(array(4,6,8,10));
?>
Output:
10
10
pow
• Returns the value of x to the power of y.
Syntax: pow(x,y) Example: <?php
echo pow(5,2);
?>
Output:
25
sqrt
• Returns the square root of a number x.
• Syntax: sqrt(number)
Example: <?php
echo sqrt(25);
Output: 5
rand
• Returns a random integer.
• Syntax: rand() or rand(min, max)
o min: Optional. Specifies the lowest number to be returned. Default is 0.
o max: Optional. Specifies the highest number to be returned. Default is
225
getrandmax().
Example:
<?php
echo rand().'<br>";
echo rand(40,500); ?>
Output:
18269
417
fwrite()
• The fwrite() writes to an open file.
229
• The function will stop at the end of the file or when it reaches the specified length,
whichever comes first.
• This function returns the number of bytes written, or FALSE on failure.
•Syntax: fwrite(file,string, length)
o file: Required. Specifies the open file to write to
o string: Required. Specifies the string to write to the open file
o length: Optional. Specifies the maximum number of bytes to write
Example:
<?php
$file = fopen("test.txt","w");
echo fwrite($file, "Hello World. Testing!");
fclose($file);
?>
fread()
• The fread() reads from an open file.
• Syntax: fread(file, length)
o file: Required. Specifies the open file to read from
o length: Required. Specifies the maximum number of bytes to read
Example:
<?php
$file = fopen("test.txt","r");
fread($file,"10");
fclose($file);
?>
fclose()
• The fclose() function is used to close an open file.
230
• The fclose() requires the name of the file (or a variable that holds the filename).
Syntax: fclose(file)
Example: <?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>
231
6.Advanced PHP
6.1 $_GET and $_POST method
• There are two ways the browser client can send information to the web server.
o The GET Method
o The POST Method
• Both GET and POST create an array (e.g. array ( key => value, key2 => value2, key3
=> value3, ...)).
• This array holds key/value pairs, where keys are the names of the form controls and
values are the input data from the user.
• Both GET and POST are treated as $_GET and $_POST. These are superglobals,
which means that they are always accessible, regardless of scope - and you can access
them from any function, class or file without having to do anything special.
• $_GET is an array of variables passed to the current script via the URL parameters.
• $_POST is an array of variables passed to the current script via the HTTP POST
method.
232
Every query string starts with in URL.
Data is limited to max length of query string.
Note: GET should NEVER be used for sending passwords or other sensitive
information!
Submitting and accessing form value using GET
OR Passing variable through URL
Example
<html>
<body>
<form action="welcome_get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
welcome_get.php
<html>
<body>
<?php
$name=$_GET['name'];
$email= $_GET['email'];
echo "welcome "$name."<br>";
echo "Your email address is: ".$email;
?>
</body>
</html>
The output could be something like this: Welcome Peter
233
Your email address is: [email protected]
The POST Method
Information sent from a form with the POST method is invisible to others (all
names/values are embedded within the body of the HTTP request).
POST has no limits on the amount of information to send.
However, because the variables are not displayed in the URL, it is not possible
to bookmark the page.
The POST method can be used to send ASCII as well as binary data.
POST may be used for sending sensitive data.
It is more secured but slower as compared to GET.
It can post unlimited form variables.
Submitting and accessing form value using POST
Example
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
When the user fills out the form above and clicks the submit button, the form
data is sent for processing to a PHP file named "welcome.php".
The form data is sent with the HTTP POST method.
To display the submitted data you could simply echo all the variables. The
"welcome.php" looks like this:
welcome.php
<html>
<body>
<?php
234
$name=$_POST['name'];
$email= $_POST['email'];
echo "welcome ".$name."<br>";
echo "Your email address is: ".$email;
?>
</body>
</html>
The output could be something like this: Welcome Peter
Your email address is: [email protected]
236
Example
Retrieve Cookies.php
<?php
$cookiename =$_COOKIE['cookiename'];
echo "Cookie named:".$cookiename;
?>
In the following example we use the isset() function to find out if a cookie has been
set.
Retrieve Cookies.php
<?php
if(isset($_COOKIE['cookiename ']))
echo " Cookie ".$_COOKIE[' cookiename '). " is not set!" ;
else
echo " Cookie".$_COOKIE['cookiename ']." is set!";
?>
Removing Cookie/ Delete Cookie
• When deleting a cookie you should assure that the expiration date is in the past.
Delete Cookies.php
<?php
setcookies' cookiename '' cookievalue', time()-60*60*24*5);
echo "Cookie is deleted";
?>
237
PHP Session Variables
When you are working with an application, you open it, do some changes and
then you close it.
This is much like a Session. The computer knows who you are. It knows when
you start the application and when you end.
But on the internet there is one problem: the web server does not know who
you are and what you do because the HTTP address doesn't maintain state.
A PHP session solves this problem by allowing you to store user information on
the server for later use (i.e. username, shopping items, etc). However, session
information is temporary and will be deleted after the user has left the website.
If you need a permanent storage you may want to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor and store variables
based on this UID. The UID is either stored in a cookie or is propagated in the
URL.
Starting Session
Before you can store user information in your PHP session, you must first start
up the session.
A session is started with the session_start() function.
The session_start() function must appear BEFORE the <html> tag.
<?php
session_start();
?>
<html>
<body>
</body>
</html>
The code above will register the user's session with the server, allow you to
start saving user information, and assign a UID for that user's session.
238
<head>
<title>Session Demo</title>
</head>
<body>
<form name="formname" method="POST" action="SessionDemo Process.php">
User Name:<input type="text" name="username"/><br/>
Password:<input type="password" name="pass"/><br/>
<input type="submit" name="submit" value="Save"/>
</form>
</body>
</html>
SessionDemo Process.php
<?php
Session_start();
$uname = $_POST['username'];
$pwd = $_POST['pass'];
if($uname=="admin" and $pwd=="123")
{
$_SESSION['username']=$uname;
header(“location:Welcome.php?un=”$_SESSION[‘ username’]);
}
else
{
echo "enter correct username and password";
}
?>
Welcome.php
<?php
Session_start();
if(isset($_SESSION['username']))
echo "Welcome:".$_SESSION['username'];
else
header("location:SessionDemo.php");
239
?>
<html>
<head>
<title>Session Demo</title>
</head>
<body>
<a href="Logout.php">Logout</a>
</body>
</html>
Destroying a Session
If you wish to delete some session data, you can use the unset() or the
session_destroy() function.
The unset() function is used to free the specified session variable.
You can also completely destroy the session by calling the session_destroy()
function.
Note: session_destroy() will reset your session and you will lose all your stored
session data.
Example Logout.php
<?php
Session_start();
session_destroy();
header("location:Session Demo.php");
?>
6.5 MySQL
- MySQL is a database system used on the web
- MySQL is a database system that runs on a server
- MySQL is ideal for both small and large applications
- MySQL is very fast, reliable, and easy to use
- MySQL uses standard SQL
- MySQL compiles on a number of platforms
- MySQL is free to download and use
- MySQL is developed, distributed, and supported by Oracle Corporation
Databases are useful for storing information categorically. A company may have
a database with the following tables:
Employees
240
Products
Customers
Orders
Database Queries
A query is a question or a request.
We can query a database for specific information and have a recordset
returned. Look at the following query (using standard SQL):
SELECT LastName FROM Employees
The query above selects all the data in the "LastName" column from the
"Employees" table.
DML is short name of Data Manipulation Language which deals with data
manipulation and includes most common SQL statements such SELECT, INSERT,
UPDATE, DELETE, etc., and it is used to store, modify, retrieve, delete and
update data in a database.
Ex2.
Delete from students where id=02
This statement delete all record with id=02
6.7 Database
A database is a separate application that stores a collection of data.
Other kinds of data stores can 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.
242
So nowadays, we use relational database management systems (RDBMS) to
store and manage huge volume of data. This is called relational database
because all the data is stored into different tables and relations are established
using primary keys or other keys known as foreign keys.
A Relational DataBase Management System (RDBMS) is a software that −
Enables you to implement a database with tables, columns and indexes.
Guarantees the Referential Integrity between rows of various tables.
Updates the indexes automatically.
Interprets an SQL query and combines information from various tables.
6.9 MySQLi
1)mysqli_connect()
PHP provides mysqli_connect() function to open a database connection. This
function takes five parameters and returns a MySQLi link identifier on success or
FALSE on failure.
Syntax:
connection mysqli_connect(server, user, passwd, new_link, client_flag);
2)mysqli_close().
This function takes a single parameter, which is a connection returned by
mysqli_connect() function.
mysqli_close() Function closes a previously opened database connection.
Syntax:
bool mysqli_close ( resource $connection );
Example:
<?php
$servername = "localhost:3306";
$username = "root";
$password = "";
$dbname = "hvcdb";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(!$conn )
{
die('Could not connect: ' . mysqli_error($conn));
}
else
{
echo 'Connected successfully';
}
mysqli_close($conn);
?>
3)mysqli_select_db()
This function is used to change the default database for the connection.
Syntax:
mysqli_select_db(connection, dbname);
245
Parameter & Description
- connection: Required. Specifies the MySQL connection to use
- dbname: Required. Specifies the default database to be used
Example
<?php
$con=mysqli_connect("localhost","root","","hvcdb");
// ...some PHP code for database " hvcdb "...
// Change database to "test"
mysqli_select_db($con,"test");
// ...some PHP code for database "test"...
mysqli_close($con);
?>
4)mysqli_query()
This function performs a query against the database.
Syntax:
mysqli_query(connection, query, resultmode);
Example:
<?php
$con=mysqli_connect("localhost","root","","hvcdb");
// Perform queries
mysqli_query($con,"INSERT INTO students (FirstName,LastName,Age)
VALUES ('Karan','Chauhan',22)");
mysqli_close($con);
?>
5)mysqli_affected_rows()
This function returns the number of affected rows in the previous SELECT,
246
INSERT, UPDATE, REPLACE, or DELETE query.
Syntax:
mysqli_affected_rows(connection);
Example:
<?php
$con=mysqli_connect("localhost","root","","hvcdb");
// Perform queries and print out affected rows
mysqli_query($con,"SELECT * FROM students");
echo "Affected rows: " . mysqli_affected_rows($con);
mysqli_query($con,"DELETE FROM students WHERE Age > 22");
echo "Affected rows: " . mysqli_affected_rows($con);
mysqli_close($con);
?>
6)mysqli_num_rows()
This function returns the number of rows in a result set.
Syntax:
mysqli_num_rows(result);
Parameter & Description
- result: Required. Specifies a result set identifier returned by mysqli_query()
Example:
<?php
$con=mysqli_connect("localhost","root","","hvcdb");
$sql="SELECT Lastname,Age FROM students ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
247
$rowcount = mysqli_num_rows($result);
echo "total record =".$rowcount;
}
mysqli_close($con);
?>
7)mysqli_fetch_array()
This function fetches a result row as an associative array, a numeric array,
or both. Note: Fieldnames returned from this function are case-sensitive.
Syntax:
mysqli_fetch_array(result,resulttype);
Example:
<?php
$con=mysqli_connect("localhost","root","","hvcdb");
$sql="SELECT Firstname,Age FROM students";
$result=mysqli_query($con,$sql);
// Numeric array
$row=mysqli_fetch_array($result,MYSQLI_NUM);
echo "Result by using MYSQLI_NUM : ".$row[0]."(".$row[1].")<br>";
// Associative array
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
echo "Result by using MYSQLI_ASSOC :".$row["Firstname"]."(".$row["Age"].")<br>";
248
// Both way : Associative array & Numeric Array
$row=mysqli_fetch_array($result,MYSQLI_BOTH);
echo "Result by using MYSQLI_BOTH : ".$row["Firstname"]."(".$row[1].")";
mysqli_close($con);
?>
8)mysqli_fetch_assoc()
The mysqli_fetch_assoc() function fetches a result row as an associative array.
Note: Fieldnames returned from this function are case-sensitive.
Syntax:
mysqli_fetch_assoc(result);
Example:
<?php
$con=mysqli_connect("localhost","root","","hvcdb");
$sql="SELECT Lastname,Age FROM students ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
{
while ($row=mysqli_fetch_assoc($result))
echo "Result by using mysqli_fetch_assoc :
".$row["Lastname"]."(".$row["Age"].")<br>";
}
mysqli_close($con);
?>
9)mysqli_fetch_object()
The mysqli_fetch_object() function returns the current row of a result set, as
an object. Note: Fieldnames returned from this function are case-sensitive.
Syntax:
mysqli_fetch_object(result, classname, params);
249
Parameter & Description:
- result: Required. Specifies a result set identifier returned by mysqli_query().
- classname: Optional. Specifies the name of the class to instantiate, set the
properties of, and return
- params: Optional. Specifies an array of parameters to pass to the
constructor for classname objects
Example:
<?php
$con=mysqli_connect("localhost","root","","hvcdb");
$sql="SELECT Lastname,Age FROM students ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
{
while ($obj = mysqli_fetch_object($result))
echo "Result by using mysqli_fetch_object() : ".$obj->Lastname."(".$obj->Age.")<br>";
}
mysqli_close($con);
?>
10)mysqli_fetch_row()
This function fetches one row from a result-set and returns it as an enumerated
array.
Syntax:
mysqli_fetch_row(result);
Example:
<?php
$con=mysqli_connect("localhost","root","","hvcdb");
$sql="SELECT Lastname,Age FROM students ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
250
{ // Fetch one and one row
while ($row=mysqli_fetch_row($result))
echo "Result by using mysqli_fetch_row() : ".$row[0]."(".$row[1].")<br>";
}
mysqli_close($con);
?>
11)mysqli_prepare()
Prepares an SQL statement for execution
Syntax:
mysqli_prepare ( mysqli $connection , string $query )
Example:
<?php
$con=mysqli_connect("localhost","root","","hvcdb");
$stmt = $con->prepare("INSERT INTO students (FirstName,LastName,Age)
VALUES(?,?,?);");
$fname="kishan";
$lname = "raval";
$age = 32;
$stmt->bind_param("ssi",$fname,$lname,$age);
$stmt->execute()or die("error".mysqli_error($con));
echo "New record created successfully";
$stmt->close();
mysqli_close($con);
?>
12)mysqli_fetch_field()
It returns an array of objects containing column in a result set
Syntax:
mysqli_fetch_field(result)
251
Parameter & Description
Result - It specifies the result set identifier returned by mysqli_query
Example
<?php
$con=mysqli_connect("localhost","root","","hvcdb");
$sql = "SELECT Firstname,Lastname FROM students";
if ($result = mysqli_query($con,$sql))
{
$fieldinfo = mysqli_fetch_fields($result);
foreach ($fieldinfo as $val)
{
echo "first field=".$val->name; echo "<br>";
echo "second field=".$val->max_length; echo "<br>";
}
}
mysqli_close($con);
?>
13)mysqli_num_fields()
It returns the number of fields in a result set.
Syntax:
mysqli_num_field(mysqli_result $result)
Example
<?php
$con=mysqli_connect("localhost","root","","hvcdb");
$sql = "SELECT * FROM students";
if ($result = mysqli_query($con,$sql))
252
{
$fieldcount = mysqli_num_fields($result);
echo “total fields in result is=”.$fieldcount;
}
mysqli_close($con);
?>
14)mysqli_data_seek()
It is used to move internal result pointer.
Syntax:
mysqli_data_seek(result, row_number)
Example
<?php
$con=mysqli_connect("localhost","root","","hvcdb");
$sql = "SELECT * FROM students";
$result = mysqli_query($con,$sql);
mysqli_data_seek($result,2);
print_r(mysqli_fetch_row($result));
mysqli_close($con);
?>
15)mysqli_error()
It returns a list of errors from the last connection
Syntax:
mysqli_data_seek(connection)
Example
<?php
253
$con=mysqli_connect("localhost","root","","hvcdb”);
$sql = "SELECT * FROM students";
$result = mysqli_query($sql,$con) or die(“error is=”.mysqli_error($con));
mysql_close($connection_mysql);
?>
16)mysqli_errno()
It returns the error code for the most recent function call.
Syntax:
mysqli_errno(connection)
Example
<?php
$con=mysqli_connect("localhost","root","","hvcdb");
$sql = "SELECT * FROM students";
$result = mysqli_query($con,$sql) or die("error is=".mysqli_errno($con));
mysql_close($connection_mysql);
?>
Advantages:
- it prevents the data to be entered in invalid format.
- it is a portable languages as it has general format.
- it is easy to learn and use.
Disadvantages:
- the validation which is provided using server side scripting is
disadvantages, as the web page is refreshed again and again.
254
- one can easily create a binary image file from the file having PERL regular
expression.
- one has to verify whether the PERL is installed for PERL regular expression or
not.
Above shown are the general symbols, the other symbols used in the format are as
shown below.
* One or more times.
+ Zero or more times
? Zero or one time
When the format which is matched is not found, then it returns as false otherwise it
would have returned as true value.
Syntax:
boolean ereg(“format”, variable/ value to be checked)
255
Example:
Lets take the validation for date having the format dd/mm/yyyy format.
<?php
$date="13/02/2020";
$indate="13/02/20";
if(ereg("^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$",$date))
{
echo "valid date";
}
else
{
echo "invalid date";
}
if(ereg("^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$",$indate))
{
echo "valid date";
}
else
{
echo "invalid date";
}
?>
256
2. Perl Compatible Regular Expression
This type of regular expression is developed using the perl language. The
function which is used for the given regular expression is preg_match() that
is perl regular expression.
The symbols are used as the above ones only. It also return the Boolean
value. If the format is matched, then it returns true value otherwise will
return false value.
There are different symbols used which are given as below.
Symbol Description
\d Any number
\D Fir anything other than a number
\s Any kind of whitespace
\S Anything other than whitespace
\W Any word character (including the underscore character)
\w Anything other than word character
\A Beginning of string
\b Word boundary
\B Not a word boundary
\Z End of string (matches before final new line or at end of string)
\z End of string (matches only at the very end of the string)
Syntax:
Boolean preg_match(“format”, variable/value to be checked)
Example:
<?php
$date="13/02/2020";
$indate="13/02/20";
if preg_match(('^\d{2}\/\d{2}\/\d{4}^',$date))
{
Echo”valid date”
}
Else
{
Echo “invalid date”
}
?>
258
}
?>
6.11File Uploading
A PHP script can be used with a HTML form to allow users to upload files
to the server. Initially files are uploaded into a temporary directory and
then relocated to a target destination by a PHP script.
Information in the phpinfo.php page describes the temporary directory
that is used for file uploads as upload_tmp_dir and the maximum
permitted size of files that can be uploaded is stated as
upload_max_filesize. These parameters are set into PHP configuration file
php.ini
The process of uploading a file follows these steps −
The user opens the page containing a HTML form featuring a text files, a
browse button and a submit button.
The user clicks the browse button and selects a file to upload from the local
PC.
The full path to the selected file appears in the text filed then the user
clicks the submit button.
The selected file is sent to the temporary directory on the server.
The PHP script that was specified as the form handler in the form's action
attribute checks that the file has arrived and then copies the file into an
intended directory.
The PHP script confirms the success to the user.
As usual when writing files it is necessary for both temporary and final
locations to have permissions set that enable file writing. If either is set to
be read-only then process will fail.
An uploaded file could be a text file or image file or any document.
Example
259
<?php
if(isset($_FILES['ima
ge'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$extensions=
array("jpeg","jpg","png");
if(in_array($file_ext,$extensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if(empty($errors)==true){ move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}else{ print_r($errors);
}
}
?>
<html>
<body>
</body>
</html>
260
6.11 Sending Mail
PHP mail is the built in PHP function that is used to send emails from PHP
scripts.
mail($to,$subject,$message,[$headers],[$parameters]);
HERE,
“$to” is the email address of the mail
recipient “$subject” is the email
261
subject
“$message” is the message to be sent.
“[$headers]” is optional, it can be used to include information such as CC, BCC
CC is the acronym for carbon copy. It’s used when you want to send a copy to
an interested person i.e. a complaint email sent to a company can also be sent
as CC to the complaints board.
BCC is the acronym for blind carbon copy. It is similar to CC. The email addresses
included in the BCC section will not be shown to the other recipients.
262
The find dialog menu will appear
Remove the semi colons before SMTP and smtp_port and set the SMTP to your
smtp server and the port to your smtp port. Your settings should look as follows
SMTP =
smtp.example.com
smtp_port = 25
Note the SMTP settings can be gotten from your web hosting providers.
If the server requires authentication, then add the following lines. auth_username
= [email protected]
auth_password = example_password
Save the new changes.
Restart Apache server.
While sending an email message you can specify a Mime version, content type
and character set to send an HTML email.
Example
264
Following example will send an HTML email message to [email protected]
copying it to [email protected]. You can code this program in such a way
that it should receive all content from the user and then it should send an email.
<?php
$to = "[email protected]";
$subject = "This is subject";
($to,$subject,$message,$header); if(
$retval == true ) {
echo "Message sent successfully...";
}else {
echo "Message could not be sent...";
}
?>
6.13 AJAX
AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique
for creating better, faster, and more interactive web applications with the
help of XML, HTML, CSS and Java Script.
With AJAX when submit is pressed, JavaScript will make a request to the
server, interpret the results and update the current screen. In the purest sense,
265
the user would never know that anything was even transmitted to the server.
Property Description
Onreadystatechange Defines a function to be called
when the readyState property
changes
267
readyState Holds the status of the
XMLHttpRequest. 0: request not
initialized
1: server connection
established 2: request
received
3: processing request
4: request finished and response is
ready
responseText Returns the response data as a string
responseXML Returns the response data as XML data
Status Returns the status-number of a
request 200: "OK"
403: "Forbidden"
404: "Not Found"
statusText Returns the status-text (e.g. "OK" or
"Not Found")
268
Example
<html>
<body>
<div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt",
true); xhttp.send();
}
</script>
</body>
</html>
272
$sql="SELECT * FROM stud_reg WHERE fname = '".$q."'";
$result = mysqli_query($con,$sql); echo "<table>
<tr>
<th>fullname</th>
<th>username</th>
<th>city</th>
</tr>";
while($row = mysqli_fetch_array($result)) { echo "<tr>";
echo "<td>" . $row['fname'] . "</td>";
echo "<td>" . $row['uname'] . "</td>";
echo "<td>" . $row['city'] . "</td>"; echo "</tr>";
}
echo "</table>"; mysqli_close($con);
?>
273