Sunteți pe pagina 1din 181

Table of Contents

What is the Internet? ....................................................................................................................... 7


What are the differences between hardware and software? ........................................................ 7
Comparison chart ..................................................................................................................... 8
What is Networks? .......................................................................................................................... 8
Types of Network Topology ....................................................................................................... 9
BUS Topology............................................................................................................................. 9
Features of Bus Topology........................................................................................................ 9
RING Topology......................................................................................................................... 10
Features of Ring Topology .................................................................................................... 10
STAR Topology ........................................................................................................................ 11
Features of Star Topology ......................................................................................................... 11
MESH Topology ....................................................................................................................... 11
Different Kind of Networks ...................................................................................................... 13
LAN: Local Area Network .................................................................................................... 13
WAN: Wide Area Network ................................................................................................... 14
LAN, WAN, and Home Networking ..................................................................................... 14
Other Types of Area Networks .............................................................................................. 14
What is WWW? ............................................................................................................................ 14
What is Web 1.0, 2.0 and 3.0? .................................................................................................. 15
What is a Static Website? ...................................................................................................... 16
What is a Dynamic Website?................................................................................................. 16
Difference between Static and Dynamic Website ................................................................. 17
What’s the Difference between Different Web Browsers ..................................................... 17
Compare different types of websites ..................................................................................... 18
Identify different Web Threats and explain their security measures ..................................... 20
DIFFERENCE BETWEEN A DOMAIN AND A HOSTING ACCOUNT ......................... 21
Learn the Basics of Web Design ........................................................................................... 22
Systems Analysis and Design ................................................................................................... 24
1
ALI RAZA MANZOOR (WEB DEVELOPER)
Web Application Development ............................................................................................. 25
WEB DEVELOPMENT LIFE CYCLE ................................................................................ 26
Information Gathering (Graphical) ........................................................................................ 28
Analysis (Graphical) .............................................................................................................. 28
Graphical Design ................................................................................................................... 28
Information Gathering (Functional) ...................................................................................... 28
Analysis (Functional) ............................................................................................................ 29
Functional Design .................................................................................................................. 29
Implementation ...................................................................................................................... 29
Maintenance........................................................................................................................... 29
Databases ...................................................................................................................................... 30
What is Data? ............................................................................................................................ 30
What is a Database? .................................................................................................................. 30
What is a Database Management System (DBMS)? ................................................................. 30
Types of DBMS ..................................................................................................................... 31
What is SQL? ............................................................................................................................ 31
What is NoSQL? ....................................................................................................................... 32
Why it makes sense to learn SQL after NOSQL? ................................................................. 32
What is Database Design? ..................................................................................................... 33
Why Database Design is Important? ..................................................................................... 33
Database development life cycle............................................................................................. 33
Requirements analysis ........................................................................................................... 34
Database designing ................................................................................................................ 34
Implementation ...................................................................................................................... 34
Two Types of Database Techniques ...................................................................................... 34
What is a KEY? ..................................................................................................................... 36
What is a Primary Key? ......................................................................................................... 36
What is Composite Key? ....................................................................................................... 36
Database - Foreign Key ......................................................................................................... 37
3NF Example ........................................................................................................................ 39

2
ALI RAZA MANZOOR (WEB DEVELOPER)
What is ER Modeling? .................................................................................................................. 41
Enhanced Entity Relationship (EER) Model ............................................................................ 41
Why use ER Model? .............................................................................................................. 42
Defining the relationships among entities ............................................................................. 43
What is HTML? ............................................................................................................................ 43
HTML Editors .......................................................................................................................... 44
Save the HTML Page ............................................................................................................ 44
HTML Headings .................................................................................................................... 44
HTML Attributes ................................................................................................................... 46
The href Attribute .................................................................................................................. 46
The src Attribute / width /height/image tag ........................................................................... 46
HTML Horizontal Rules........................................................................................................... 46
Internal CSS ........................................................................................................................... 50
Style.css file ........................................................................................................................... 51
CSS Padding .......................................................................................................................... 51
HTML Links – Hyperlinks .................................................................................................... 53
HTML Links - The target Attribute ....................................................................................... 53
Image as Link ........................................................................................................................ 53
Link Titles.............................................................................................................................. 53
HTML Table .......................................................................................................................... 54
HTML Block and Inline Elements ...................................................................................... 56
Inline Element........................................................................................................................ 58
CSS Outline .......................................................................................................................... 63
Outline Style .......................................................................................................................... 63
Outline Color ......................................................................................................................... 64
Outline Width ........................................................................................................................ 65
CSS Text ................................................................................................................................ 68
CSS text-decoration-style/text-justify .............................................................................. 68
Text Transformation/Text Decoration ...................................................................................... 69

3
ALI RAZA MANZOOR (WEB DEVELOPER)
Text Transformation .............................................................................................................. 69
Text Decoration ..................................................................................................................... 69
Letter Spacing/ Line Height/ Text Direction/ Word Spacing/ Text Shadow ........................ 70
Different List Item Markers ................................................................................................... 71
An Image as The List Item Marker ....................................................................................... 72
Override The Default Display Value ..................................................................................... 73
CSS Layout - width and max-width .................................................................................. 74
position: static;....................................................................................................................... 76
position: relative; ................................................................................................................... 76
position: fixed; ....................................................................................................................... 76
position: absolute; .................................................................................................................. 76
position: sticky;...................................................................................................................... 76
CSS Overflow ........................................................................................................................ 79
Use inline-block to Create Navigation Links ........................................................................ 82
The ::first-line Pseudo-element/::first-letter Pseudo-element................................................ 83
Show Different Images Depending on Browser Width ......................................................... 87
HTML tabindex Attribute .................................................................................................... 88
CSS letter-spacing PropertyAndCSS word-spacing Property .......................................... 89
JavaScript ...................................................................................................................................... 93
JavaScript Can Change HTML Styles (CSS) ............................................................................ 93
JavaScript Display Possibilities ............................................................................................. 94
JavaScript Arithmetic ........................................................................................................... 97
JavaScript Functions........................................................................................................... 103
JavaScript Switch Statement ............................................................................................... 103
JavaScript Objects .............................................................................................................. 105
JavaScript Objects ............................................................................................................... 106
JavaScript Scope ................................................................................................................. 107
JavaScript Events ................................................................................................................ 109
JavaScript Type Conversion ................................................................................................ 111

4
ALI RAZA MANZOOR (WEB DEVELOPER)
The JavaScript constructor Property.................................................................................... 113
JavaScript Arrays................................................................................................................. 115
Using the JavaScript Keyword new..................................................................................... 116
JavaScript Data Types ........................................................................................................ 118
JavaScript For Loop ............................................................................................................ 123
Different Kinds of Loops ..................................................................................................... 124
JavaScript While Loop ....................................................................................................... 127
The Do/While Loop ............................................................................................................. 128
Input Validation Example .................................................................................................... 130
The finally Statement........................................................................................................... 131
The JavaScript this Keyword ............................................................................................... 132
PHP ............................................................................................................................................. 133
What is a PHP File? ................................................................................................................ 133
What Can PHP Do? ................................................................................................................. 133
To start using PHP, you can: ............................................................................................... 134
PHP 5 Variables .................................................................................................................. 135
PHP Variables Scope .............................................................................................................. 136
Global and Local Scope ....................................................................................................... 136
PHP The Static Keyword ..................................................................................................... 137
PHP 5 echo Statements ........................................................................................................ 138
PHP 5 Data Types .............................................................................................................. 139
PHP String ........................................................................................................................... 139
PHP Integer.......................................................................................................................... 140
PHP Array............................................................................................................................ 141
PHP 5 Operators .................................................................................................................... 143
. PHP Arithmetic Operators ................................................................................................ 144
PHP Assignment Operators ................................................................................................. 144
PHP Logical Operators ........................................................................................................ 147
PHP 5 if...else...elseif Statements ........................................................................................ 149

5
ALI RAZA MANZOOR (WEB DEVELOPER)
PHP - The if...else Statement ............................................................................................... 150
PHP - The if...elseif....else Statement .................................................................................. 151
PHP 5 switch Statement ...................................................................................................... 151
The PHP switch Statement .................................................................................................. 151
PHP Loops ........................................................................................................................... 152
The PHP for Loop................................................................................................................ 153
The PHP while Loop ........................................................................................................... 154
PHP 5 Functions ................................................................................................................. 155
Create a User Defined Function in PHP .............................................................................. 155
PHP Function Arguments .................................................................................................... 156
PHP Default Argument Value ............................................................................................. 156
PHP 5 Arrays ....................................................................................................................... 157
What is an Array? ................................................................................................................ 157
Create an Array in PHP ....................................................................................................... 158
PHP 5 Sorting Arrays ......................................................................................................... 160
PHP 5 Form Handling........................................................................................................ 164
SQL Database ............................................................................................................................. 167
Introduction to SQL.............................................................................................................. 167
What is SQL?....................................................................................................................... 167
What Can SQL do? .............................................................................................................. 167
RDBMS ............................................................................................................................... 167
The SQL INSERT INTO Statement .................................................................................... 170
The SQL UPDATE Statement ............................................................................................... 170
The SQL DELETE Statement ............................................................................................. 171
Server file: ........................................................................................................................... 177
In this file session and check login authentication........................................................... 177
login file:.............................................................................................................................. 179
Change password file: ......................................................................................................... 180

6
ALI RAZA MANZOOR (WEB DEVELOPER)
What is the Internet?
The Internet is a worldwide system of interconnected computer networks that use the TCP/IP set
of network protocols to reach billions of users. The Internet began as a U.S Department of Defense
network to link scientists and university professors around the world by name of ARPANET in
1969. A network of networks, today, the Internet serves as a global data communications system
that links millions of private, public, academic and business networks via an international
telecommunications backbone that consists of various electronic and optical networking
technologies.
The terms "Internet" and "World Wide Web" are often used interchangeably; however, the Internet
and World Wide Web are not one and the same.
The Internet is a vast hardware and software infrastructure that enables computer interconnectivity.
The Web, on the other hand, is a massive hypermedia library database - a myriad collection of
documents and other resources interconnected by hyperlinks. Imagine the World Wide Web as the
platform which allows one to navigate the Internet with the use of a browser such as Google
Chrome or Mozilla Firefox.

What are the differences between hardware and


software?
Software is a general term used to describe a collection of computer programs, procedures, and
documentation that perform some task on a computer system. Practical computer systems divide
software systems into three major classes: system software, programming software, and
application software, although the distinction is arbitrary and often blurred. Software is an ordered
sequence of instructions for changing the state of the computer hardware in a particular sequence.
Software is typically programmed with a user-friendly interface that allows humans to interact
more efficiently with a computer system.
Hardware is best described as a device, such as a hard drive, that is physically connected to the
computer or something that can be physically touched. A CD-ROM, computer display monitor,
printer, and video card are all examples of computer hardware. Without any hardware, a computer
would not function, and software would have nothing to run on. Hardware and software interact
with one another: software tells hardware which tasks it needs to perform.
There are several differences between computer hardware and software.

7
ALI RAZA MANZOOR (WEB DEVELOPER)
Comparison chart
Hardware versus Software comparison chart

Hardware Software
Collection of instructions that enables
a user to interact with the computer.
Devices that are required to store and Software is a program that enables a
Definition
execute (or run) the software. computer to perform a specific task, as
opposed to the physical components of
the system (hardware).
Input, storage, processing, control, and System software, Programming
Types
output devices. software, and Application software.
Hardware serve as the delivery system for
software solutions. The hardware of a To perform the specific task you need
computer is infrequently changed, in to complete. Software is generally not
Function comparison with software and data, which needed to for the hardware to perform
are “soft” in the sense that they are readily its basic level tasks such as turning on
created, modified, or erased on the and responding to input.
computer
CD-ROM, monitor, printer, video card, QuickBooks, Adobe Acrobat, Google
Examples scanners, label makers, routers and Chrome, Microsoft Word, Microsoft
modems. Excel, Apple Maps
Inter Hardware starts functioning once To deliver its set of instructions,
dependency software is loaded. Software is installed on hardware.
Hardware failure is random. Hardware Software failure is systematic.
Failure does have increasing failure at the last Software does not have an increasing
stage. failure rate.
Software does not wear out over time.
Durability Hardware wears out over time. However, bugs are discovered in
software as time passes.

Nature Hardware is physical in nature. Software is logical in nature.

What is Networks?
You can do lots of things with a computer but, connect it up to other computers and peripherals
(the general name given to add-on bits of computer equipment such as modems, inkjet and laser
printers, and scanners) and you can do an awful lot more. A computer network is simply a

8
ALI RAZA MANZOOR (WEB DEVELOPER)
collection of computer equipment that's connected with wires, optical fibers, or wireless links so
the various separate devices (known as nodes) can "talk" to one another and swap data
(computerized information).

Types of Network Topology


Network Topology is the schematic description of a network arrangement, connecting various
nodes (sender and receiver) through lines of connection.

BUS Topology
Bus topology is a network type in which every computer and network device is connected to single
cable. When it has exactly two endpoints, then it is called Linear Bus topology.

Features of Bus Topology


1. It transmits data only in one direction.
2. Every device is connected to a single cable

Advantages of Bus Topology

1. It is cost effective.
2. Cable required is least compared to other network topology.
3. Used in small networks.
4. It is easy to understand.
5. Easy to expand joining two cables together.

Disadvantages of Bus Topology

1. Cables fails then whole network fails.


2. If network traffic is heavy or nodes are more the performance of the network decreases.
9
ALI RAZA MANZOOR (WEB DEVELOPER)
3. Cable has a limited length.
4. It is slower than the ring topology.

RING Topology
It is called ring topology because it forms a ring as each computer is connected to another
computer, with the last one connected to the first. Exactly two neighbors for each device.

Features of Ring Topology


1. A number of repeaters are used for Ring topology with large number of nodes, because if
someone wants to send some data to the last node in the ring topology with 100 nodes, then
the data will have to pass through 99 nodes to reach the 100th node. Hence to prevent data
loss repeaters are used in the network.
2. The transmission is unidirectional, but it can be made bidirectional by having 2 connections
between each Network Node, it is called Dual Ring Topology.
3. In Dual Ring Topology, two ring networks are formed, and data flow is in opposite
direction in them. Also, if one ring fails, the second ring can act as a backup, to keep the
network up.
4. Data is transferred in a sequential manner that is bit by bit. Data transmitted, has to pass
through each node of the network, till the destination node.
Advantages of Ring Topology
1. Transmitting network is not affected by high traffic or by adding more nodes, as only the
nodes having tokens can transmit data.
2. Cheap to install and expand
Disadvantages of Ring Topology
1. Troubleshooting is difficult in ring topology.

10
ALI RAZA MANZOOR (WEB DEVELOPER)
2. Adding or deleting the computers disturbs the network activity.
3. Failure of one computer disturbs the whole network.

STAR Topology
In this type of topology all the computers are connected to a single hub through a cable. This hub
is the central node and all others nodes are connected to the central node.

Features of Star Topology


1. Every node has its own dedicated connection to the hub.
2. Hub acts as a repeater for data flow.
3. Can be used with twisted pair, Optical Fibre or coaxial cable.
Advantages of Star Topology
1. Fast performance with few nodes and low network traffic.
2. Hub can be upgraded easily.
3. Easy to troubleshoot.
4. Easy to setup and modify.
5. Only that node is affected which has failed, rest of the nodes can work smoothly.
Disadvantages of Star Topology
1. Cost of installation is high.
2. Expensive to use.
3. If the hub fails then the whole network is stopped because all the nodes depend on the hub.
4. Performance is based on the hub that is it depends on its capacity

MESH Topology
11
ALI RAZA MANZOOR (WEB DEVELOPER)
It is a point-to-point connection to other nodes or devices. All the network nodes are connected to
each other. Mesh has n(n-1)/2 physical channels to link n devices.
There are two techniques to transmit data over the Mesh topology, they are:
 Routing
 Flooding

MESH Topology: Routing


In routing, the nodes have a routing logic, as per the network requirements. Like routing logic to
direct the data to reach the destination using the shortest distance. Or, routing logic which has
information about the broken links, and it avoids those node etc. We can even have routing logic,
to re-configure the failed nodes.
MESH Topology: Flooding
In flooding, the same data is transmitted to all the network nodes, hence no routing logic is
required. The network is robust, and the its very unlikely to lose the data. But it leads to unwanted
load over the network.
Types of Mesh Topology
1. Partial Mesh Topology : In this topology some of the systems are connected in the same
fashion as mesh topology but some devices are only connected to two or three devices.
2. Full Mesh Topology : Each and every nodes or devices are connected to each other.
Features of Mesh Topology
1. Fully connected.
2. Robust.
3. Not flexible.

12
ALI RAZA MANZOOR (WEB DEVELOPER)
Advantages of Mesh Topology

1. Each connection can carry its own data load.


2. It is robust.
3. Fault is diagnosed easily.
4. Provides security and privacy.

Disadvantages of Mesh Topology

1. Installation and configuration is difficult.


2. Cabling cost is more.
3. Bulk wiring is required.

Different Kind of Networks


One way to categorize the different types of computer network designs is by their scope or scale.
For historical reasons, the networking industry refers to nearly every type of design as some kind
of area network. Common types of area networks are:

 LAN - Local Area Network


 WAN - Wide Area Network
 WLAN - Wireless Local Area Network
 MAN - Metropolitan Area Network
 SAN - Storage Area Network, System Area Network, Server Area Network, or sometimes
Small Area Network
 CAN - Campus Area Network, Controller Area Network, or sometimes Cluster Area
Network
 PAN - Personal Area Network

LAN and WAN are the two primary and best-known categories of area networks, while the others
have emerged with technology advances

LAN: Local Area Network


A LAN connects network devices over a relatively short distance. A networked office building,
school, or home usually contains a single LAN, though sometimes one building will contain a few
small LANs (perhaps one per room), and occasionally a LAN will span a group of nearby
buildings. In TCP/IP networking, a LAN is often but not always implemented as a single IP subnet.
In addition to operating in a limited space, LANs are also typically owned, controlled, and
managed by a single person or organization. They also tend to use certain connectivity
technologies, primarily Ethernet and Token Ring.

13
ALI RAZA MANZOOR (WEB DEVELOPER)
WAN: Wide Area Network
As the term implies, a WAN spans a large physical distance. The Internet is the largest WAN,
spanning the Earth.A WAN is a geographically-dispersed collection of LANs. A network device
called a router connects LANs to a WAN. In IP networking, the router maintains both a LAN
address and a WAN address.
A WAN differs from a LAN in several important ways. Most WANs (like the Internet) are not
owned by any one organization but rather exist under collective or distributed ownership and
management. WANs tend to use technology like ATM, Frame Relay and X.25 for connectivity
over the longer distances.

LAN, WAN, and Home Networking


Residences typically employ one LAN and connect to the Internet WAN via an Internet Service
Provider (ISP) using a broadband modem. The ISP provides a WAN IP address to the modem, and
all of the computers on the home network use LAN (so-called private) IP addresses. All computers
on the home LAN can communicate directly with each other but must go through a central network
gateway, typically a broadband router, to reach the ISP.

Other Types of Area Networks


While LAN and WAN are by far the most popular network types mentioned, you may also
commonly see references to these others:

 Wireless Local Area Network - A LAN based on Wi-Fi wireless network technology
 Metropolitan Area Network - A network spanning a physical area larger than a LAN but
smaller than a WAN, such as a city. A MAN is typically owned and operated by a single
entity such as a government body or large corporation.
 Campus Area Network - A network spanning multiple LANs but smaller than a MAN,
such as on a university or local business campus.
 Storage Area Network - Connects servers to data storage devices through a technology
like Fibre Channel.
 System Area Network (also known as Cluster Area Network) - Links high-performance
computers with high-speed connections in a cluster configuration.

What is 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 of human knowledge."
14
ALI RAZA MANZOOR (WEB DEVELOPER)
The Web, as it's commonly known, is often confused with the internet. Although the two are
intricately 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 hypertext browser/editor that ran in the NeXTStep environment.
The World Wide Web has been widely available since 1991.

What is Web 1.0, 2.0 and 3.0?


I’ll start with the challenges that cause people to think in terms of web 2.0 and web 3.0. Since these
are buzzwords and not clearly defined terms, think of this as an attempt to describe the ever-
changing web. I will borrow from Tim Berners-Lee, director of World Wide Web Consortium and
the inventor of the World Wide Web (in 1989). His notion of the “read-write” web is often used
to describe web 2.0.
Web 1.0
The first iteration of the web represents the web 1.0, which, according to Berners-Lee, is the “read-
only web.” In other words, the early web allowed us to search for information and read it. There
was very little in the way of user interaction or content generation.

The first iteration of the web represents the web 1.0, which, according to
Berners-Lee, is the “read-only web.”
This was what most website owners wanted. They needed a website to make their information
available to anyone at any time. I call this “brick-and-mortar thinking applied to the web.” The
web as a whole hasn’t moved much beyond this stage. Shopping cart applications, which most
ecommerce sites use in some form, fall under the category of web 1.0. The overall goal is to present
products to potential customers — much as a catalog or a brochure does — to anyone in the world.
The web provides the exposure. It removes the geographical restrictions associated with brick-
and-mortar businesses.
Web 2.0
We are now seeing the infancy of web 2.0, or the “read-write” web as Berners-Lee described it.
It’s the ability to contribute content and interact with other web users. It has dramatically changed
the landscape of the web in a short time. It has much potential. As examples, look at YouTube and
15
ALI RAZA MANZOOR (WEB DEVELOPER)
MySpace, which rely on user submissions. Web 2.0 is a welcome response to web users, who want
to participate in the information. There are many definitions of a “web 2.0 application.” For
example, there’s the perception that just because a website is built using a certain technology (such
as Ruby on Rails) or because it employs Ajax in its interface, it represents web 2.0. But that is not
necessarily the case. Web 2.0, for lay people, simply requires that users can interact or contribute
content.
Web 3.0
This leads us web 3.0 (extending the vague nomenclature). By extrapolating Tim Berners-Lee’s
explanations, web 3.0 is “read-write-execute.” This is difficult to envision in its abstract form. To
illustrate, consider semantic markup and web services. Semantic markup refers to the
communication gap between humans and computerized applications. One of the biggest challenges
of presenting information on the web is that applications cannot provide context to data, and,
therefore, can’t understand what is relevant. Through the use of some sort of semantic markup (or
data interchange formats), data could be put in a form not only accessible to humans via natural
language, but able to be understood and interpreted by software applications as well. While it is
still evolving, this notion — formatting data to be understood by software agents — leads to the
“execute” portion of the web 3.0 definition. A web service is a software that supports computer-
to-computer interaction over the internet. Web services are not new and usually take the form of
an application programming interface. The popular photography-sharing website Flickr provides
a web service whereby developers can programmatically interface to search for images. There are
thousands of web services. Combining semantic markup and web services can produce a web 3.0
experience — applications that can speak to each other directly and interpret information for
humans?

What is a Static Website?


It’s the most basic kind of website that’s coded in plain HTML with no custom coding and dynamic
features. It requires no server-side scripting, only client-side such as HTML and CSS. The site of a
small-scale company with just information of two to three pages without any bells and whistles
can be regarded as a static website. They are easy and cheap to develop and host with no
maintenance costs and no additional skills other than HTML. Each page exists as individual files
coded in HTML with no interactivity features other than hyperlinks, pictures or graphics. In simple
terms, static websites are the sites in which the content remains unchanged unless it’s changed
from the source code and changes to the main page require editing of each page.

What is a Dynamic Website?


As the name suggests, dynamic websites contain dynamic pages that are characterized by
constantly changing content that would be more functional, something users can interact with,
not just read. It requires more than just client-side scripting; it’s written using server-side
scripting languages such as ASP, PHP, JavaScript, JSP, Coldfusion, etc. When a webpage is

16
ALI RAZA MANZOOR (WEB DEVELOPER)
accessed, the code is parsed on the web server and the resulting HTML page is displayed on the
client’s web browser. They use a combination of both server-side and client-side scripting to
generate dynamic content. E-commerce sites and social media sites are the two best examples
of dynamic websites.

Difference between Static and Dynamic Website

What’s the Difference between Different Web Browsers


Long gone are the days of Internet Explorer being the only available web browser. These days
Google Chrome, Mozilla Firefox and Safari have joined the battle to be your main web browser. In
this blog post we hope that you will learn about browsers that you haven’t used and maybe find
one that better suits your needs.
Internet Explorer is the default browser that comes installed on most, if not all, PCs. IE has a
very sophisticated tab management system, which is very helpful for people who like to have
several pages open at once. Also, it provides a stable application that does not crash very
often. However, IE typically takes longer to load web pages than other browsers, and only
supports the Windows operating system.
Google Chrome is quickly becoming a very popular option known for its speed and
simplicity. The “omnibar” combines your regular address bar with your search bar, allowing you
to type in URLs and Google searches in the same place. Chrome is a very powerful web browser,
and is definitely a browser that is worth a look.

17
ALI RAZA MANZOOR (WEB DEVELOPER)
Mozilla Firefox is known for its vast array of add-ons that add to the web-browsing
experience. Their selection of add-ons and extensions, such as AdBlockerPlus, can revolutionize
the way that you use the Internet. Firefox is also well-known for its stability, but its startup process
is not as fast as Chrome’s.
Safari is the default web browser installed on Macs, and is known for its simple and non-flashy
approach. By removing unnecessary bells and whistles, Safari loads pages very quickly and is
perfect for users that do not ask a lot of their web browsers. However, it sacrifices a lot of the
customization that other browsers provide.
Web browsers are all about personal preference, so try out browsers that you’ve never used
before. You may find that certain features are more important to you than others, and you may be
able to enhance your web browsing experience. If you are one of many people who have only
used the default Internet Explorer all your life, you should definitely explore using a different
browser. The worst that could happen is that you find that you still prefer IE. Most likely, you’ll
find that another browser provides a better Internet experience for you and you’ll never go back.

Compare different types of websites


Affiliate
A site, typically few in pages, whose purpose is to sell a third party's product. The seller receives
a commission for facilitating the sale.

Blog
Sites generally used to post online diaries which may include discussion forums (e.g.,blogger,
Xanga). Many bloggers use blogs like an editorial section of a newspaper to express their ideas on
anything ranging from politics to religion to video games to parenting, along with anything in
between. Some bloggers are professional bloggers and they are paid to blog about a certain subject,
and they are usually found on news sites.

News Site
Similar to an information site, but dedicated to dispensing news, politics, and commentary.

Information Site
Most websites could fit in this type of website to some extent many of them are not necessarily for
commercial purposes.

Search Engine Site


A website that indexes material on the internet or an intranet (and lately on traditional media such
as books and newspapers)and provides links to information as a response to a query.

18
ALI RAZA MANZOOR (WEB DEVELOPER)
School Site
A site on which teachers, students, or administrators can post information about current events at
or involving their school. U.S. elementary-high school websites generally use k12 in the URL.

Archive Site
Used to preserve valuable electronic content threatened with extinction. Two examples are:
Internet Archive, which since 1996 has preserved billions of old (and new) web pages; and Google
Groups, which in early 2005 was archiving over 845,000,000 messages posted to Usenet
news/discussion groups.

Award
The Webby Awards, Favorite Website Awards, Interactive Media Awards and Web Awards are
prominent award organizations recognizing the world's best websites.

Photo Sharing Website


These types of website are cropping up like fleas on dog. There are web companies like,
Flickr.com, Photosite.com, and Google's Picasa. There could easily be over a hundred such sites
that offer free photo sharing paid for by their online advertising. Also, many digital cameras and
photo printers now come with software enabling mere mortals to create digital photo slide shows
and upload them to the web.

Online Business Website


In the days before the Internet, we used the print, radio, and television media to spread the word
about our businesses. Now we can cast a large net, reaching literally millions of people with just
one website. With your online brochure or catalog, you can show anyone who looks for and finds
your website, photos and descriptions of your products or services. To some this may sound like
an Ecommerce Website, but there are many businesses that deal in products or services that are
not sellable over the web—think hair-stylist, dentist, or day-care center.

Content Aggregator
Business that gathers and organizes web content and then distributes or feeds the content to
subscribers for free or for a fee.

19
ALI RAZA MANZOOR (WEB DEVELOPER)
Identify different Web Threats and explain their security
measures
1. Security Misconfiguration
A functioning web application is usually supported by some complex elements that make up its
security infrastructure. This includes databases, OS, firewalls, servers and other application
software or devices.
What people don’t realize is that all these elements require frequent maintenance and configuration
to keep the web application running properly. Before making use of a web application,
communicate with the developers to understand the security and priority measures that have been
undertaken for its development.

2. Malware
The presence of malware is yet another one of the most common threats that companies commonly
have to guard against. Upon downloading malware, severe repercussions like activity monitoring,
access to confidential information and backdoor access to large scale data breaches can be
incurred. Malware can be categorized in different groups since they work to achieve different
goals- Spyware, Viruses, Ransomware, Worms, and Trojans.
To combat this problem, make sure to install and keep firewalls up to date. Ensure that all your
operating systems have been updated as well. You can also engage developers and antispam/virus
experts to come up with preventative measures to remove and spot malware infections. Do also
make sure to backup important files in external safe environments. This essentially means that if
you are locked out, you will be able to access all your information without having to pay due to
ransomware. Do perform checks on your security software, the browsers used and third party
plugins. If there are patches and updates for the plugins, make sure to update as soon as possible.

3. Injection Attacks
Injection attacks are yet another common threat to be on the lookout for. These types of attacks
come in a variety of different injection types and are primed to attack the data in web applications
since web applications require data to function.
The more data is required, the more opportunities for injection attacks to target. Some examples
of these attacks include SQL injection, code injection and cross site scripting. SQL injection
attacks usually hijack control over the website owner’s database through the act of data injection
into the web application. The data injected gives the website owner’s database instructions that
have not been authorized by the site owner themselves. This results in data leaking, removal or
manipulation of stored data. Code injection, on the other hand, involves the injecting of source
codes into the web application while cross site scripting injects code (JavaScript) into browsers.
These injection attacks primarily function to give your web application instructions that are not
authorized as well. To combat this, business owners are advised to implement input validation

20
ALI RAZA MANZOOR (WEB DEVELOPER)
techniques and robust coding. Business owners are also encouraged to make use of ‘least privilege’
principles so that the user rights and authorization for actions are minimized.

4. Phishing Scam
Phishing scam attacks are usually involved and interfere directly with email marketing efforts.
These types of threats are designed to look like emails that are from legitimate sources, with the
goal of acquiring sensitive information like login credentials, bank account numbers, credit card
numbers and other data.
If the individual is not aware of the differences and indications that the email messages are
suspicious, it can be deadly since they may respond to it. Alternatively, they can also be used to
send in malware that, upon clicking, may end up gaining access to the user’s information. To
prevent such incidents from happening, ensure that all employees are aware and capable of spotting
suspicious emails. Preventative measures should also be covered so that further actions can be
undertaken.
For example, scanning links and information before downloading, as well as contacting the
individual to which the email is sent from to verify its legitimacy.

5. Brute Force
Then there’s also brute force attacks, where hackers attempt to guess passwords and forcefully
gain access to the web application owner’s details. There is no effective way to prevent this from
occurring. However, business owners can deter this form of attack by limiting the number of logins
one can undertake as well as making use of a technique known as encryption. By taking the time
to encrypt data, this ensures that they are difficult for hackers to make use of it for anything else
unless they have encryption keys. This is an important step for corporations who are required to
store data that is sensitive to prevent further problems from occurring.

DIFFERENCE BETWEEN A DOMAIN AND A HOSTING


ACCOUNT
Every website has its web pages or scripts stored on a server somewhere. These web pages or
scripts are what you view on your browser. This space on a server is called a hosting account.
The domain name is a unique name that your site visitors use to access your website. In reality,
the domain name is translated to the IP address of the server that hosts the web pages for the web
site. There is a link between a domain name and a hosting account called the name servers. These
name servers are values given to the domain that would direct the domain to the server where the
web pages are hosted.
This means that you can register a domain with one company and get a hosting account with
another. As long as the domain has the right name servers, the domain would point to the correct

21
ALI RAZA MANZOOR (WEB DEVELOPER)
server. This therefore implies that you can place an order for a hosting account alone, a domain
name alone or a combination of both a domain and a hosting account.
Shopping Cart and E-Commerce
A shopping cart is a software used in e-commerce to assist visitors to make purchases online. Upon
checkout, the software calculates the total of the order, including shipping and handling, taxes and
other parameters the owner of the site has previously set. The shopping cart typically provides a
means of collecting the shopper's payment information.
Some shopping carts strictly allow for an item to be added to the basket to start a checkout process
(such as the PayPal shopping cart), other shopping carts actually provides additional features that
the merchant can fully manage the online store.
Shopping cart software consists of two main components:
Storefront: The area of the website that is accessed by the visitor.
Administration: The area of the website that is accessed by the merchant to manage the online
shop.

Learn the Basics of Web Design


When you're setting out to learn web design, the first thing you should remember is that designing
websites is very similar to print design. The basics are all the same. You need to understand space
and layout, how to handle fonts and colors, and put it all together in a way that delivers your
message effectively. Let's take a look at the key elements that go into learning web design. This
is a good resource for beginners, but even experienced designers may be able to hone some skills
with this advice.
Elements of Good Design
Good web design is the same as good design in general. If you understand what makes something
a good design, you'll be able to apply those rules to your websites. The most important elements
in web design are good navigation, concise and effective pages, working links, and, most
importantly, good grammar and spelling. Keep these things in mind as you add color and graphics
and your website will be off to a great start.
How to Layout a Web Page
Many people think that the layout of a web page is the design, and in many ways it is. The layout
is the way the elements are positioned on the page, it is your foundation for images, text,
navigation, etc.
Many designers choose to do their layouts with CSS. It can also be used for elements like fonts,
colors, and other custom styles. This helps ensure consistent and easy to manage features across
your entire website. The best part of using CSS is that when you need to change something, you
can just turn to the CSS and it changes on every page. It really is slick and learning to use CSS can

22
ALI RAZA MANZOOR (WEB DEVELOPER)
end up saving you time and quite a few hassles. In today's online world, it's very important to
consider responsive web design (RWD) as well. The primary focus of RWD is to change the layout
depending on the width of the device viewing the page. Keep in mind that your visitors will be
viewing it on desktops, phones, and tablets of all sizes, so this is more important than ever.
Fonts and Typography
Fonts are the way your text looks on a Web page. This is a vital element because most web pages
include large amounts of text. When you're thinking of design, you need to think about how the
text looks on a micro-level (the font glyphs, font family, etc.) as well as the macro-level
(positioning blocks of text and adjusting the size and shape of the text). It's certainly not as simple
as choosing a font and a few tips will help you get started.
Your Website's Color Scheme
Color is everywhere. It's how we dress up our world and how we see things. Color has meaning
beyond just "red" or "blue" and color is an important design element. If you think about it, every
website has a color scheme. It adds to the brand identity of the site and flows into each page as
well as other marketing materials. Determining your color scheme is a vital step in any design and
should be considered carefully.
Adding Graphics and Images
Graphics are the fun part of building web pages. As the saying goes "a picture is worth 1,000
words" and that's also true in web design. The internet is a very visual medium and eye-catching
photos and graphics can really add to your user engagement. Unlike text, search engines have a
difficult time telling what an image is of unless you give them that information. For that reason,
designers can use IMG tag attributes like the ALT tag to include those important details.
Don't Discount Navigation
Navigation is how your visitors get around from one page to another. It provides movement and
gives visitors the chance to find other elements of your site. You need to make sure that the
structure of your website (the information architecture) makes sense. It also needs to be extremely
easy to find and read so visitors don't have to rely on the search function. The ultimate goal is that
your navigation and inline links help visitors explore your site. The longer you can keep them, the
more likely you'll get them to buy whatever you're selling.
Web Design Software
Most web designers prefer to work in WYSIWYG or "What You See Is What You Get" editors.
These provide a visual interface to the design and let you focus less on coding HTML. Choosing
the right web design software can be a challenge. Many designers prefer Adobe Dreamweaver
because it's easy to use and includes almost every feature you're ever going to need. It does come
at a cost, though, but there is a free trial available. Beginners might want to look into free or online
web editors. These allow you to dabble in web design and build some amazing pages at little to no
cost.
23
ALI RAZA MANZOOR (WEB DEVELOPER)
Systems Analysis and Design
During the late 1970’s and early 1980’s, a systematic approach to developing applications was
developed called the Systems Development Life Cycle (SDLC) (Avison and Fitzgerald, 2003).
The SDLC is a phased approach consisting multiple phases that are designed to improve the
management of information systems development. Other methodologies that have been
established for application development include Joint Application Development (JAD), Rapid
Application Development (RAD), and Prototyping. Prototyping is an adjustment to the SDLC used
to speed up development and delivery of applications (Kendall and Kendall, 2010; Turban et al,
2004).

The SDLC will be used as a benchmark for application development due to it being a complete
methodology containing all of the steps required for development of applications. Due to the nature
of web application development environment, time schedules for development are relatively short,
often being less than one or two months for development (Pressman, 2000). These web
applications require a high degree of granularity that is often not completely suited for the SDLC.
Prototyping generally is more suited to these types of problems due to its ability to speed up the
steps of the SDLC. Therefore, this research will focus its attention on the SDLC and prototyping
methodologies. The majority of the literature covering systems analysis and design focus on the
analysis of information or knowledge used in designing a system or application. These
methodologies are formal attempts used to address the complexity of system development through
standard, predictable approaches (Vessey and Glass, 1998). Developing web applications is a
highly complex problem consisting of many dimensions that must be addressed for web
application development to be successful (McDonald and Welland, 2001):

Short development life-cycle times.

1. Delivery of customized solutions.

2. Multidisciplinary development teams.

3. Small development teams working in parallel on similar tasks.

4. Analysis and Evaluation.

5. Requirements and Testing.

6. Maintenance.

The SDLC covers most of the needs for successful web development minus one critical factor, the
need for short development time. The SDLC has added structure to complex problems that exists
in application development. The basic concept behind the SDLC method is that there is a well-
defined process by which an application is conceived, developed, and implemented. (Kettinger

24
ALI RAZA MANZOOR (WEB DEVELOPER)
and Teng, 1997). The speed at which applications need to be developed and the additional factors
such as navigation and the graphical component adds complexity that is beyond the use of SDLC
by itself.

Prototyping is generally used for more unstructured processes and for rapid development of
applications. There are several methods of prototyping that can be used for application
development. The method focus on by the current research is known as the "Throw Away"
prototype, which is used primarily to clarify and satisfy information requirements and then
discarded. (Kettinger and Teng, 1997). One technique used in the throw away method of
prototyping is to create a visual display or image of what the web pages will look like using a
graphical tool such as Adobe Photoshop or Macromedia Fireworks. This will allow the developers
to quickly create a visual prototype for the users to see what the website will look like and make
any necessary changes. This allows the users to work in iterations decreasing the time of
development.

Web Application Development


Internet applications encompass four general types of web-based systems: Intranets, web-presence
sites, electronic commerce, and extranets (Isakowitz et al, 1998). These systems all have different
functions and goals but are similar in regards to the technology used, namely the protocol known
as Transmission Control Protocol (TCP). TCP is the most commonly used transfer protocol of the
Internet (Altman et al, 2005). The Information used by these web applications is stored in many
places and rapidly changes containing both structured and unstructured formats (Fraternali and
Paolini, 2000). Other differences between web applications and software applications is the
content, including text, graphics, images, audio, and video, which are integrated with procedural
processing (Pressman, 2000).

The speed at which information is desired has also increased resulting in the need for quicker
delivery times for web based applications. Numerous methodologies have been developed and
used in order to respond to the changes brought about in the web development environment.
McDonald and Welland (2001) describe several differences between web-based application
development and traditional software development, such as:

Short Development Life Cycle times (Typically 3 months or less)

Custom made systems integrating software and data

Multidisciplinary development teams

Research has shown that adopting a minimalistic approach to design results in increased
effectiveness (Rosen and Puriton, 2004). Strategic use of graphics can draw users to the site and
sustain their interest. However, excessive use of graphics may overwhelm the users causing them

25
ALI RAZA MANZOOR (WEB DEVELOPER)
to exit the website. This calls for careful planning in the layout and graphical display of the website
during the requirements and planning phases of development.

Many development methodologies have been proposed to address the complexity of web
application development. Each methodology has its own series of phases that may or not be the
same as other methodologies. Escalona and Koch (2002) developed a taxonomy describing
different methodologies and the phases that each methodology contains compared against the
system development life cycle. Most methodologies used for web development focus on designing
and coding the application. Hypermedia Flexible Processing Model (HFPM) strategy is the only
methodology that includes all of the phases of the SDLC. However, HFPM does not state the
techniques to be applied in each of the phases, it only gives the process. No single methodology
listed offers a complete suitable framework for development of web applications (Escalona and
Koch, 2002).

WEB DEVELOPMENT LIFE CYCLE


The purpose of this paper is to propose a new methodology encompassing all the phases of the
SDLC in a suitable way that can be used to develop web based applications quickly in a structured
manner. The Web Development Life Cycle (WDLC) is a new methodology being proposed
specifically for the development of web applications. This methodology is grounded in previous
methodologies found in the literature to create structured process for the highly unstructured
problem of web application development. The WDLC is a hybrid of two former methodologies
known as the Systems Development Life Cycle and Prototyping. The WDLC uses components
from each methodology, combining them into a new approach that will decrease the time of
development, add structure to an unstructured problem, and keep the users involved throughout
the entire development life cycle.

Rosen and Purinton (2004) describe three factors are important to users when using web based
applications: coherence, complexity, and legibility. Coherence involves the ease at which the user
can navigate through the site and includes the understandability of the content contained within
the website. Complexity revolves around the design of the website including the variety of images
that satisfies the users desired to explore the environment. Legibility is rooted in the impression
made by the website to the user. It is the perception that the website is memorable and distinctive.
Internet application design addresses both the database/application development and the graphical
representation to the users (Gellersen, 1999). The visual element of a website encompasses the
website’s aesthetics whereas the database element affects functionality within a website. Both the
aesthetic design and functionality of the website are important but each are distinct from the other.
The graphical design of a web application is often performed by a graphic designer or artist
whereas the database design would be performed by a database administrator or programmer.
Therefore, the WDLC will contain two iterative steps, which include the graphical development
and the functional development.

26
ALI RAZA MANZOOR (WEB DEVELOPER)
Scalability, modifiability, and robustness are important factors that must be addressed in any
system (Ross et al, 2008). Due to the dynamic nature of Internet applications and their need to be
viewable 24 hours a day, 7 days a week, and these factors have become even more prevalent. The
ability to rapidly change content, requirements, and the architecture of Internet applications is
important when designing for scalability. (Fraternali and Paolini, 2000). Lack of scalability is a
problem that has been seen in many large scale IS projects in developing countries (Avgerou,
2008). One phase that few Internet application development methodologies fail to address is the
requirements phase (Escalona and Koch, 2002). Spending a little more time on the front end on
information gathering and analysis will allow for faster implementation of applications on the web
site in the future. Systems that are well designed and thoroughly implemented often display
improved software quality and increased reusability (Pree, 1995). Webbased applications tend to
evolve very quickly with frequent updates and redesigns. These factors often lead to decreased
maintainability and can be very troublesome throughout the life of the application (Gellersen,
1999). The WDLC addresses this issue by dividing the development of Internet applications into
two distinct iterations of the development process:

1. Graphical Development

2. Information Gathering

3. Analysis

4. Design

5. Functional Development

6. Information Gathering

7. Analysis

8. Design

This follows the same concept of the SDLC model using a waterfall approach. However, by
incorporating prototyping methodology, the WDLC become iterative process involving the users
through the development process. By dividing the graphical development and the functional
development into different stages, each of these set of phases can be worked on sequentially or
simultaneously. For instance, if the website has already been designed and developed and a new
application needs to be added, the designers and developers could skip to the functional
development set of phases in the WDLC and add the application to the existing website. By
following proper measures in the graphical development and planning for scalability, future
updates or redesigns will require minimal efforts. Redesigning an existing website would only
require the graphical development phases of the WDLC to be performed since the functionality of
the website would remain unchanged. This creates congruence among the different parts of a web

27
ALI RAZA MANZOOR (WEB DEVELOPER)
site and its applications. Since the design phase of the WDLC uses prototyping, after it has been
tested and works you can implement it as the working system. This creates a four phase approach
to web application development with two of these phases containing 3 steps each.

Information Gathering (Graphical)


The first phase of the WDLC is the information gathering step for designing the website. The
design of a website is extremely important because if it is not appealing to the customer and easy
to navigate, then they will be less likely to return and purchase the products or use the services
offered. The analyst is required to gather information that will assist the graphic designers in
creating an effective layout for the website and determine the various pages will be included. How
information is to be arranged and the navigation through this information should also be discussed
in the information gathering phase of the WDLC.

Analysis (Graphical)
The next step involves analyzing the information acquired and documenting the needs of the
website design. This documentation includes the color schemes to be used along with logos and
other graphics that will be incorporated on the website. The analyst will also be required to outline
the site map entailing how the users will navigate through the website. Incorporating a navigation
elements, search mechanisms, and site map within the website will increase the user’s ability to
find the information they desire (Malak et al, 2010). This is also important for scalability because
it will allow the programmers to create templates and implement cascading style sheets (CSS) into
the site allowing for easy maintenance and updates in the future.

The graphic designers use the acquired information to create an image of what the website should
look like for the developers to use. This will be a graphical representation, or prototype, of the
website that the programmers will use to develop the template. The graphic designers typically
work closely with users (marketing, merchandising, etc.) in charge of leading the efforts for
development of the website. Images of the website pages will also be included in the
documentation.

Graphical Design
The graphical design phase of the WDLC is where the developers use the documentation provided
by the analysts and graphic designers and create a prototype of the website. The only functionality
available at this phase of the WDLC is the ability to navigate through the website. This is where
the programmers create the templates and navigation for the website. Once the prototype has been
finished and tested, the working model will then be used as the actual system.

Information Gathering (Functional)


Phase 2 involves the functional development of the website. During the information gathering
phase for the functionality development, the systems analyst meets with the users to gathering

28
ALI RAZA MANZOOR (WEB DEVELOPER)
requirements for the functionality of the website. They identify the purpose of the website, what
functionality is required, and the different components for each section of the website.

Analysis (Functional)
The functional analysis phase of the WDLC is where the analyst creates Entity Relationship
Diagrams (ERD) and Data Flow Diagrams (DFD) needed for the functionality of the website. They
will then break down the different components of the website into smaller fragments. For example,
if developing an e-commerce website, the developer might create different components such as a
shopping cart, products page, contact page, information page, and a frequently asked questions
page. Then each one of these components will be designed and developed as if they were individual
programs. Once the website’s functionality has been designed and the different components have
been developed, the developer will start creating the physical prototype.

Functional Design
The functional design phase of the WDLC is where the developers start creating the prototype for
each of the components on the website. This is where the functionality of the website is developed.
The web developers work with the users to identify the components of the website that are required
for the implementation. After identifying the critical components, they begin developing the
prototype for those components. The users should be actively involved with the developers as each
component is created. Many times the user knows what they want but do not understand what can
be done in web development. Therefore, the web developer should guide the users and involve
them during the development process.

As functionality is added to the website, the users should test the components and give feedback
to the developer. Each component can be implemented upon completion and successful testing.
This creates an iterative process of the functional phases in the WDLC and increases the speed at
which the website is developed by working in modules.

Implementation
This phase in the WDLC is similar to normal implementation in the SDLC. The prototype is
typically developed on a test server or development server. This allows the users to work with the
developers until the prototype is complete. Once the component being developed is completed, the
database and web page files will be moved to the production server for implementation.

Maintenance
Maintenance is an ongoing step of the WDLC that never ends. Maintenance may include
modifications to existing programs, updating the style sheet to give the website a different look,
or anything that might need to be done to the website once it has been implemented.

29
ALI RAZA MANZOOR (WEB DEVELOPER)
The WDLC is an iterative process, particularly during functional phases of development. Once the
website has been designed there is little need to perform the graphical phases of the WDLC until
a re-design of the website is needed. For each new application or component added to the website
after it has been designed, the systems analyst can start on phase two of the WDLC. For a website
redesign, only phase one will need to be completed because a redesign will change the layout and
look of a website but not the functionality.

Databases
What is Data?
In simple words data can be facts related to any object in consideration.
For example your name, age, height, weight, etc. are some data related to you.
A picture , image , file , pdf etc. can also be considered data.

What is a Database?
Database is a systematic collection of data. Databases support storage and manipulation of data.
Databases make data management easy. Let's discuss few examples.
 An online telephone directory would definitely use database to store data pertaining to
people, phone numbers, other contact details, etc.
 Your electricity service provider is obviously using a database to manage billing, client
related issues, to handle fault data, etc.
Let's also consider the Facebook. It needs to store, manipulate and present data related to members,
their friends, member activities, messages, advertisements and lot more.

What is a Database Management System (DBMS)?


Database Management System (DBMS) is a collection of programs which enables its users to
access database, manipulate data, reporting / representation of data.
It also helps to control access to the database.
Database Management Systems are not a new concept and as such had been first implemented in
1960s.
Charles Bachman’s Integrated Data Store (IDS) is said to be the first DBMS in history.

30
ALI RAZA MANZOOR (WEB DEVELOPER)
With time database technologies evolved a lot while usage and expected functionalities of
databases have been increased immensely.

Types of DBMS
Let's see how the DBMS family got evolved with the time. Following diagram shows the evolution
of DBMS categories.

There are 4 major types of DBMS. Let's look into them in detail.
 Hierarchical - this type of DBMS employs the "parent-child" relationship of storing data.
This type of DBMS is rarely used nowadays. Its structure is like a tree with nodes
representing records and branches representing fields. The windows registry used in
Windows XP is an example of a hierarchical database. Configuration settings are stored as
tree structures with nodes.
 Network DBMS - this type of DBMS supports many-to many relations. This usually
results in complex database structures. RDM Server is an example of a database
management system that implements the network model.
 Relational DBMS - this type of DBMS defines database relationships in form of tables,
also known as relations. Unlike network DBMS, RDBMS does not support many to many
relationships. Relational DBMS usually have pre-defined data types that they can support.
This is the most popular DBMS type in the market. Examples of relational database
management systems include MySQL, Oracle, and Microsoft SQL Server database.
 Object Oriented Relation DBMS - this type supports storage of new data types. The data
to be stored is in form of objects. The objects to be stored in the database have attributes
(i.e. gender, ager) and methods that define what to do with the data. PostgreSQL is an
example of an object oriented relational DBMS.

What is SQL?
Structured Query language (SQL) pronounced as "S-Q-L" or sometimes as "See-Quel" is
actually the standard language for dealing with Relational Databases.
SQL programming can be effectively used to insert, search, update, and delete database records.
In fact it can do lot of things including, but not limited to, optimizing and maintenance of
databases.

31
ALI RAZA MANZOOR (WEB DEVELOPER)
Relational databases like MySQL Database, Oracle, MS SQL server, Sybase, etc. uses SQL! How
to use SQL syntaxes?
SQL syntaxes used in these databases are almost similar, except the fact that some are using few
different syntaxes and even proprietary SQL syntaxes.
SQL Example

SELECT * FROM Members WHERE Age > 30

What is NoSQL?
NoSQL is an upcoming category of Database Management Systems. Its main characteristic is its
non-adherence to Relational Database Concepts. NOSQL means "Not only SQL".
Concept of NoSQL databases grew with internet giants such as Google, Facebook, and Amazon
etc. who deal with gigantic volumes of data.
When you use relational database for massive volumes of data, the system starts getting slow in
terms of response time.
To overcome this, we could of course "scale up" our systems by upgrading our existing hardware.
The alternative to the above problem would be to distribute our database load on multiple hosts as
the load increases.
This is known as "scaling out".
NOSQL database are non-relational databases that scale out better than relational databases and
are designed with web applications in mind.
They do not use SQL to query the data and do not follow strict schemas like relational models.
With NoSQL, ACID (Atomicity, Consistency, Isolation, and Durability) features are not
guaranteed always

Why it makes sense to learn SQL after NOSQL?


With the advantages of NOSQL databases outlined above that scale out better than relational
models, you might be thinking why one would still want to learn about SQL database?
Well, NOSQL databases are sort of highly specialized systems and have their special usage and
limitations. NOSQL suit more for those who handles huge volumes of data. The vast majority, use
relational databases and associated tools.
Relational databases have the following advantages over NOSQL databases;
 SQL (relational) databases have a mature data storage and management model. This is
crucial for enterprise users.

32
ALI RAZA MANZOOR (WEB DEVELOPER)
 SQL databases support the notion of views which allow users to only see data that they are
authorized to view. The data that they are not authorized to see is kept hidden from them.
 SQL databases support stored procedure SQL which allow database developers to
implement part of the business logic into the database.
 SQL databases have better security models compared to NoSQL databases.
The world has not deviated from use of relational databases. There is growing a demand for
professionals who can handle relational databases. Thus learning databases and SQL still holds
merit.

What is Database Design?


Database Design is a collection of processes that facilitate the designing, development,
implementation and maintenance of enterprise data management systems
 It helps produce database systems
 That meet the requirements of the users
 Have high performance.
The main objectives of database designing are to produce logical and physical designs models of
the proposed database system. The logical model concentrates on the data requirements and the
data to be stored independent of physical considerations. It does not concern itself with how the
data will be stored or where it will be stored physically. The physical data design model involves
translating the logical design of the database onto physical media using hardware resources and
software systems such as database management systems (DBMS).

Why Database Design is Important?


Database designing is crucial to high performance database system. Apart from improving the
performance, properly designed database is easy to maintain, improve data consistency and are
cost effective in terms of disk storage space.
Note, the genius of a database is in its design. Data operations using SQL is relatively simple

Database development life cycle

33
ALI RAZA MANZOOR (WEB DEVELOPER)
The database development life cycle has a number of stages that are followed when developing
database systems. The steps in the development life cycle do not necessary have to be followed
religiously in a sequential manner. On small database systems, the database system development
life cycle is usually very simple and does not involve a lot of steps.
In order to fully appreciate the above diagram, let's look at the individual components listed in
each step.

Requirements analysis
 Planning - This stages concerns with planning of entire Database Development Life
Cycle It takes into consideration the Information Systems strategy of the organization.
 System definition - This stage defines the scope and boundaries of the proposed database
system.

Database designing
 Logical model - This stage is concerned with developing a database model based on
requirements. The entire design is on paper without any physical implementations or
specific DBMS considerations.
 Physical model - This stage implements the logical model of the database taking into
account the DBMS and physical implementation factors.

Implementation
 Data conversion and loading - this stage is concerned with importing and converting data
from the old system into the new database.
 Testing - this stage is concerned with the identification of errors in the newly implemented
system. It checks the database against requirement specifications.

Two Types of Database Techniques


1. Normalization
2. ER Modeling
What is Normalization?
Normalization is a database design technique which organizes tables in a manner that reduces
redundancy and dependency of data. It divides larger tables to smaller tables and links them using
relationships. The inventor of the relational model Edgar Codd proposed the theory of
normalization with the introduction of First Normal Form, and he continued to extend theory with
Second and Third Normal Form. Later he joined with Raymond F. Boyce to develop the theory of
Boyce-Codd Normal Form.
Theory of Data Normalization in SQL is still being developed further. For example, there are
discussions even on 6th Normal Form. However, in most practical applications, normalization

34
ALI RAZA MANZOOR (WEB DEVELOPER)
achieves its best in 3rd Normal Form. The evolution of Normalization theories is illustrated
below-

Database Normalization Examples -


Assume a video library maintains a database of movies rented out. Without any normalization, all
information is stored in one table as shown below.

Here you see Movies Rented column has multiple values.


Database Normal Forms
Now let's move into 1st Normal Forms
1NF (First Normal Form) Rules
 Each table cell should contain a single value.
 Each record needs to be unique.
1NF Example

35
ALI RAZA MANZOOR (WEB DEVELOPER)
What is a KEY?
A KEY is a value used to identify a record in a table uniquely. A KEY could be a single column
or combination of multiple columns
Note: Columns in a table that are NOT used to identify a record uniquely are called non-key
columns.

What is a Primary Key?


A primary is a single column value used to identify a database record
uniquely.
It has following attributes
A primary key cannot be NULL
A primary key value must be unique
The primary key values cannot be changed
The primary key must be given a value when a new record is inserted.

What is Composite Key?


A composite key is a primary key composed of multiple columns used to identify a record uniquely
In our database, we have two people with the same name Robert Phil, but they live in different
places.

Hence, we require both Full Name and Address to identify a record uniquely. That is a composite
key.
Let's move into second normal form 2NF
2NF (Second Normal Form) Rules
 Rule 1- Be in 1NF

36
ALI RAZA MANZOOR (WEB DEVELOPER)
 Rule 2- Single Column Primary Key
It is clear that we can't move forward to make our simple database in 2nd Normalization form unless
we partition the table above.

We have divided our 1NF table into two tables viz. Table 1 and Table2. Table 1 contains member
information. Table 2 contains information on movies rented.
We have introduced a new column called Membership_id which is the primary key for table 1.
Records can be uniquely identified in Table 1 using membership id

Database - Foreign Key


In Table 2, Membership_ID is the Foreign Key

37
ALI RAZA MANZOOR (WEB DEVELOPER)
Foreign Key references the primary key of another Table! It helps
connect your Tables

 A foreign key can have a different name from its primary key
 It ensures rows in one table have corresponding rows in another
 Unlike the Primary key, they do not have to be unique. Most
often they aren't
 Foreign keys can be null even though primary keys can not

Why do you need a foreign key?


You will only be able to insert values into your foreign key that exist in the unique key in the
parent table. This helps in referential integrity.

38
ALI RAZA MANZOOR (WEB DEVELOPER)
The above problem can be overcome by declaring membership id from Table2 as foreign key of
membership id from Table1
Now, if somebody tries to insert a value in the membership id field that does not exist in the parent
table, an error will be shown!
What are transitive functional dependencies?
A transitive functional dependency is when changing a non-key column, might cause any of the
other non-key columns to change
Consider the table 1. Changing the non-key column Full Name may change Salutation.

3NF (Third Normal Form) Rules

 Rule 1- Be in 2NF
 Rule 2- Has no transitive functional dependencies

To move our 2NF table into 3NF, we again need to again divide our table.

3NF Example

39
ALI RAZA MANZOOR (WEB DEVELOPER)
We have again divided our tables and created a new table which stores Salutations.
There are no transitive functional dependencies, and hence our table is in 3NF
Now our little example is at a level that cannot further be decomposed to attain higher forms of
normalization. In fact, it is already in higher normalization forms. Separate efforts for moving into
next levels of normalizing data are normally needed in complex databases. However, we will be
discussing next levels of normalizations in brief in the following.
Boyce-Codd Normal Form (BCNF)
Even when a database is in 3rd Normal Form, still there would be anomalies resulted if it has more
than one Candidate Key.
Sometimes is BCNF is also referred as 3.5 Normal Form.
4NF (Fourth Normal Form) Rules
If no database table instance contains two or more, independent and multivalued data describing
the relevant entity, then it is in 4th Normal Form.
5NF (Fifth Normal Form) Rules

40
ALI RAZA MANZOOR (WEB DEVELOPER)
A table is in 5th Normal Form only if it is in 4NF and it cannot be decomposed into any number of
smaller tables without loss of data.
6NF (Sixth Normal Form) Proposed
6th Normal Form is not standardized, yet however, it is being discussed by database experts for
some time. Hopefully, we would have a clear & standardized definition for 6th Normal Form in the
near future...

What is ER Modeling?
Entity Relationship Modeling (ER Modeling) is a graphical approach to database design. It uses
Entity/Relationship to represent real world objects.
An Entity is a thing or object in real world that is distinguishable from surrounding environment.
For example each employee of an organization is a separate entity. Following are some of major
characteristics of entities.
 An entity has a set of properties.
 Entity properties can have values.
Let's consider our first example again. An employee of an organization is an entity. If "Peter" is a
programmer (an employee) at Microsoft, he can have attributes (properties) like name, age,
weight, height, etc. It is obvious that those do hold values relevant to him.
Each attribute can have Values. In most cases single attribute have one value. But it is possible for
attributes have multiple values also. For example Peter's age has a single value. But his "phone
numbers" property can have multiple values.
Entities can have relationships with each other. Let's consider a simplest example. Assume that
each Microsoft Programmer is given a Computer. It is clear that that Peter's Computer is also an
entity. Peter is using that computer and the same computer is used by Peter. In other words there
is a mutual relationship among Peter and his computer.
In Entity Relationship Modeling, we model entities, their attributes and relationships among
entities.

Enhanced Entity Relationship (EER) Model


Enhanced Entity Relationship (EER) Model is a high level data model which provides extensions
to original Entity Relationship (ER) model. EER Models supports more details design. EER
Modeling emerged as a solution for modeling highly complex databases.
EER uses UML notation. UML is the acronym for Unified Modeling Language; it is a general
purpose modeling language used when designing object oriented systems. Entities are represented

41
ALI RAZA MANZOOR (WEB DEVELOPER)
as class diagrams. Relationships are represented as associations between entities. The diagram
shown below illustrates an ER diagram using the UML notation.

Why use ER Model?


Now you may think why use ER modeling when we can simply create the database and all of its
objects without ER modeling? One of the challenges faced when designing database is the fact
that designers, developers and end-users tend to view data and its usage differently. If this situation
is left unchecked, we can end up producing a database system that does not meet the requirements
of the users. Communication tools understood by all stakeholders (technical as well non-technical
users) are critical in producing database systems that meet the requirements of the users. ER
models are examples of such tools.
ER diagrams also increase user productivity as they can be easily translated into relational tables.
Case Study: ER diagram for "MyFlix" Video Library
Let's now work with the MyFlix Video Library database system to help understand the concept of
ER diagrams. We will using this database for all hand-on in the remainder of this tutorials MyFlix
is a business entity that rents out movies to its members. MyFlix has been storing its records
manually. The management now wants to move to a DBMS
Let's look at the steps to develop EER diagram for this database-
1. Identify the entities and determine the relationships that exist among them.
2. Each entity, attribute and relationship, should have appropriate names that can be easily
understood by the non-technical people as well.
3. Relationships should not be connected directly to each other. Relationships should connect
entities.
4. Each attribute in a given entity should have a unique name.

42
ALI RAZA MANZOOR (WEB DEVELOPER)
Entities in the "MyFlix" library
The entities to be included in our ER diagram are;
 Members - this entity will hold member information.
 Movies - this entity will hold information regarding movies
 Categories - this entity will hold information that places movies into different categories
such as "Drama", "Action", and "Epic" etc.
 Movie Rentals - this entity will hold information that about movies rented out to members.
 Payments - this entity will hold information about the payments made by members.

Defining the relationships among entities


Members and movies
The following holds true regarding the interactions between the two entities.

 A member can rent a more than movie in a given period.


 A movie can be rented by more than one member in a given period.

From the above scenario, we can see that the nature of the relationship is many-to-many.
Relational databases do not support many-to-many relationships. We need to introduce a
junction entity. This is the role that the MovieRentals entity plays. It has a one-to-many
relationship with the members table and another one-to-many relationship with movies table.
Movies and categories entities
The following holds true about movies and categories.
A movie can only belong to one category but a category can have more than one movie.
We can deduce from this that the nature of the relation between categories and movies table is one-
to-many.
Members and payments entities
The following holds true about members and payments
A member can only have one account but can make a number of payments.
We can deduce from this that the nature of the relationship between members and payments entities
is one-to-many.

What is HTML?
HTML is the standard markup language for creating Web pages.
HTML stands for Hyper Text Markup Language
HTML describes the structure of Web pages using markup
43
ALI RAZA MANZOOR (WEB DEVELOPER)
HTML elements are the building blocks of HTML pages
Example:
<!DOCTYPE html>
<html>
<head>
<title>PageTitle</title>
</head>
<body>
<h1>MyFirstHeading</h1>
<p>Myfirstparagraph.</p>
</body></html>
 The <!DOCTYPE html> declaration defines this document to be HTML5
 The <html> element is the root element of an HTML page
 The <head> element contains meta information about the document
 The <title> element specifies a title for the document
 The <body> element contains the visible page content
 The <h1> element defines a large heading
 The <p> element defines a paragraph

HTML Editors
Web pages can be created and modified by using professional HTML editors.
However, for learning HTML we recommend a simple text editor like Notepad (PC) or
Notepad++.Simple text editor is a good way to learn HTML.

Save the HTML Page


Save the file on your computer. Select File > Save as in the Notepad menu.
Name:
Name.html

HTML Headings
HTML headings are defined with the <h1> to <h6> tags.
<h1> defines the most important heading. <h6> defines the least important heading:
Example:
<!DOCTYPE html>

44
ALI RAZA MANZOOR (WEB DEVELOPER)
<html>
<body>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>
</body>
</html>

HTML Paragraphs
HTML paragraphs are defined with the <p> tag:
<!DOCTYPE html>
<html><body><p>This is a paragraph.</p>
<p>This is another paragraph.</p></body></html>
HTML Links
HTML links are defined with the <a> tag:
The link's destination is specified in the href attribute.
Attributes are used to provide additional information about HTML elements.
<a href="file Name”>click me some one</a>
HTML Buttons
HTML buttons are defined with the <button> tag:
<button>Click me</button>
Empty(Break line) HTML Elements
<br>
HTML Lists
Unoder list

45
ALI RAZA MANZOOR (WEB DEVELOPER)
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
oder list
An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.
The list items will be marked with numbers by default:
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>

HTML Attributes
 All HTML elements can have attributes
 Attributes provide additional information about an element
 Attributes are always specified in the start tag
 Attributes usually come in name/value pairs like: name="value"

The href Attribute


<a href="filename">This is a link</a>

The src Attribute / width /height/image tag


HTML images are defined with the <img> tag.
The source file (src), alternative text (alt), width, and height are provided as attributes:
Src=”Imagepath/imagenamne”
Width define the image width ,height define image height and alt define
alternative name of image
<img src="img.jpg" alt=”alternative name” width="500" height="600">
Font Size Change
<h1 style="font-size:60px;">Heading 1</h1>

HTML Horizontal Rules


<p>This is Some Text>/p?
46
ALI RAZA MANZOOR (WEB DEVELOPER)
<h2>This is heading 2</h2>
HTML Fonts
The font-family property defines the font to be used for an HTML element:
<h1 style="font-family:verdana;">This is a heading</h1>
HTML Text Alignment
<h1 style="text-align:center;">Centered Heading</h1>
<h1 style="text-align:left;">Centered Heading</h1>
<h1 style="text-align:right;">Centered Heading</h1>
The HTML <pre> Element
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.
Example:
<html><body>
<p>The pre tag preserves both spaces and line breaks:</p>
<pre>
My Bonnie lies over the ocean.
My Bonnie lies over the sea.
My Bonnie lies over the ocean.
</pre>
</body></html>
HTML Styles
Setting the style of an HTML element, can be done with the style attribute.
The HTML style attribute has the following syntax:
<h1 style="property:value;"></h1>
Example:
<!DOCTYPE html>
<html>
<body>
<p>I am normal</p>

47
ALI RAZA MANZOOR (WEB DEVELOPER)
<p style="color:red;">I am red</p>
<p style="color:blue;">I am blue</p>
<p style="font-size:50px;">I am big</p></body></html

HTML Background Color


<body style="background-color:powderblue;"></body>
<p style="background-color:blue;"></p>
HTML Text Color
<h1 style="color:blue;">This Is a Heading</h1>
<p style="color:red;">This is a paragraph.</p>

HTML Text Formatting


HTML also defines special elements for defining text with a special meaning.
HTML uses elements like <b> and <i> for formatting output, like bold or italic text.
 <b> - Bold text
 <strong> - Important text
 <i> - Italic text
 <em> - Emphasized text
 <mark> - Marked text
 <small> - Small text
 <del> - Deleted text
 <ins> - Inserted text
 <sub> - Subscript text
 <sup> - Superscript text
Example:
<!DOCTYPE html>
<html>
<body>
<p><b>This text is bold</b></p>
<p><i>This text is italic</i></p>
<strong>this is srrong text</strong>
<p>This is<sub> subscript</sub> and <sup>superscript</sup></p>
<del> Deleted text</del>

48
ALI RAZA MANZOOR (WEB DEVELOPER)
<em> - Emphasized text</em><br>
<mark> - Marked text</mark><br>
<small> - Small text<small><br>
<ins> - Inserted text</ins></body>
</html>
HTML <q> Quotations And <blockquote>
<q> for short quotation
The HTML <blockquote> element defines a section that is quoted from another source.
<!DOCTYPE html>
<html>
<body>
<p>paragraph simple example in p tag:</p>
<q>this is double qoutes </q>
<blockquote cite="index.html">
For 50 years, WWF has been protecting the future of nature.
</blockquote>
</body>
</html>
HTML Comment Tags

<!—comment area -->

Background Color &Text Color Border Color

<h1 style="background-color:DodgerBlue;">Hello World</h1>


<h1 style="color:Tomato;">Hello World</h1>
<h1 style="border:2px solid Tomato;">Hello World</h1>

HTML Styles - CSS


CSS stands for Cascading Style Sheets.
CSS can be added to HTML elements in 3 ways:

49
ALI RAZA MANZOOR (WEB DEVELOPER)
 Inline - by using the style attribute in HTML elements
 Internal - by using a <style> element in the <head> section
 External - by using an external CSS file
Inline CSS
Inline css use in html file and html Tag
<h1 style="color:red;">This is a Blue Heading</h1>

Internal CSS
An internal CSS is defined in the <head> section of an HTML page, within a <style> element:

Example:

<!DOCTYPE html>
<html>
<head>
<style>
body {background-color: blue;}
h1 {color: pink;}
p {color: red;}
</style>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a Paragraph</p>
</body>
</html>
External CSS
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>

50
ALI RAZA MANZOOR (WEB DEVELOPER)
<body>
<h1>This is a Heading</h1>
<p>This is a Paragraph</p>
</body></html>

Style.css file
body {background-color: blue;}
h1 {color: pink;}
p {color: red;}

CSS Padding
The CSS padding property defines a padding (space) between the text and the border:
Example:
<html>
<head>
<style>
p.ex1 {
border: 1px solid red;
padding: 35px;
padding-bottom: 25px;
padding-left: 50px;
padding-right: 150px;
padding-top: 25px;
}
</style>
</head>
<body>
<h1>The padding Property</h1>
<p class="ex1">This paragraph has a padding of 35 pixels on all four sides.</p>
<p><strong>Note:</strong> Padding creates extra space within an element, while margin creates
extra space around an element!</p>
</body>

51
ALI RAZA MANZOOR (WEB DEVELOPER)
</html>
CSS Margin/ Id Attribute/ Class Attribute
The HTML class attribute is used to define equal styles for elements with the same class
name.So, all HTML elements with the same class attribute will have the same format and style.
The id attribute specifies a unique id for an HTML element (the value must be unique within the
HTML document).The id value can be used by CSS and JavaScript to perform certain tasks for a
unique element with the specified id value.In CSS, to select an element with a specific id, write a
hash (#) character, followed by the id of the element:
Example:
<!DOCTYPE html>
<html>
<head>
<style>
#topper{
border: solid;
border-width: 1px;
margin-top:200px;
margin-left:200px;
margin-bottom:100px;
color:black;
margin-right:100px;
}
h1.hea{
padding-top:20px;
padding-bottom:20px;
padding-right:20px;
padding-left:20px;
background-color:red;
border: dotted;
border-width: 3px;
color:red;
52
ALI RAZA MANZOOR (WEB DEVELOPER)
}
</style>
</head>
<body>
<h1>The margin-right Property</h1>
<!--heading class call -->
<h1 class="hea">heading class change</h1>
<h1>heading 2 change</h1>
<p id="toper">A paragraph with a pixels </p>
</body>
</html>

HTML Links – Hyperlinks


You can click on a link and jump to another document.
<a href="url">link text</a>

HTML Links - The target Attribute


 _blank - Opens the linked document in a new window or tab
 _self - Opens the linked document in the same window/tab as it was clicked (this is default)
 _parent - Opens the linked document in the parent frame
 _top - Opens the linked document in the full body of the window
 framename - Opens the linked document in a named frame
Example:
 <a href="google.com/" target="_blank">Visit W3Schools!</a>
 <a href=" google.com/" target="_top">HTML5 tutorial!</a>

Image as Link
<a href="first.html">
<img src="ali.png" alt="aliimage" style="width:42px;height:42px;border:0;">
</a>

Link Titles
<!DOCTYPE html>

53
ALI RAZA MANZOOR (WEB DEVELOPER)
<html>
<body>
<h2>Link Titles</h2>
<a href="https://www.google.com/" title="googel page">Visit our HTML Tutorial</a>
</body>
</html>

HTML Table
<html>
<body>
<table border="1" style="color:yellow; border: 1px solid black; border-collapse: collapse; "
align="center" width="200" height="200">
<tr>
<th style="background-color:red">cities</th>
<th>Savings</th>
</tr>
<tr>
<td>city</td>
<td>city1</td>
</tr>
<tr>
<td>city2</td>
<td>city3</td>
</tr>
</table>
</body>
</html>
Explain Example
<tr>table Row
<table>For Table
<td> Table Column
54
ALI RAZA MANZOOR (WEB DEVELOPER)
<th> Table Heading
Collapsed Borders/Boder Spacing/Colspan/RowSpan
This property use for table multiple lines into one line
Border spacing property use for spacing in table border
Colspan merge the table column
Rowspan merge the table Row
table{border-collapse: collapse;
border-spacing: 5px ;}
Example:
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
border-spacing: 5px ;
}
th, td {
padding: 5px;
text-align: left;
}
</style>
</head>
<body>
<table style="width:100%">
<tr>
<th colspan="2">Heading:</th
</tr>
<tr>
<th>Name:</th>
55
ALI RAZA MANZOOR (WEB DEVELOPER)
<td>ali</td>
</tr>
<tr>
<th>roll No</th>
<td>2012</td>
</tr>
<tr>
<th rowspan="2">Telephone:</th>
<td>55577854</td>
</tr>
<tr>
<td>55577855</td>
</tr>
</table>
</body>
</html>

HTML Block and Inline Elements


Block-level Elements
A block-level element always starts on a new line and takes up the full width available (stretches
out to the left and right as far as it can).
The <div> element is a block-level element.
Simple Example
<!DOCTYPE html>
<html>
<head>
<title>div</title>
</head>
<body>
<div style="width:100%;"> <!-- Main Div -->

56
ALI RAZA MANZOOR (WEB DEVELOPER)
<div style="float:left; width:20%;">
Left <!-- Set Div As your requirement -->
</div>
<div style="float:left; width:80%; margin-left:10px;">
Right <!-- Set Div As your requirement -->
</div></div>
</body>
</html>
Other Example
<!DOCTYPE html>
<html>
<head>
<title>div</title>
</head>
<body><!-- main div -->
<div>
<!-- upper div -->
<div>
<div style="background-color: red; float:right; width:35%;">html</div>
<div style="background-color: blue; float: left; width: 25%">css</div>
<div style="background-color: gray; float: center; width:70%;">java</div>
</div>
<!-- middle div -->
<div>
<div style="background-color: black; float:right; width:50%;">html</div>
<div style="background-color: yellow; float:left; width:50%;">java</div>
</div>
<!-- lower div -->
<div>
<div style="background-color: pink; float:left; width:25%;">html</div>
57
ALI RAZA MANZOOR (WEB DEVELOPER)
<div style="background-color: blue; float:left; width:25%;">html</div>
<div style="background-color: pink; float:right; width:25%;">fiffif</div>
<div style="background-color: red; float:right; width:25%;">html
</div>
</div>
</body>
</html>

Inline Element
An inline element does not start on a new line and only takes up as much width as necessary.

This is an inline <span> element inside a paragraph.

<html>
<body>
<span>Hello</span>
<span>World</span>
</body>
</html>

HTML Iframes
An iframe is used to display a web page within a web page.
Example:
<!DOCTYPE html>
<html>
<body>
<h2>Iframe - Target for a Link</h2>
<iframe height="300" width="80%" src="radio.html" name="iframe1" style="border:2px solid
red;"></iframe>
<p><a href="ifram.html" target="iframe1">google per jao</a></p>
<p>When the target of a link matches the name of an iframe, the link will open in the iframe.</p>
</body>
58
ALI RAZA MANZOOR (WEB DEVELOPER)
</html>
HTML Layout Elements
Websites often display content in multiple columns (like a magazine or newspaper).
HTML5 offers new semantic elements that define the different parts of a web page:

 <header> - Defines a header for a document or a section


 <nav> - Defines a container for navigation links
 <section> - Defines a section in a document
 <article> - Defines an independent self-contained article
 <aside> - Defines content aside from the content (like a sidebar)
 <footer> - Defines a footer for a document or a section
 <details> - Defines additional details
<summary> - Defines a heading for the <details> element
<!DOCTYPE html>
<html lang="en">
<head>
<title>CSS Template</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
*{
box-sizing: border-box;
}
body {
font-family: Arial, Helvetica, sans-serif;

59
ALI RAZA MANZOOR (WEB DEVELOPER)
}
/* Style the header */
header {
background-color: #666;
padding: 30px;
text-align: center;
font-size: 35px;
color: white;
}
/* Create two columns/boxes that floats next to each other */
nav {
float: left;
width: 30%;
height: 300px; /* only for demonstration, should be removed */
background: #ccc;
padding: 20px;
}
/* Style the list inside the menu */
nav ul {
list-style-type: none;
padding: 0;
}
article {
float: left;
padding: 20px;
width: 70%;
background-color: #f1f1f1;
height: 300px; /* only for demonstration, should be removed */

60
ALI RAZA MANZOOR (WEB DEVELOPER)
}
/* Clear floats after the columns */
section:after {
content: "";
display: table;
clear: both;
}
/* Style the footer */
footer {
background-color: #777;
padding: 10px;
text-align: center;
color: white;
}
/* Responsive layout - makes the two columns/boxes stack on top of each other instead of next to
each other, on small screens */
@media (max-width: 600px) {
nav, article {
width: 100%;
height: auto;
}
}
</style>
</head>
<body>
<h2>CSS Layout Float</h2>
<p>In this example, we have created a header, two columns/boxes and a footer. On smaller
screens, the columns will stack on top of each other.</p>

61
ALI RAZA MANZOOR (WEB DEVELOPER)
<p>Resize the browser window to see the responsive effect (you will learn more about this in our
next chapter - HTML Responsive.)</p>
<header>
<h2>Cities</h2>
</header>

<section>
<nav>
<ul>
<li><a href="#">London</a></li>
<li><a href="#">Paris</a></li>
<li><a href="#">Tokyo</a></li>
</ul>
</nav>
<article>
<h1>London</h1>
<p>London is the capital city of England. It is the most populous city in the United Kingdom,
with a metropolitan area of over 13 million inhabitants.</p>
<p>Standing on the River Thames, London has been a major settlement for two millennia, its
history going back to its founding by the Romans, who named it Londinium.</p>
</article>
</section>
<footer>
<p>Footer</p>
</footer>
</body>
</html>
The float Property
The float property is used for positioning and layout on web pages.

62
ALI RAZA MANZOOR (WEB DEVELOPER)
The float property can have one of the following values:
 Left - The element floats to the left of its container
 Right- The element floats to the right of its container
 None - The element does not float (will be displayed just where it occurs in the text). This
is default
 Inherit - The element inherits the float value of its parent
Example:
<!DOCTYPE htmlc>
<html>
<head>
<style>
p{ float: right; }
</style>
</head>
<body>
<p>In this example, the image will float to the right in the paragraph, and the text in the paragraph
will wrap around the image.</p>
</body>
</html>

CSS Outline
An outline is a line that is drawn around elements, OUTSIDE the borders, to make the element
"stand out".
CSS has the following outline properties:
 outline-style
 outline-color
 outline-width
 outline-offset
 outline

Outline Style
The outline-style property specifies the style of the outline, and can have one of the
following values:

63
ALI RAZA MANZOOR (WEB DEVELOPER)
 dotted - Defines a dotted outline
 dashed - Defines a dashed outline
 solid - Defines a solid outline
 double - Defines a double outline
 groove - Defines a 3D grooved outline
 ridge - Defines a 3D ridged outline
 inset - Defines a 3D inset outline
 outset - Defines a 3D outset outline
 none - Defines no outline
 hidden - Defines a hidden outline
Example:
<!DOCTYPE html>
<html><head><style>
p {outline-color:red;} p.dotted {outline-style: dotted;} p.dashed {outline-style: dashed;} p.solid
{outline-style: solid;} p.double{outline-style: double;} p.groove {outline-style: groove;}
p.ridge {outline-style: ridge;}p.inset {outline-style: inset;}p.outset {outline-style: outset;}
</style>
</head>
<body>
<h2>The outline-style Property</h2>
<p class="dotted">A dotted outline</p>
<p class="dashed">A dashed outline</p>
<p class="solid">A solid outline</p>
<p class="double">A double outline</p>
<p class="groove">A groove outline. The effect depends on the outline-color value.</p>
<p class="ridge">A ridge outline. The effect depends on the outline-color value.</p>
<p class="inset">An inset outline. The effect depends on the outline-color value.</p>
<p class="outset">An outset outline. The effect depends on the outline-color value.</p>
</body></html>

Outline Color
The outline-color property is used to set the color of the outline.
The color can be set by:

64
ALI RAZA MANZOOR (WEB DEVELOPER)
 Name - specify a color name, like "red"
 RGB - specify a RGB value, like "rgb(255,0,0)"
 Hex - specify a hex value, like "#ff0000"
 Invert - performs a color inversion (which ensures that the outline is visible, regardless of
color background)
Example:
<!DOCTYPE html>
<html>
<head><style>
p.ex1 { border: 1px solid black; outline-style: solid; outline-color: red;}
p.ex2 {border: 1px solid black;
outline-style: double; outline-color: green;}
p.ex3 {
border: 1px solid black; outline-style: outset; outline-color: yellow;}
</style></head>
<body>
<h2>The outline-color Property</h2>
<p class="ex1">A solid red outline.</p>
<p class="ex2">A double green outline.</p>
<p class="ex3">An outset yellow outline.</p>
</body></html>

Outline Width
The outline-width property specifies the width of the outline, and can have one of the
following values:
 Thin (typically 1px)
 Medium (typically 3px)
 Thick (typically 5px)
 A specific size (in px, pt, cm, em, etc)
The following example shows some outlines with different widths:
Example:
<!DOCTYPE html>
<html><head><style>
65
ALI RAZA MANZOOR (WEB DEVELOPER)
p.ex1 {border: 1px solid black; outline-style: solid;outline-color: red;
outline-width: thin;}
p.ex2 {border: 1px solid black;outline-style: solid; outline-color: red;
outline-width: medium;}
p.ex3 { border: 1px solid black;outline-style: solid;
outline-color: red; outline-width: thick;}
p.ex4 { border: 1px solid black: outline-style: solid;
outline-color: red; outline-width: 10px;}</style></head>
<body>
<h2>The outline-width Property</h2>
<p class="ex1">A thin outline.</p>
<p class="ex2">A medium outline.</p>
<p class="ex3">A thick outline.</p>
<p class="ex4">A 4px thick outline.</p>
</body></html>
Outline - Shorthand property
The outline property is a shorthand property for setting the following individual outline
properties:
 outline-width
 outline-style (required)
 outline-color
The outline property is specified as one, two, or three values from the list above. The order of
the values does not matter.
The following example shows some outlines specified with the shorthand outline property:
Example:
<!DOCTYPE html>
<html>
<head><style>
p.ex1 {outline: dashed;}
p.ex2 {outline: dotted red;}
p.ex3 {outline: 5px solid yellow;}
66
ALI RAZA MANZOOR (WEB DEVELOPER)
p.ex4 {outline: thick ridge pink;}
</style></head>
<body>
<h2>The outline Property</h2>
<p class="ex1">A dashed outline.</p>
<p class="ex2">A dotted red outline.</p>
<p class="ex3">A 5px solid yellow outline.</p>
<p class="ex4">A thick ridge pink outline.</p>
</body>
</html>
Outline Offset
The outline-offset property adds space between an outline and the edge/border of an
element. The space between an element and its outline is transparent.
The following example specifies an outline 15px outside the border edge:
Example:
<!DOCTYPE html>
<html>
<head>
<style>
p{
margin: 30px;
border: 1px solid black;
outline: 1px solid red;
outline-offset: 10px;
}
</style>
</head>
<body>

<h2>The outline-offset Property</h2>

67
ALI RAZA MANZOOR (WEB DEVELOPER)
<p>This paragraph has an outline 15px outside the border edge.</p>
</body></html>

CSS Text
The other text-decoration values are used to decorate text:
Example:
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
text-decoration: overline;
text-decoration-color: red;
}
h2 {
text-decoration: line-through;
}
h3 {
text-decoration: underline;
}
</style></head>
<body>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
</body></html>

CSS text-decoration-style/text-justify
The text-decoration-style property sets the style of the text decoration (like solid, wavy,
dotted, dashed, double).
68
ALI RAZA MANZOOR (WEB DEVELOPER)
The text-justify property specifies the justification method of text when text-align is set to
"justify".
text-decoration-style: solid;
text-decoration-style: wavy;
text-decoration-style: double;
text-indent: 20px;
text-align: justify;

Text Transformation/Text Decoration


Text Transformation
The text-transform property is used to specify uppercase and lowercase letters in a text.
It can be used to turn everything into uppercase or lowercase letters, or capitalize the first letter of
each word:

Text Decoration
The text-decoration property is used to set or remove decorations from text.
The value text-decoration: none; is often used to remove underlines from links:
Example:
<!DOCTYPE html>
<html>
<head>
<style>
p { text-indent: 50px;}
p.uppercase {text-transform: uppercase;}
a { text-decoration: none;}
p.lowercase {text-transform: lowercase;}
p.capitalize { text-transform: capitalize;}
</style></head>
<body>
<p>A link with no underline: <a href="https://www.google.com">click</a></p>

69
ALI RAZA MANZOOR (WEB DEVELOPER)
<p cla<p>A link with no underline: <a
href="https://www.google.com">click</a></p>ss="uppercase">In my younger and more
vulnerable years my father gave me some advice that I've been turning over in my mind ever since.
'Whenever you feel like criticizing anyone,' he told me, 'just remember that all the people in this
world haven't had the advantages that you've had..</p>
<p class="lowercase">This is some text.</p>
<p class="capitalize">This is some text.</p>
</body>
</html>

Letter Spacing/ Line Height/ Text Direction/ Word Spacing/


Text Shadow
Letter Spacing
The letter-spacing property is used to specify the space between the characters in a text.The
following example demonstrates how to increase or decrease the space between characters:
Line Height
The line-height property is used to specify the space between lines:
Text Direction
The direction property is used to change the text direction of an element:
Word Spacing
The word-spacing property is used to specify the space between the words in a text.
The following example demonstrates how to increase or decrease the space between words:
Text Shadow
The text-shadow property adds shadow to text.
The following example specifies the position of the horizontal shadow (3px), the position of the
vertical shadow (2px) and the color of the shadow (red):
Example:
<!DOCTYPE html>
<html>
<head>
<style>

70
ALI RAZA MANZOOR (WEB DEVELOPER)
h1 { letter-spacing: 3px;
word-spacing: 10px;}
h2 {
letter-spacing: -1px;
word-spacing: 5px;
text-shadow: 3px 2px red;}
p.small { line-height: 0.7;}
p.big { line-height: 1.8;}
p.ex1 {direction: ltl;}
</style></head>
<body>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<p>
This is a paragraph with a standard line-height.<br>
The default line height in most browsers is about 110% to 120%.<br>
</p>
<p class="ex1"><bdo dir="rtl">This is right-to-left text direction.</bdo></p>
<p class="small">
This is a paragraph with a smaller line-height.<br>
This is a paragraph with a smaller line-height.<br></p>
<p class="big">
This is a paragraph with a bigger line-height.<br>
This is a paragraph with a bigger line-height.<br>
</p></body></html>

Different List Item Markers


The list-style-type property specifies the type of list item marker.
The following example shows some of the available list item markers:

71
ALI RAZA MANZOOR (WEB DEVELOPER)
An Image as The List Item Marker
The list-style-image property specifies an image as the list item marker:
Example:
<!DOCTYPE html>
<html>
<head>
<style>
.ul1{ list-style-image: url('sqpurple.gif');
}
ul.a {
list-style-type: circle;
}
ul.b { list-style-type: square;}
ol.c {
list-style-type: upper-roman;
}
ol.d {
list-style-type: lower-alpha;
}
</style>
</head>
<body>
<p>Example of unordered lists:</p>
<ul class="ul1">
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>
<ul class="a">

72
ALI RAZA MANZOOR (WEB DEVELOPER)
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>
<ul class="b">
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>
<p>Example of ordered lists:</p>
<ol class="c">
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ol>
<ol class="d">
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ol>

</body>
</html>

Override The Default Display Value


As mentioned, every element has a default display value. However, you can override this.
Changing an inline element to a block element, or vice versa, can be useful for making the page
look a specific way, and still follow the web standards.
A common example is making inline <li> elements for horizontal menus:
Example:
<!DOCTYPE html>
73
ALI RAZA MANZOOR (WEB DEVELOPER)
<html>
<head>
<style>
a{
display: block;
}
.a1{
display: inline;
}
</style>
</head>
<body>

<p>Display links as block elements:</p>

<a href="#" target="_blank">HTML</a>


<a href="#" target="_blank">CSS</a>
<a href="#" target="_blank" class="a1">JavaScript</a>
<a href="#" target="_blank" class="a1">JavaScript</a>

<a href="#" target="_blank" class="a1">JavaScript</a>

</body>
</html>

CSS Layout - width and max-width


Using width, max-width and margin: auto;
<!DOCTYPE html>
<html>

74
ALI RAZA MANZOOR (WEB DEVELOPER)
<head>
<style>
div.ex1 {
width:500px;
margin: auto;
border: 3px solid #73AD21;
}
div.ex2 {
max-width:500px;
margin: auto;
border: 3px solid #73AD21;
}
</style>
</head>
<body>
<div class="ex1">This div element has width: 500px;</div>
<br>
<div class="ex2">This div element has max-width: 500px;</div>
<p><strong>Tip:</strong> Drag the browser window to smaller than 500px wide, to see the
difference between the two divs!</p>
</body></html>

CSS Layout - The Position Property


The position property specifies the type of positioning method used for an element (static, relative,
fixed, absolute or sticky).
The position Property
The position property specifies the type of positioning method used for an element.
There are five different position values:
 Static
 Relative
 Fixed
75
ALI RAZA MANZOOR (WEB DEVELOPER)
 Absolute
 Sticky

position: static;
HTML elements are positioned static by default.
Static positioned elements are not affected by the top, bottom, left, and right properties.
An element with position: static; is not positioned in any special way; it is always
positioned according to the normal flow of the page

position: relative;
An element with position: relative; is positioned relative to its normal position.
Setting the top, right, bottom, and left properties of a relatively-positioned element will cause it to
be adjusted away from its normal position. Other content will not be adjusted to fit into any gap
left by the element.

position: fixed;
An element with position: fixed; is positioned relative to the viewport, which means it
always stays in the same place even if the page is scrolled. The top, right, bottom, and left
properties are used to position the element.
A fixed element does not leave a gap in the page where it would normally have been located.

position: absolute;
An element with position: absolute; is positioned relative to the nearest positioned
ancestor (instead of positioned relative to the viewport, like fixed).
However; if an absolute positioned element has no positioned ancestors, it uses the document body,
and moves along with page scrolling.

position: sticky;
An element with position: sticky; is positioned based on the user's scroll position.
A sticky element toggles between relative and fixed, depending on the scroll position. It is
positioned relative until a given offset position is met in the viewport - then it "sticks" in place
(like position:fixed).

76
ALI RAZA MANZOOR (WEB DEVELOPER)
Example:
<!DOCTYPE html>
<html>
<head>
<style>
div.static {
position: static;
border: 3px solid #73AD21;
}
div.relative {
position: relative;
left: 30px;
border: 3px solid #73AD21;
}
div.fixed {
position: fixed;
bottom: 0;
right: 0;
width: 300px;
border: 3px solid #73AD21;
}
div.relative {
position: relative;
width: 400px;
height: 200px;
border: 3px solid #73AD21;
}

77
ALI RAZA MANZOOR (WEB DEVELOPER)
div.absolute {
position: absolute;
top: 80px;
right: 0;
width: 200px;
height: 100px;
border: 3px solid #73AD21;
}
div.sticky {
position: -webkit-sticky;
position: sticky;
top: 0;
padding: 5px;
background-color: #cae8ca;
border: 2px solid #4CAF50;
}
img {
position: absolute;
left: 0px;
top: 0px;
z-index: -1;
}
</style>
</head>
<body>
<h2>position: static;</h2>
<div class="static">
This div element has position: static;
</div>
<div class="relative">

78
ALI RAZA MANZOOR (WEB DEVELOPER)
This div element has position: relative;
</div>
<div class="fixed">
This div element has position: fixed;
</div>
<div class="relative">This div element has position: relative;
<div class="absolute">This div element has position: absolute;</div>
</div>
<div class="sticky">I am sticky!</div>
<img src="ali.png" width="100" height="140">
<p>Because the image has a z-index of -1, it will be placed behind the text.</p>
</body>
</html>

CSS Overflow
The overflow property specifies whether to clip content or to add scrollbars when the content of
an element is too big to fit in a specified area.
The overflow property has the following values:
 visible - Default. The overflow is not clipped. It renders outside the element's box
 hidden - The overflow is clipped, and the rest of the content will be invisible
 scroll - The overflow is clipped, but a scrollbar is added to see the rest of the content
 auto - If overflow is clipped, a scrollbar should be added to see the rest of the content
Example:
<html>
<head>
<style>
div {
background-color: #eee;
width: 200px;
height: 50px;
border: 1px dotted black;

79
ALI RAZA MANZOOR (WEB DEVELOPER)
overflow: visible;
}
.divhidden {
background-color: #eee;
width: 200px;
height: 50px;
border: 1px dotted black;
overflow: hidden;
}
.divscroll {
background-color: #eee;
width: 200px;
height: 100px;
border: 1px dotted black;
overflow: scroll;
}
.divauto {
background-color: #eee;
width: 200px;
height: 50px;
border: 1px dotted black;
overflow: auto;
}</style>
</head>
<body>
<h2>CSS Overflow</h2>
<div>You can use the overflow property when you want to have better
control of the layout.</div><br><br>
<div class="divhidden">You can use the overflow property when you want to have better control
of the layout. </div><br><br>

80
ALI RAZA MANZOOR (WEB DEVELOPER)
<div class="divscroll">You can use the overflow property when you want to have better control
of the layout. </div><br><br>
<div class="auto">You can use the overflow property when you want to have better control of the
layout. </div><br><br>
</body>
</html>
The float Property
The float property is used for positioning and layout on web pages.
The float property can have one of the following values:
 Left - The element floats to the left of its container
 Right- The element floats to the right of its container
 None - The element does not float (will be displayed just where it occurs in the text). This
is default
 Inherit - The element inherits the float value of its parent

Example:

<!DOCTYPE html>
<html>
<head><style>
p{float: right;}
h1{float:left;}
h2{float:none;}
h3{float:inherit ;}
</style>
</head>
<body>
<h1>this is heading</h1>
<h2>this is heading 2</h2>
<h3>this is heading 3</h3>
<p>pargraph is very lenthly</p>
</body></html>

81
ALI RAZA MANZOOR (WEB DEVELOPER)
Use inline-block to Create Navigation Links
One common use for display: inline-block is to create horizontal navigation links:
Example:
<!DOCTYPE html>
<html>
<head>
<style>
.nav {
background-color: yellow;
padding: 15px;
list-style-type: none;
text-align: center;
}

.nav li {
display: inline-block;
font-size: 20px;
padding-left: 20px;
padding-right: 20px;
}
</style>
</head>
<body>
<h1>Horizontal Navigation Links</h1>\
<ul class="nav">
<li><a href="#home">Home</a></li>
<li><a href="#about">About Us</a></li>
<li><a href="#clients">Our Clients</a></li>
<li><a href="#contact">Contact Us</a></li>

82
ALI RAZA MANZOOR (WEB DEVELOPER)
<li><a href="#map">Map</a></li>
</ul>
</body>
</html>

The ::first-line Pseudo-element/::first-letter Pseudo-element


The ::first-line pseudo-element is used to add a special style to the first line of a text.
The ::first-line pseudo-element can only be applied to block-level elements.
The following properties apply to the ::first-letter pseudo- element:
 Font Properties
 Color Properties
 Background Properties
 Margin Properties
 Padding Properties
 Border Properties
 Text-Decoration
 Vertical-Align (Only If "Float" Is "None")
 Text-Transform
 Line-Height
 Float
 Clear
Example: First Letter
<!DOCTYPE html>
<html>
<head>
<style>
p::first-letter {
color: #ff0000;
font-size: xx-large;
}
</style>
</head>
<body>

83
ALI RAZA MANZOOR (WEB DEVELOPER)
<p>You can use the ::first-letter pseudo-element to add a special effect to the first character of a
text!</p></body></html>
Example: First-line
<!DOCTYPE html>
<html>
<head>
<style>
p::first-line {
color: #ff0000;
font-variant: small-caps;
}
</style>
</head>
<body><p>You can use the ::first-line pseudo-element to add a special effect to the first line of a
text., and more, and more, and more.</p></body>
</html>
Horizontal Navigation Bar Examples
<!DOCTYPE html>
<html>
<head>
<style>
ul {
margin: 0;
padding: 0;
overflow: hidden;
background-color: black;
}
li{
float:left;
}

84
ALI RAZA MANZOOR (WEB DEVELOPER)
li a {
display: block;
color: white;
text-align:center;
padding: 10px;
text-decoration:none;
}
li a:hover {
background-color:green;
}
</style>
</head>
<body>
<h2>Navigation Menu</h2>
<ul>
<li><a href="">Home</a>
</li>
<li><a href="order.html">News</a></li>
<li><a href="">Contact</a></li>
<li><a href="">About</a></li>
</ul>
</body>
</html>
Dropdown Menu
Create a dropdown menu that allows the user to choose an option from a list:
Example:
<!DOCTYPE html>
<html>
<head>
<style>
85
ALI RAZA MANZOOR (WEB DEVELOPER)
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropdown {
position: relative;
display: inline-block; }
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}

.dropdown-content a:hover {background-color: #f1f1f1;}


.dropdown:hover .dropdown-content { display: block; }
.dropdown:hover .dropbtn { background-color: #3e8e41; }
</style>

86
ALI RAZA MANZOOR (WEB DEVELOPER)
</head>
<body>
<h2>Dropdown Menu</h2>
<p>Move the mouse over the button to open the dropdown menu.</p>
<div class="dropdown">
<button class="dropbtn">Dropdown</button>
<div class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
<p><strong>Note:</strong> We use href="#" for test links. In a real web site this would be
URLs.</p>
</body>
</html>

Show Different Images Depending on Browser Width


The HTML <picture> element allows you to define different images for different browser
window sizes.
Resize the browser window to see how the image below change depending on the width:
Example:
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<h2>Show Different Images Depending on Browser Width</h2>
<p>Resize the browser width and the image will change at 600px and 1500px.</p>
<picture>
<source srcset="img_smallflower.jpg" media="(max-width: 600px)">
<source srcset="img_flowers.jpg" media="(max-width: 1500px)">

87
ALI RAZA MANZOOR (WEB DEVELOPER)
<source srcset="flowers.jpg">
<img src="img_flowers.jpg" alt="Flowers" style="width:auto;">
</picture>
</body>
</html>

HTML tabindex Attribute


The tabindex attribute specifies the tab order of an element (when the "tab" button is used for
navigating).
Example:
<!DOCTYPE html>
<html>
<body>
<a href="#/" tabindex="2">aliraza</a><br>
<a href="#/" tabindex="1">manzoor</a><br>
<a href="#" tabindex="3">hussain</a>
<p><b>Note:</b> Try navigating the links by using the "Tab" button on you keyboard.</p>
</body>
</html>

HTML accesskey Attribute


<!DOCTYPE html>
<html>
<body>
<a href="#/" tabindex="2" accesskey="h">aliraza</a><br>
<a href="#/" tabindex="1" accesskey="l">manzoor</a><br>
<a href=”#" tabindex="3" accesskey="g">hussain</a>
<p><b>Note:</b> Try navigating the links by using the "Tab" button on you keyboard.</p>
</body></html>

88
ALI RAZA MANZOOR (WEB DEVELOPER)
CSS letter-spacing PropertyAndCSS word-

spacing Property
Example:
<!DOCTYPE html>
<html>
<head>
<style>
p.a {
word-spacing: normal;
}
p.b {
letter-spacing: 10px;
}
p.c {
word-spacing: 1cm;
}
</style>
</head>
<body>
<h1>The word-spacing Property</h1>
<h2>word-spacing: normal:</h2>
<p class="a">This is some text. This is some text.</p>
<h2>word-spacing: 30px:</h2>
<p class="b">This is some text. This is some text.</p>
<h2>word-spacing: 1cm:</h2>
<p class="c">This is some text. This is some text.</p>
</body>
</html>

89
ALI RAZA MANZOOR (WEB DEVELOPER)
CSS border-radius Property
Example:
<!DOCTYPE html>
<html>
<head>
<style>
#example1 {
border: 2px solid red;
padding: 10px;
border-radius: 25px;
} #example2 {
border: 2px solid red;
padding: 10px;
border-radius: 50px 20px;
} </style>
</head>
<body>
<h2>border-radius: 25px:</h2>
<div id="example1">
<p>The border-radius property defines the radius of the element's corners.</p>
</div>
<h2>border-radius: 50px 20px:</h2>
<div id="example2">
<p>If two values are set; the first one is for the top-left and bottom-right corner, the second one
for the top-right and bottom-left corner.</p>
</div>
</body>
</html>

90
ALI RAZA MANZOOR (WEB DEVELOPER)
CSS text-indent Property
The text-indent property specifies the indentation of the first line in a text-block.
<!DOCTYPE html>
<html>
<head><style>
div.a {
text-indent: 50px;}
div.b { text-indent: -2em;}
div.c { text-indent: 30%;}
</style></head>
<body>
<h1>The text-indent Property</h1>
<h2>text-indent: 50px:</h2>
<div class="a">
<p> Vestibulum volutpat tellus diam, consequat gravida libero rhoncus ut.</p>
</div>
<h2>text-indent: -2em:</h2>
<div class="b">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat
pulvinar,.</p>
</div>
<h2>text-indent: 30%:</h2>
<div class="c">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam erat .</p>
</div>
</body></html>

91
ALI RAZA MANZOOR (WEB DEVELOPER)
HTML <fieldset>/HTML<legend>Tag
The <fieldset> tag is used to group related elements in a form.
<!DOCTYPE html>
<html>
<body>
<form>
<fieldset>
<legend>Personalia:</legend>
Name: <input type="text"><br>
Email: <input type="text"><br>
Date of birth: <input type="text">
</fieldset>
</form></body></html>

CSS @media Rule


The @media rule is used in media queries to apply different styles for different media
types/devices.
Media queries can be used to check many things, such as:
 WIDTH AND HEIGHT OF THE VIEWPORT
 WIDTH AND HEIGHT OF THE DEVICE
 ORIENTATION (IS THE TABLET/PHONE IN LANDSCAPE OR PORTRAIT MODE?)
 RESOLUTION
Using media queries are a popular technique for delivering a tailored style sheet (responsive web
design) to desktops, laptops, tablets, and mobile phones.
You can also use media queries to specify that certain styles are only for printed documents or for
screen readers (mediatype: print, screen, or speech).
In addition to media types, there are also media features. Media features provide more specific
details to media queries, by allowing to test for a specific feature of the user agent or display
device. For example, you can apply styles to only those screens that are greater, or smaller, than a
certain width.
Example:

92
ALI RAZA MANZOOR (WEB DEVELOPER)
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
background-color: yellow;
}
@media only screen and (max-width: 600px) {
body {
background-color: lightblue;
}
}
</style>
</head>
<body>
<h1>The @media Rule</h1>
<p>Resize the browser window. When the width of this document is 600 pixels or less, the
background-color is "lightblue", otherwise it is "yellow".</p>
</body></html>

JavaScript
JavaScript Can Change HTML Styles (CSS)
Changing the style of an HTML element, is a variant of changing an HTML attribute:
Example:
<!DOCTYPE html>
<html>
<body>

93
ALI RAZA MANZOOR (WEB DEVELOPER)
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change the style of an HTML element.</p>
<button type="button" onclick="document.getElementById('demo').style.fontSize='35px'">Click
Me!</button>
</body></html>

JavaScript Display Possibilities


JavaScript can "display" data in different ways:
 Writing into an HTML element, using innerHTML.
 Writing into the HTML output using document.write().
 Writing into an alert box, using window.alert().
 Writing into the browser console, using console.log().
Using innerHTML
To access an HTML element, JavaScript can use the do
cument.getElementById(id) method.
The id attribute defines the HTML element. The innerHTML property defines the HTML
content:
Example
<!DOCTYPE html>
<html>
<body>
<h1>This is a Heading</h1>
<p>This is a Paragraph</p>

<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Using document.write()
For testing purposes, it is convenient to use document.write():
<!DOCTYPE html>
<html>

94
ALI RAZA MANZOOR (WEB DEVELOPER)
<body>
<h1>This is a Heading</h1>
<p>This is a Paragraph</p>

<script>
document.write(5 + 6);
</script>
</body>
</html>
Other Example:

Using document.write() after an HTML document is fully loaded, will delete all
existing HTML:

<!DOCTYPE html>
<html>
<body>
<h1>This is a Heading</h1>
<p>This is a Paragraph</p>
<button type="button" onclick="document.write(5 + 6)">Try it</button>

</body>
</html>
Using window.alert()
You can use an alert box to display data:
<!DOCTYPE html>
<html>
<body>
<h1>This is a Heading</h1>
<p>This is a Paragraph</p>

<script>
window.alert(5 + 6);
</script>

</body>
</html>

95
ALI RAZA MANZOOR (WEB DEVELOPER)
Using console.log()
For debugging purposes, you can use the console.log() method to display data.
<!DOCTYPE html>
<html>
<body>
<script>
console.log(5 + 6);
</script>
</body>
</html>

JavaScript Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
This statement tells the browser to write "Hello Dolly." inside an HTML element with id="demo":
Statement
document.getElementById("demo").innerHTML = "Hello Dolly.";
Semicolons ; and Variable/ Operators
Semicolons separate JavaScript statements.
Add a semicolon at the end of each executable statement:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>JavaScript statements are separated by semicolons.</p>
<p id="demo1"></p>
<script>
var a, b, c;
a = 1;
b = 2;
c = a + b;

96
ALI RAZA MANZOOR (WEB DEVELOPER)
document.getElementById("demo1").innerHTML = c;
</script>
</body>
</html>

JavaScript Arithmetic
Arithmetic operators perform arithmetic on numbers (literals or variables).

Operator Description

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus (Remainder)

++ Increment

-- Decrement

JavaScript Code Blocks


JavaScript statements can be grouped together in code blocks, inside curly brackets {...}.
The purpose of code blocks is to define statements to be executed together.
One place you will find statements grouped together in blocks, is in JavaScript functions:
Example:
<!DOCTYPE html>
97
ALI RAZA MANZOOR (WEB DEVELOPER)
<html>
<body>
<h2>JavaScript Statements</h2>
<p>JavaScript code blocks are written between { and }</p>
<button type="button" onclick="myFunction()">Click Me!</button>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
function myFunction() {
document.getElementById("demo1").innerHTML = "Hello Dolly!";
d
ocument.getElementById("demo2").innerHTML = "How are you?";
}
</script>
</body>
</html>
JavaScript Assignment Operators
Assignment operators assign values to JavaScript variables.
The += assignment operator adds a value to a variable.
The -= assignment operator subtracts a value from a variable.
The *= assignment operator multiplies a variable.
The /= assignment divides a variable.
The %= assignment operator assigns a remainder to a variable.

Operator Example Same as

= X=y X=y

+= X+=y X=x+y

98
ALI RAZA MANZOOR (WEB DEVELOPER)
-= x-=y X=x-y

*= X*=y X=x*y

/= x/=y X=x/y

%= X%=y X=x%y

<<= X<<=y X=x<<y

>>= x>>=y X=x>>y

>>>= x>>>=y X=x>>>y

&= X&=y X=x&y

^= X^=y X=x^y

|= X|=y X=x|y

**= X**=y X=x**y

Example: Assignment
<!DOCTYPE html>
<html>
<body>
<h2>The = Operator</h2>
<p id="demo"></p>

99
ALI RAZA MANZOOR (WEB DEVELOPER)
<script>
var x = 10;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>

JavaScript variable Statement


Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>A <b>JavaScript program</b> is a list of <b>statements</b> to be executed by a
computer.</p>
<p id="demo"></p>
<script>
var x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4
document.getElementById("demo").innerHTML ="The value of z is " + z + ".";
</script>
</body>
</html>

JavaScript Comments
JavaScript comments can be used to explain JavaScript code, and to make it more readable.
Single Line Comments
// Change heading:
100
ALI RAZA MANZOOR (WEB DEVELOPER)
Multi-line Comments
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored by JavaScript.
JavaScript Function Syntax
A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}
Syntax:
function name(parameter1, parameter2, parameter3) {
code to be executed
}
Function parameters are listed inside the parentheses () in the function
definition.
Function arguments are the values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.
Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:
 When an event occurs (when a user clicks a button)
 When it is invoked (called) from JavaScript code
 Automatically (self-invoked)
Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code after the
invoking statement.
Functions often compute a return value. The return value is "returned" back to the "caller":

Example

<!DOCTYPE html>
<html>
101
ALI RAZA MANZOOR (WEB DEVELOPER)
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation, and returns the result:</p>
<p id="demo"></p>
<script>
function myFunction(p1, p2) {
return p1 * p2;
}document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>
</body>
</html>
Why Functions?

You can reuse code: Define the code once, and use it many times.You can use
the same code many times with different arguments, to produce different results.

Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function to convert from Fahrenheit to Celsius:</p>
<p id="demo"></p>
<script>
function toCelsius(f) {
return (5/9) * (f-32);
}
document.getElementById("demo").innerHTML = toCelsius(50);
</script>
</body>
</html>

102
ALI RAZA MANZOOR (WEB DEVELOPER)
JavaScript Functions
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it (calls it).
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation, and returns the result:</p>
<p id="demo"></p>
<script>
function myFunction(p1, p2) {
return p1 * p2;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>
</body>
</html>

JavaScript Switch Statement


The switch statement is used to perform different actions based on different
conditions.

The JavaScript Switch Statement


Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch(expression) {
case n:
code block
break;

103
ALI RAZA MANZOOR (WEB DEVELOPER)
case n:
code block
break;
default:
code block
}
This is how it works:
 The switch expression is evaluated once.
 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
Example:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var day;
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
104
ALI RAZA MANZOOR (WEB DEVELOPER)
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
document.getElementById("demo").innerHTML = "Today is " + day;
</script>
</body>
</html>
The break Keyword
When JavaScript reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no need for more testing.

JavaScript Objects
Real Life Objects, Properties, and Methods
In real life, a car is an object.

A car has properties like weight and color, and methods like start and stop

Object Properties Methods


CAR

105
ALI RAZA MANZOOR (WEB DEVELOPER)
JavaScript Objects
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable named car:
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
// Create an object: in this line (Fiat, 500, white)is value
var car = {type:"Fiat", model:"500", color:"white"};
// Display some data from the object:
document.getElementById("demo").innerHTML = car.type;
</script>
</body>
</html>
Other Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
// Create an object:
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
// Display some data from the object:
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";

106
ALI RAZA MANZOOR (WEB DEVELOPER)
</script>
</body>
</html>
Object Properties

The name:values pairs in JavaScript objects are called properties:

Property Property Value


First name Ali
Last name Raza
Age 50
Eye Color Blue

JavaScript Scope
JavaScript Function Scope
In JavaScript there are two types of scope:
 Local scope
 Global scope
JavaScript has function scope: Each function creates a new scope.
Scope determines the accessibility (visibility) of these variables.
Variables defined inside a function are not accessible (visible) from outside the function.
Local JavaScript Variables
Variables declared within a JavaScript function, become LOCAL to the function.
Local variables have local scope: They can only be accessed within the function.
Example:
<!DOCTYPE html>
<html>
<body>
<p>The local variable carName cannot be accessed from code outside the function:</p>
<p id="demo"></p>
<script>
myFunction();

107
ALI RAZA MANZOOR (WEB DEVELOPER)
document.getElementById("demo").innerHTML =
"The type of carName is " + typeof carName;
function myFunction() {
var carName = "Volvo";
}
</script>
</body>
</html>
local variables are only recognized inside their functions, variables with the same name can be
used in different functions.
Local variables are created when a function starts, and deleted when the function is completed.
Global JavaScript Variables
A variable declared outside a function, becomes GLOBAL.
A global variable has global scope: All scripts and functions on a web page can access it.
<!DOCTYPE html>
<html>
<body>
<p>A GLOBAL variable can be accessed from any script or function.</p>
<p id="demo"></p>
<script>
var carName = "Volvo";
myFunction();
function myFunction() {
document.getElementById("demo").innerHTML =
"I can display " + carName;
}
</script>
</body></html>

108
ALI RAZA MANZOOR (WEB DEVELOPER)
JavaScript Events
HTML events are "things" that happen to HTML elements.
When JavaScript is used in HTML pages, JavaScript can "react" on these events.
HTML Events
An HTML event can be something the browser does, or something a user does.
Here are some examples of HTML events:
 An HTML web page has finished loading
 An HTML input field was changed
 An HTML button was clicked
Often, when events happen, you may want to do something.
JavaScript lets you execute code when events are detected.
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
With single quotes:
<element event='some JavaScript'>
With double quotes:
<element event="some JavaScript">
Example:
<button onclick="this.innerHTML = Date()">The time is?</button>
<button onclick="document.getElementById('demo').innerHTML = Date()">The time
is?</button>
Common HTML Events
Here is a list of some common HTML events:

Event Description

onchange An HTML element has been changed

onchange An HTML element has been changed

onclick The user clicks an HTML element

onmouseover The user moves the mouse over an HTML element

109
ALI RAZA MANZOOR (WEB DEVELOPER)
Onmouseout The user moves the mouse away from an HTML element

Onkeydown The user pushes a keyboard key

Onload The browser has finished loading the page

onchange Event
The onchange event occurs when the value of an element has been changed.
For radiobuttons and checkboxes, the onchange event occurs when the checked state has been
changed.
Example:
<!DOCTYPE html>
<html>
<body>
<p>Select a new car from the list.</p>
<select id="mySelect" onchange="myFunction()">
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Mercedes">Mercedes
<option value="Volvo">Volvo
</select>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
</script>
</bod y>
</html>

110
ALI RAZA MANZOOR (WEB DEVELOPER)
onclick Event
The onclick event occurs when the user clicks on an element.

Example:
<!DOCTYPE html>
<html>
<body>
<h1>This is a Heading</h1>
<p>This is a Paragraph</p>

<button type="button" onclick="document.write(5 + 6)">Try it</button>


</body>
</html>
Example:
<!DOCTYPE html>
<html>
<body onload="myFunction()">
<h1>Hello World!</h1>
<script>
function myFunction() {
alert("Page is loaded");
}
</script>
</body>
</html>

JavaScript Type Conversion


JavaScript Data Types
In JavaScript there are 5 different data types that can contain values:
 String
 Number
 Boolean

111
ALI RAZA MANZOOR (WEB DEVELOPER)
 Object
 Function
There are 3 types of objects:
 Object
 Date
 Array
And 2 data types that cannot contain values:
 Null
 Undefined
The typeof Operator
You can use the typeof operator to find the data type of a JavaScript variable.
Example:
<!DOCTYPE html>
<html>
<body>
<h2>The JavaScript typeof Operator</h2>
<p>The typeof operator returns the type of a variable, object, function or expression.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
typeof "john" + "<br>" +
typeof 3.14 + "<br>" +
typeof NaN + "<br>" +
typeof false + "<br>" +
typeof [1,2,3,4] + "<br>" +
typeof {name:'john', age:34} + "<br>" +
typeof new Date() + "<br>" +
typeof function () {} + "<br>" +
typeof myCar + "<br>" +
typeof null;
</script>

112
ALI RAZA MANZOOR (WEB DEVELOPER)
</body>
</html>

The JavaScript constructor Property


The constructor property returns the constructor function for a variable or an object.
<!DOCTYPE html>
<html>
<body>
<h2>The JavaScript constructor Property</h2>
<p>The constructor property returns the constructor function for a variable or an
object.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"john".constructor + "<br>" +
(3.14).constructor + "<br>" +
false.constructor + "<br>" +
[1,2,3,4].constructor + "<br>" +
{name:'john', age:34}.constructor + "<br>" +
new Date().constructor + "<br>" +
function () {}.constructor;
</script>
</body>
</html>

JavaScript Strings
A JavaScript string is zero or more characters written inside quotes.
Because strings must be written within quotes, JavaScript will misunderstand this string:

113
ALI RAZA MANZOOR (WEB DEVELOPER)
Example:
<html>
<body>
<h2>JavaScript Strings</h2>
<p id="demo"></p>
<script>
var x = "John Doe"; // String written inside quotes
document.getElementById("demo").innerHTML = x;
</script></body>
</html>
You can use single or double quotes:
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</h2>
<p>Strings are written inside quotes. You can use single or double quotes:</p>
<p id="demo"></p>
<script>
var carName1 = "Volvo XC60"; // Double quotes
var carName2 = 'Volvo XC60'; // Single quotes
document.getElementById("demo").innerHTML =
carName1 + " <br>" + carName2;
</script>
</body>
</html>
String Length
The length of a string is found in the built in property length:
Example:

114
ALI RAZA MANZOOR (WEB DEVELOPER)
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Properties</h2>
<p>The length property returns the length of a string:</p>
<p id="demo"></p>
<script>
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.getElementById("demo").innerHTML = txt.length;
</script>
</body>
</html>

JavaScript Arrays
JavaScript arrays are used to store multiple values in a single variable.
An array is a special variable, which can hold more than one value at a time.
Syntax:
var array_name = [item1, item2, ...];

Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
</body>

115
ALI RAZA MANZOOR (WEB DEVELOPER)
</html>
Example2:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
var cars = [
"Saab",
"Volvo",
"BMW"
];
document.getElementById("demo").innerHTML = cars;
</script>
</body>
</html>

Using the JavaScript Keyword new


The following example also creates an Array, and assigns values to it:
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
var cars = new Array("Saab", "Volvo", "BMW");
document.getElementById("demo").innerHTML = cars;
</script>

116
ALI RAZA MANZOOR (WEB DEVELOPER)
</body>
</html>
Access the Elements of an Array
You refer to an array element by referring to the index number.
This statement accesses the value of the first element in cars:
var name = cars[0];
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>JavaScript array elements are accesses using numeric indexes (starting from 0).</p>
<p id="demo"></p>
<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
</script>
</body>
</html>
Arrays are Objects
Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.
But, JavaScript arrays are best described as arrays.
Example:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>
<p>JavaScript uses names to access object properties.</p>

117
ALI RAZA MANZOOR (WEB DEVELOPER)
<p id="demo"></p>

<script>
var person = {firstName:"John", lastName:"Doe", age:46};
document.getElementById("demo").innerHTML = person["firstName"];
</script>
</body>
</html>

JavaScript Data Types


JavaScript variables can hold many data types: numbers, strings, objects and more:
The Concept of Data Types
In programming, data types is an important concept.
To be able to operate on variables, it is important to know something about the type.
Without data types, a computer cannot safely solve this:
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript</h2>
<p>When adding a number and a string, JavaScript will treat the number as a string.</p>
<p id="demo"></p>
<script>
var x = 16 + "Volvo";
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>

118
ALI RAZA MANZOOR (WEB DEVELOPER)
JavaScript Types are Dynamic.
JavaScript has dynamic types. This means that the same variable can be used to hold different data
types:
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Data Types</h2>
<p>JavaScript has dynamic types. This means that the same variable can be used to hold different
data types:</p>
<p id="demo"></p>
<script>
var x; // Now x is undefined
x = 5; // Now x is a Number
x = "John"; // Now x is a String
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
JavaScript Strings
A string (or a text string) is a series of characters like "John Doe".
Strings are written with quotes. You can use single or double quotes:
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</h2>
<p>Strings are written with quotes. You can use single or double quotes:</p>
<p id="demo"></p>

119
ALI RAZA MANZOOR (WEB DEVELOPER)
<script>
var carName1 = "Volvo XC60";
var carName2 = 'Volvo XC60';
document.getElementById("demo").innerHTML =
carName1 + "<br>" +
carName2;
</script>
</body>
</html>
JavaScript Numbers
JavaScript has only one type of numbers.
Numbers can be written with, or without decimals:
Example: Number(intger),Floating
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Numbers</h2>
<p>Numbers can be written with, or without decimals:</p>
<p id="demo"></p>
<script>
var x1 = 34.00;
var x2 = 34;
var x3 = 3.14;
document.getElementById("demo").innerHTML =
x1 + "<br>" + x2 + "<br>" + x3;
</script>
</body>
</html>

120
ALI RAZA MANZOOR (WEB DEVELOPER)
JavaScript Booleans
Booleans can only have two values: true or false.
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Booleans</h2>
<p>Booleans can have two values: true or false:</p>
<p id="demo"></p>
<script>
var x = 5;
var y = 5;
var z = 6;
document.getElementById("demo").innerHTML =
(x == y) + "<br>" + (x == z);
</script>
</body>
</html>
JavaScript Objects
JavaScript objects are written with curly braces.
Object properties are written as name:value pairs, separated by commas.
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>

121
ALI RAZA MANZOOR (WEB DEVELOPER)
var person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>
</body>
</html>
Undefined
In JavaScript, a variable without a value, has the value undefined. The typeof is also undefined.
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript</h2>
<p>The value (and the data type) of a variable with no value is <b>undefined</b>.</p>
<p id="demo"></p>
<script>
var car;
document.getElementById("demo").innerHTML =
car + "<br>" + typeof car;
</script>
</body>
</html>

122
ALI RAZA MANZOOR (WEB DEVELOPER)
Null
In JavaScript null is "nothing". It is supposed to be something that doesn't exist.
Unfortunately, in JavaScript, the data type of null is an object.
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript</h2>
<p>Objects can be emptied by setting the value to <b>null</b>.</p>
<p id="demo"></p>
<script>
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
person = null;
document.getElementById("demo").innerHTML = typeof person;
</script>
</body>
</html>

JavaScript For Loop


Loops can execute a block of code a number of times.
Loops are handy, if you want to run the same code over and over again, each time with a different
value.
Often this is the case when working with arrays:
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Loops</h2>
<p id="demo"></p>

123
ALI RAZA MANZOOR (WEB DEVELOPER)
<script>
var cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
var text = "";
var i;
for (i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

Different Kinds of Loops


JavaScript supports different kinds of loops:
 For - loops through a block of code a number of times
 While - loops through a block of code while a specified condition is true
 Do/while - also loops through a block of code while a specified condition is true
The For Loop
The for loop has the following syntax:
for (statement 1; statement 2; statement 3) {
code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Loops</h2>
<p id="demo"></p>

124
ALI RAZA MANZOOR (WEB DEVELOPER)
<script>
var text = "";
var i;
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Statement 1
Normally you will use statement 1 to initialize the variable used in the loop (i = 0).
This is not always the case, JavaScript doesn't care. Statement 1 is optional.
You can initiate many values in statement 1 (separated by comma):
Example:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i, len, text;
for (i = 0, len = cars.length, text = ""; i < len; i++) {
text += cars[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

125
ALI RAZA MANZOOR (WEB DEVELOPER)
Statement 2
Often statement 2 is used to evaluate the condition of the initial variable.
This is not always the case, JavaScript doesn't care. Statement 2 is also optional.
If statement 2 returns true, the loop will start over again, if it returns false, the loop will end.
Example:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 2;
var len = cars.length;
var text = "";
for (; i < len; i++) {
text += cars[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Statement 3
Often statement 3 increments the value of the initial variable.
This is not always the case, JavaScript doesn't care, and statement 3 is optional.
Statement 3 can do anything like negative increment (i--), positive increment (i = i + 15), or
anything else.
Statement 3 can also be omitted (like when you increment your values inside the loop):
Example:
<!DOCTYPE html>

126
ALI RAZA MANZOOR (WEB DEVELOPER)
<html>
<body>
<p id="demo"></p>
<script>
var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 0;
var len = cars.length;
var text = "";
for (; i < len; ) {
text += cars[i] + "<br>";
i++;
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

JavaScript While Loop


Loops can execute a block of code as long as a specified condition is true.
The while loop loops through a block of code as long as a specified condition is true.
Syntax
While (Condition){
Write code here to Execute
}
Example:
<!DOCTYPE html>
<html>
<body>
127
ALI RAZA MANZOOR (WEB DEVELOPER)
<h2>JavaScript while</h2>
<p id="demo"></p>
<script>
var text = "";
var i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

The Do/While Loop


The do/while loop is a variant of the while loop. This loop will execute the code block once, before
checking if the condition is true, then it will repeat the loop as long as the condition is true.
Syntax
do{
Write code here to Execute
}
While(Condition);
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript do ... while</h2>
<p id="demo"></p>
<script>
var text = ""

128
ALI RAZA MANZOOR (WEB DEVELOPER)
var i = 0;
do {
text += "<br>The number is " + i;
i++;
}
while (i < 10);
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

JavaScript Errors - Throw and Try to Catch


The try statement lets you test a block of code for errors.
The catch statement lets you handle the error.
The throw statement lets you create custom errors.
The finally statement lets you execute code, after try and catch, regardless of the result.

Errors Will Happen!


When executing JavaScript code, different errors can occur.
Errors can be coding errors made by the programmer, errors due to wrong input, and other
unforeseeable things.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
try {
aaaalert("Welcome guest!");
}
catch(err) {

129
ALI RAZA MANZOOR (WEB DEVELOPER)
document.getElementById("demo").innerHTML = err.message;
}
</script>
</body>
</html>

Input Validation Example


This example examines input. If the value is wrong, an exception (err) is thrown.
The exception (err) is caught by the catch statement and a custom error message is displayed:
<!DOCTYPE html>
<html>
<body>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="p01"></p>
<script>
function myFunction() {
var message, x;
message = document.getElementById("p01");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x < 5) throw "too low";
if(x > 10) throw "too high";
}
catch(err) {

130
ALI RAZA MANZOOR (WEB DEVELOPER)
message.innerHTML = "Input is " + err;
}
}
</script>
</body>
</html>

The finally Statement


The finally statement lets you execute code, after try and catch, regardless of the result:
Syntax:
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {
Block of code to be executed regardless of the try / catch result
}
<!DOCTYPE html>
<html>
<body>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="p01"></p>
<script>
function myFunction() {
var message, x;
message = document.getElementById("p01");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
131
ALI RAZA MANZOOR (WEB DEVELOPER)
if(x == "") throw "is empty";
if(isNaN(x)) throw "is not a number";
x = Number(x);
if(x > 10) throw "is too high";
if(x < 5) throw "is too low";
}
catch(err) {
message.innerHTML = "Input " + err;
}
finally {
document.getElementById("demo").value = "";
}
}
</script>
</body>
</html>

The JavaScript this Keyword


The JavaScript this keyword refers to the object it belongs to.
<!DOCTYPE html>
<html>
<body>
<h2>The JavaScript <b>this</b> Keyword</h2>
<p>In this example, <b>this</b> represents the <b>person</b> object.</p>
<p>Because the person object "owns" the fullName method.</p>
<p id="demo"></p>

<script>
// Create an object:
var person = {

132
ALI RAZA MANZOOR (WEB DEVELOPER)
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
// Display data from the object:
document.getElementById("demo").innerHTML = person.fullName();
</script>
</body>
</html>

PHP
 PHP is an acronym for "PHP: Hypertext Preprocessor"
 PHP is a widely-used, open source scripting language
 PHP scripts are executed on the server
 PHP is free to download and use

What is a PHP File?


 PHP files can contain text, HTML, CSS, JavaScript, and PHP code
 PHP code are executed on the server, and the result is returned to the browser as plain
HTML
 PHP files have extension ".php"

What Can PHP Do?


 PHP can generate dynamic page content
 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can add, delete, modify data in your database
 PHP can be used to control user-access
 PHP can encrypt data

133
ALI RAZA MANZOOR (WEB DEVELOPER)
To start using PHP, you can:
 Find a web host with PHP and MySQL support
 Install a web server on your own PC, and then install PHP and MySQL

PHP 5 Syntax
A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>:
The default file extension for PHP files is ".php".
<!DOCTYPE html>
<html>
<body>
<h1>First PHP </h1>
<?php
echo “Hello World!”
?>

</body>
</html>
Comments in PHP
A comment in PHP code is a line that is not read/executed as part of the program. Its only purpose
is to be read by someone who is looking at the code.
<!DOCTYPE html>
<html>
<body>

<?php

$x = 5 /* + 15 */ + 5;
echo $x;
?>

</body>
</html>

134
ALI RAZA MANZOOR (WEB DEVELOPER)
PHP Case Sensitivity
PHP is case sensitivity language.
<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
echo "My car is ". $color . "<br>";
echo "My house is ". $COLOR . "<br>";
echo "My boat is ". $coLOR . "<br>";
?>
</body>
</html>

PHP 5 Variables
Variables are "containers" for storing information.
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
Rules for PHP variables:
 A variable starts with the $ sign, followed by the name of the variable
 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and
_)
 Variable names are case-sensitive ($age and $AGE are two different variables)
Display Output through Variable
The PHP echo statement is often used to output data to the screen.
<html>
<body>
<?php
$txt = "W3Schools.com";
echo "I love $txt!"; ?>
</body>
</html>

135
ALI RAZA MANZOOR (WEB DEVELOPER)
PHP Variables Scope
In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
 local
 Global
 Static

Global and Local Scope


A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside
a function:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
</body>
</html>
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that
function:
<!DOCTYPE html>
<html>
<body>

<?php
function myTest() {
$x = 5; // local scope

136
ALI RAZA MANZOOR (WEB DEVELOPER)
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

// using x outside the function will generate an error


echo "<p>Variable x outside function is: $x</p>";
?>

</body>
</html>
PHP The Global Keyword
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):
<!DOCTYPE html>
<html>
<body>

<?php
$x = 5;
$y = 10;

function myTest() {
global $x, $y;
//or other method using Array $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
$y = $x + $y;
}
myTest(); // run function
echo $y; // output the new value for variable $y
?>
</body>
</html>

PHP The Static Keyword


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:
<!DOCTYPE html>
<html>

137
ALI RAZA MANZOOR (WEB DEVELOPER)
<body>

<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}

myTest();
echo "<br>";
myTest();
echo "<br>";
myTest();
?>

</body>
</html>

PHP 5 echo Statements


The echo statement can be used with or without parentheses: echo or echo().
<!DOCTYPE html>
<html>
<body>

<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>

</body>
</html>
PHP Concatenation of Multi.. Value
Two and multiple output combine with (.) or output and text combine with (.)
<!DOCTYPE html>
<html>
<body>

138
ALI RAZA MANZOOR (WEB DEVELOPER)
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;

echo "<h2>" . $txt1 . "</h2>";


echo "Study PHP at ". $txt2 . "<br>";
echo $x + $y;
?>
</body>
</html>

PHP 5 Data Types


PHP Data Types
Variables can store data of different types, and different data types can do different things.
PHP supports the following data types:
 String
 Integer
 Float (floating point numbers - also called double)
 Boolean
 Array
 Object
 NULL
 Resource

PHP String
A string is a sequence of characters, like "Hello world!".
A string can be any text inside quotes. You can use single or double quotes:
<!DOCTYPE html>
<html>
<body>

<?php
$x = "Hello world!";
$y = 'Hello world!';

139
ALI RAZA MANZOOR (WEB DEVELOPER)
echo $x;
echo "<br>";
echo $y;
?>

</body>
</html>

PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
Rules for integers:
 An integer must have at least one digit
 An integer must not have a decimal point
 An integer can be either positive or negative
 Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based -
prefixed with 0x) or octal (8-based - prefixed with 0)
In the following example $x is an integer. The PHP var_dump() function returns the data type and
value:
PHP Float
A float (floating point number) is a number with a decimal point or a number in exponential form.
In the following example $x is a float. The PHP var_dump() function returns the data type and
value:

<!DOCTYPE html>
<html>
<body>
<?php
$x = 10.365;
var_dump($x);
?>
</body>
</html>

PHP Boolean
A Boolean represents two possible states: TRUE or FALSE. Booleans are often used in conditional
testing.

140
ALI RAZA MANZOOR (WEB DEVELOPER)
$x = true;
$y = false;

PHP Array
An array stores multiple values in one single variable.
In the following example $cars is an array. The PHP var_dump() function returns the data type
and value:

<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
</body>
</html>

Example
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota","ali","ok","ll","aaa","pap","al");
// $arrlength = count($cars);
for($x = 0; $x < 6; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
</body>
</html>
PHP Object
An object is a data type which stores data and information on how to process that data.
In PHP, an object must be explicitly declared.
141
ALI RAZA MANZOOR (WEB DEVELOPER)
First we must declare a class of object. For this, we use the class keyword. A class is a structure
that can contain properties and methods:

<!DOCTYPE html>
<html>
<body>

<?php
class Car {
function Car() {
$this->model = "VW";
}
}
// create an object
$herbie = new Car();
// show object properties
echo $herbie->model;
?>
</body>
</html>

PHP NULL Value


Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.
Tip: If a variable is created without a value, it is automatically assigned a value of NULL.

<!DOCTYPE html>
<html>
<body>
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
</body>
</html>

PHP 5 Strings
A string is a sequence of characters, like "Hello world!".
Count The Length

142
ALI RAZA MANZOOR (WEB DEVELOPER)
The PHP strlen() function returns the length of a string.
Count The Number of Words
The PHP str_word_count() function counts the number of words in a string:
Reverse a String
The PHP strrev() function reverses a string:
Search For a Specific Text Within a String
The PHP strpos() function searches for a specific text within a string.
Replace Text Within a String
The PHP str_replace() function replaces some characters with some other characters in a
string.
<html>
<body>
<?php
echo strlen("Hello world!");
echo str_word_count("Hello world!");
echo strpos("Hello world!", "world"); // outputs 6
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!

?>
</body>
</html>

PHP 5 Operators
Operators are used to perform operations on variables and values.
PHP divides the operators in the following groups:
 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators

143
ALI RAZA MANZOOR (WEB DEVELOPER)
. PHP Arithmetic Operators
The PHP arithmetic operators are used with numeric values to perform common arithmetical
operations, such as addition, subtraction, multiplication etc

Operator Name Example Result

+ Addition $x + $y Sum of $x and $y

- Subtraction $x - $y Difference of $x and $y

* Multiplication $x * $y Product of $x and $y

/ Division $x / $y Quotient of $x and $y

% Modulus $x % $y Remainder of $x divided by $y

** Exponentiation $x ** $y Result of raising $x to the $y'th power (Introduced


in PHP 5.6)

<html>
<body>
<?php
$x = 10;
$y = 6;
echo $x + $y;?> </body></html>

PHP Assignment Operators


The PHP assignment operators are used with numeric values to write a value to a variable.

Assignment Same as... Description

144
ALI RAZA MANZOOR (WEB DEVELOPER)
x=y x=y The left operand gets set to the value of the
expression on the right

x += y x=x+y Addition

x -= y x=x-y Subtraction

x *= y x=x*y Multiplication

x /= y x=x/y Division

x %= y x=x%y Modulus

The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of
the assignment expression on the right.
<html>
<body>
<?php
$x = 15;
$x %= 4;
echo $x;
?></body></html>
PHP Comparison Operators

Operator Name Example Result

== Equal $x == $y Returns true if $x is equal to $y

=== Identical $x === $y Returns true if $x is equal to $y, and they are of
the same type

145
ALI RAZA MANZOOR (WEB DEVELOPER)
!= Not equal $x != $y Returns true if $x is not equal to $y

<> Not equal $x <> $y Returns true if $x is not equal to $y

!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are
not of the same type

> Greater than $x > $y Returns true if $x is greater than $y

< Less than $x < $y Returns true if $x is less than $y

>= Greater than or $x >= $y Returns true if $x is greater than or equal to $y


equal to

<= Less than or $x <= $y Returns true if $x is less than or equal to $y


equal to

The PHP comparison operators are used to compare two values (number or string):

PHP Increment / Decrement Operators


The PHP increment operators are used to increment a variable's value.

Operator Name Description

++$x Pre-increment Increments $x by one, then returns $x

$x++ Post-increment Returns $x, then increments $x by one

--$x Pre-decrement Decrements $x by one, then returns $x

146
ALI RAZA MANZOOR (WEB DEVELOPER)
Operator Name Example Result
$x-- Post-decrement Returns $x, then decrements $x by one

And And $x and $y True if both $x and $y are true

Or Or $x or $y True if either $x or $y is true

Xor Xor $x xor $y True if either $x or $y is true, but


not both

&& And $x && $y True if both $x and $y are true

|| Or $x || $y True if either $x or $y is true

! Not !$x True if $x is not true

The PHP decrement operators are used to decrement a variable's value.

PHP Logical Operators


The PHP logical operators are used to combine conditional statements.

<html>
<body>

<?php
$x = 100;
147
ALI RAZA MANZOOR (WEB DEVELOPER)
$y = 50;

if ($x == 100 or $y == 80) {


echo "Hello world!";
}
?>

</body>
</html>

PHP String Operators


PHP has two operators that are specially designed for strings.

Operator Name Example

. Concatenation $txt1 . $txt2 (Concatenation of


$txt1 and $txt2)

.= Concatenation assignment $txt1 .= $txt2

<html>
<body>
<?php
$txt1 = "Hello";
$txt2 = " world!";
$txt1 .= $txt2;
echo $txt1;
?>
</body>
</html>

PHP Array Operators

Operator Name Example Result

+ Union $x + $y Union of $x and $y

148
ALI RAZA MANZOOR (WEB DEVELOPER)
== Equality $x == $y Returns true if $x and $y have the same
key/value pairs

=== Identity $x === $y Returns true if $x and $y have the same


key/value pairs in the same order and of the
same types

!= Inequality $x != $y Returns true if $x is not equal to $y

<> Inequality $x <> $y Returns true if $x is not equal to $y

!== Non-identity $x !== $y Returns true if $x is not identical to $y

The PHP array operators are used to compare arrays.


<html>
<body>
<?php
$x = array("a" => "red", "b" => "green");
$y = array("c" => "blue", "d" => "yellow");
var_dump($x != $y);
?>
</body>
</html>

PHP 5 if...else...elseif Statements


PHP Conditional Statements
Very often when you write code, you want to perform different actions for different conditions.
You can use conditional statements in your code to do this.
In PHP we have the following conditional statements:
 if statement - executes some code if one condition is true
 if...else statement - executes some code if a condition is true and another code if that
condition is false
 if...elseif....else statement - executes different codes for more than two
conditions
 switch statement - selects one of many blocks of code to be executed

149
ALI RAZA MANZOOR (WEB DEVELOPER)
PHP - The if Statement
The if statement executes some code if one condition is true.
Syntax
if (condition) {
code to be executed if condition is true;
}
Example:
<html>
<body>
<?php
$t = date("H");

if ($t < "20") {


echo "Have a good day!";
}
?>
</body>
</html>

PHP - The if...else Statement


The if....else statement executes some code if a condition is true and another code if that
condition is false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
<!DOCTYPE html>
<html>
<body>
<?php
$t = date("H");

if ($t < "20") {


echo "Have a good day!";
} else {
echo "Have a good night!";
150
ALI RAZA MANZOOR (WEB DEVELOPER)
}
?>
</body>
</html>

PHP - The if...elseif....else Statement


The if....elseif...else statement executes different codes for more than two conditions.
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
}
<html>
<body>
<?php
$t = date("H");
echo "<p>The hour (of the server) is " . $t;
echo ", and will give the following message:</p>";
if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
</body>
</html>

PHP 5 switch Statement


The switch statement is used to perform different actions based on different conditions.

The PHP switch Statement


Use the switch statement to select one of many blocks of code to be executed.

151
ALI RAZA MANZOOR (WEB DEVELOPER)
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
<html>
<body>
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
</body>
</html>

PHP Loops
Often when you write code, you want the same block of code to run over and over again in a row.
Instead of adding several almost equal code-lines in a script, we can use loops to perform a task
like this.
In PHP, we have the following looping statements:
152
ALI RAZA MANZOOR (WEB DEVELOPER)
 while - loops through a block of code as long as the specified condition is
true
 do...while - loops through a block of code once, and then repeats the loop
as long as the specified condition is true
 for - loops through a block of code a specified number of times
 foreach - loops through a block of code for each element in an array

The PHP for Loop


The for loop is used when you know in advance how many times the script should run.
Syntax
for (init counter; test counter; increment counter) {
code to be executed;
}
Parameters:
 init counter: Initialize the loop counter value
 test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues.
If it evaluates to FALSE, the loop ends.
 increment counter: Increases the loop counter value
<html>
<body>
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
</body>
</html>
The PHP for each Loop
The for each loop works only on arrays, and is used to loop through each key/value pair in an
array.
Syntax
For each ($array as $value) {
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value and the array
pointer is moved by one, until it reaches the last array element.

153
ALI RAZA MANZOOR (WEB DEVELOPER)
<html>
<body>
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
</body>
</html>

The PHP while Loop


The while loop executes a block of code as long as the specified condition is true.
Syntax
while (condition is true) {
code to be executed;
}
<html>
<body>
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
</body>
</html>
The PHP do...while Loop
The do...while loop will always execute the block of code once, it will then check the
condition, and repeat the loop while the specified condition is true.
Syntax
do {
code to be executed;
} while (condition is true);
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will write some
output, and then increment the variable $x with 1. Then the condition is checked (is $x less than,
or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5:
154
ALI RAZA MANZOOR (WEB DEVELOPER)
<html>
<body>

<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
</body>
</html>

PHP 5 Functions
PHP User Defined Functions
Besides the built-in PHP functions, we can create our own functions.
A function is a block of statements that can be used repeatedly in a program.
A function will not execute immediately when a page loads.
A function will be executed by a call to the function.

Create a User Defined Function in PHP


A user-defined function declaration starts with the word function:
Syntax
function functionName() {
code to be executed;
}
<html>
<body>
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg();
?>
</body>
</html>

155
ALI RAZA MANZOOR (WEB DEVELOPER)
PHP Function Arguments
Information can be passed to functions through arguments. An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.The following example has a function
with one argument ($fname). When the familyName() function is called, we also pass along a
name (e.g. Jani), and the name is used inside the function, which outputs several different first
names, but an equal last name:
<html>
<body>
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
</body>
</html>

PHP Default Argument Value


The following example shows how to use a default parameter. If we call the function setHeight()
without arguments it takes the default value as argument:
<html>
<body>
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight();
setHeight(135);
setHeight(80);
?>
</body>
</html

156
ALI RAZA MANZOOR (WEB DEVELOPER)
PHP Functions - Returning values
To let a function return a value, use the return statement:
<html>
<body>
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}

echo "5 + 10 = " . sum(5,10) . "<br>";


echo "7 + 13 = " . sum(7,13) . "<br>";
echo "2 + 4 = " . sum(2,4);
?>

</body>
</html>

PHP 5 Arrays
An array stores multiple values in one single variable:
<html>
<body>

<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

</body>
</html>

What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables
could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
157
ALI RAZA MANZOOR (WEB DEVELOPER)
However, what if you want to loop through the cars and find a specific one? And
what if you had not 3 cars, but 300?
The solution is to create an array!
An array can hold many values under a single name, and you can access the
values by referring to an index number.

Create an Array in PHP


In PHP, the array() function is used to create an array:
array();
In PHP, there are three types of arrays:
 Indexed arrays - Arrays with a numeric index
 Associative arrays - Arrays with named keys
 Multidimensional arrays - Arrays containing one or more arrays
PHP Indexed Arrays
There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0), like this:
$cars = array("Volvo", "BMW", "Toyota");
or the index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
<html>
<body>

<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
</body>
</html>

158
ALI RAZA MANZOOR (WEB DEVELOPER)
Get The Length of an Array - The count() Function
The count() function is used to return the length (the number of elements) of an array:
<html>
<body>

<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>

</body>
</html>
Loop Through an Indexed Array
To loop through and print all the values of an indexed array, you could use a for loop, like this:
<html>
<body>

<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);

for($x = 0; $x < $arrlength; $x++) {


echo $cars[$x];
echo "<br>";
}
?>
</body>
</html>
PHP Associative Arrays
Associative arrays are arrays that use named keys that you assign to them.
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";

159
ALI RAZA MANZOOR (WEB DEVELOPER)
The named keys can then be used in a script:
<!DOCTYPE html>
<html>
<body>

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>

</body>
</html>
Loop Through an Associative Array
To loop through and print all the values of an associative array, you could use a foreach loop,
like this:
<!DOCTYPE html>
<html>
<body>

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>

</body>
</html>

PHP 5 Sorting Arrays


The elements in an array can be sorted in alphabetical or numerical order, descending or ascending.

160
ALI RAZA MANZOOR (WEB DEVELOPER)
PHP - Sort Functions For Arrays
In this chapter, we will go through the following PHP array sort functions:
 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
 arsort() - sort associative arrays in descending order, according to the value
 krsort() - sort associative arrays in descending order, according to the key

Sort Array in Ascending Order - sort()


The following example sorts the elements of the $cars array in ascending alphabetical order:
<html>
<body>

<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);

$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>

</body>
</html>
Sort Array in Descending Order - rsort()
The following example sorts the elements of the $cars array in descending alphabetical order:
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);

161
ALI RAZA MANZOOR (WEB DEVELOPER)
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>

</body>
</html>
Sort Array (Ascending Order), According to Value - asort()
The following example sorts an associative array in ascending order, according to the value:
<html>
<body>

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>

</body>
</html>
Sort Array (Ascending Order), According to Key - ksort()
The following example sorts an associative array in ascending order, according to the key:
<html>
<body>

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";

162
ALI RAZA MANZOOR (WEB DEVELOPER)
}
?>

</body>
</html>
Sort Array (Descending Order), According to Value - arsort()
The following example sorts an associative array in descending order, according to the value:
<html>
<body>

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>

</body>
</html>
Sort Array (Descending Order), According to Key - krsort()
The following example sorts an associative array in descending order, according to the key:
<html>
<body>

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>

163
ALI RAZA MANZOOR (WEB DEVELOPER)
</body>
</html>

PHP 5 Form Handling


The PHP superglobals $_GET and $_POST are used to collect form-data.
<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>
PHP - Complete Form Example
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}

164
ALI RAZA MANZOOR (WEB DEVELOPER)
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}

if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
165
ALI RAZA MANZOOR (WEB DEVELOPER)
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textar
ea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) &&
$gender=="female") echo"checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) &&
$gender=="male") echo"checked";?> value="male">Male
<input type="radio" name="gender" <?php if (isset($gender) &&
$gender=="other") echo"checked";?> value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>

166
ALI RAZA MANZOOR (WEB DEVELOPER)
SQL Database

Introduction to SQL
What is SQL?
 SQL stands for Structured Query Language
 SQL lets you access and manipulate databases
 SQL became a standard of the American National Standards Institute (ANSI) in 1986, and
of the International Organization for Standardization (ISO) in 1987

What Can SQL do?


 SQL can execute queries against a database
 SQL can retrieve data from a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can create new databases
 SQL can create new tables in a database
 SQL can create stored procedures in a database
 SQL can create views in a database
 SQL can set permissions on tables, procedures, and views

RDBMS
RDBMS stands for Relational Database Management System.
RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server, IBM
DB2, Oracle, MySQL, and Microsoft Access.
The data in RDBMS is stored in database objects called tables. A table is a collection of related
data entries and it consists of columns and rows.
Look at the "Customers" table:
Database Tables
A database most often contains one or more tables. Each table is identified by a name (e.g.
"Customers" or "Orders"). Tables contain records (rows) with data.
In this tutorial we will use the well-known Northwind sample database (included in MS Access
and MS SQL Server).
Below is a selection from the "Customers" table:

167
ALI RAZA MANZOOR (WEB DEVELOPER)
SQL Statements
Most of the actions you need to perform on a database are done with SQL statements.
The following SQL statement selects all the records in the "Customers" table:
Example:
SELECT * FROM Customers;
Some of The Most Important SQL Commands
 SELECT - extracts data from a database
 UPDATE - updates data in a database
 DELETE - deletes data from a database
 INSERT INTO - inserts new data into a database
 CREATE DATABASE - creates a new database
 ALTER DATABASE - modifies a database
 CREATE TABLE - creates a new table
 ALTER TABLE - modifies a table
 DROP TABLE - deletes a table
 CREATE INDEX - creates an index (search key)
 DROP INDEX - deletes an index

SQL SELECT Statement


The SELECT statement is used to select data from a database.
The data returned is stored in a result table, called the result-set.
SELECT Syntax
SELECT column1, column2, ...
FROM table_name;
Example:
SELECT CustomerName,City FROM Customers;
SELECT * FROM Customers;
The SQL SELECT DISTINCT Statement
The SELECT DISTINCT statement is used to return only distinct (different) values.
Inside a table, a column often contains many duplicate values; and sometimes you only want to
list the different (distinct) values.
SELECT DISTINCT Syntax

168
ALI RAZA MANZOOR (WEB DEVELOPER)
SELECT DISTINCT column1, column2, ...
FROM table_name;
Example:
SELECT Country FROM Customers;
SELECT COUNT(DISTINCT Country) FROM Customers;
The SQL WHERE Clause
The WHERE clause is used to filter records.
The WHERE clause is used to extract only those records that fulfill a specified condition.
WHERE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
SELECT * FROM Customers
WHERE Country='Mexico';
The SQL AND, OR and NOT Operators
The WHERE clause can be combined with AND, OR, and NOT operators.
The AND and OR operators are used to filter records based on more than one condition:
The AND operator displays a record if all the conditions separated by AND is TRUE.
The OR operator displays a record if any of the conditions separated by OR is TRUE.
The NOT operator displays a record if the condition(s) is NOT TRUE.
AND Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
SELECT * FROM Customers
WHERE Country='Germany' AND City='Berlin';
OR Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
SELECT * FROM Customers
WHERE City='Berlin' OR City='München';

169
ALI RAZA MANZOOR (WEB DEVELOPER)
NOT Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
SELECT * FROM Customers
WHERE NOT Country='Germany';

The SQL INSERT INTO Statement


The INSERT INTO statement is used to insert new records in a table.

INSERT INTO Syntax


It is possible to write the INSERT INTO statement in two ways.
The first way specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Example:
INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen
21', 'Stavanger', '4006', 'Norway');

The SQL UPDATE Statement


The UPDATE statement is used to modify the existing records in a table.
UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
UPDATE Multiple Records
It is the WHERE clause that determines how many records that will be updated.

170
ALI RAZA MANZOOR (WEB DEVELOPER)
The following SQL statement will update the contactname to "Juan" for all records where country
is "Mexico":
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';

The SQL DELETE Statement


The DELETE statement is used to delete existing records in a table.
DELETE Syntax
DELETE FROM table_name WHERE condition;
SQL DELETE Example
The following SQL statement deletes the customer "Alfreds Futterkiste" from the "Customers"
table:
Example
DELETE FROM Customers WHERE CustomerName='Ali';
Example of form insert data php to database
<!DOCTYPE html>
<html>
<head><Script>
function confirmDelete(){
return confirm("Are u Sure to Delte")
}
</Script></head>
<body>
<table width="500" border="2" cellpadding="1" cellspacing="2" align="center">
<form action="form.php" method="POST"> //method post
<tr><td colspan="2" align="center"><h2>HTML Forms</h2></td></tr>
<tr bgcolor="#EEEEEE"><td> Employee Name:</td>
<td> <input type="text" name="ename" pattern="[A-Za-z\s]+" ></td></tr>
<br>
<tr bgcolor="#DDDDDD"><td> Employee Salary:

171
ALI RAZA MANZOOR (WEB DEVELOPER)
<td><input type="number" name="esalary" ></td></tr>
<br><br>
<tr><td colspan="0"><input type="radio" name="gender" value="male"> Male </td><td>
<input type="radio" name="gender" value="female"> Female<br></td></tr>
<tr><td>Destination</td><td ><select id="budget" name="edesination">
<option value="">select</option>
<option value="1">Admin</option> <!-- first option contains value="" -->
<option value="2">Superviser</option>
<option value="3">Student</option>
</select>
<br /><br /></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="Submit"
name="submit"></td></tr>
</form> </table>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "class";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
//echo "connection ok";
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST['submit'])){
$ename=$_POST['ename'];
$esalary=$_POST['esalary'];
$edesination=$_POST['edesination'];

172
ALI RAZA MANZOOR (WEB DEVELOPER)
$gender=$_POST['gender'];
//insert Query
$sql= "INSERT INTO employee(empName,empSalary,empDesination,empGender)
VALUES('$ename','$esalary','$edesination',
'$gender')";
//echo "$sql";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
header("location: form.php");
}
}
?>
<table width="500" border="0" cellpadding="1" cellspacing="2" align="center">
<tr height="26" id="mainHeading">
<th height="26" colspan="6" class="txtHead">Update / Delete Bank</th>
</tr>
<tr height="26" bgcolor="#EEEEEE">
<th >Sr#</th>
<th >Employee Name</th>
<th >Employee Salary</th>
<th>employee Destination</th>
<th>employee Gender</th>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<?php
$i=1;
//select query
$sq="SELECT * FROM Employee";
$sqlQ=mysqli_query($conn,$sq);

173
ALI RAZA MANZOOR (WEB DEVELOPER)
while($sqlRow=mysqli_fetch_array($sqlQ))
{
?>
<?php
if($i%2==1)
{
?>
<tr height="26" bgcolor="#DDDDDD">
<?php
}
else
{
?>
<tr height="26" bgcolor="#EEEEEE">
<?php
}
?>
<td><?=$i?></td>
<td ><?=$sqlRow['empName']?></td>
<td ><?=$sqlRow['empSalary']?></td>
<td ><?=$sqlRow['empDesination']?></td>
<td ><?=$sqlRow['empGender']?></td>
<td ><a href="#">Edit</a></td>
<td><a href='form.php? ' onClick="confirmDelete();">Delete</a></td>
</tr>
<?php
$i++;
}
//mysqli_close($conn);
?>

174
ALI RAZA MANZOOR (WEB DEVELOPER)
</table>
<?php
$empNo =$_POST['empNo'];
// sending query delete Query
$del=mysqli_query("DELETE FROM employee WHERE empNo = '$empNo'")
or die(mysql_error()); //connect die
//echo "$del"
mysqli_close(); //connect of database close
?>
</body>
</html>
Other Example
Database connectivity:
Connect.php
<?
$servername = "localhost";
$username = "root";
$password = "";
$connname = "class";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $connname);
//echo "connection ok";
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
Register user :
//File name registeruser.php
<?php include('server.php') ;
175
ALI RAZA MANZOOR (WEB DEVELOPER)
?>
<!DOCTYPE html>
<html>
<head>
<title>Registration system PHP and MySQL</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="header">
<h2>Register</h2>
</div>
<form method="post" action="register.php">
<?php include('errors.php'); ?>
<div class="input-group">
<label>Username</label>
<input type="text" name="username" value="<?php echo $username; ?>">
</div>
<div class="input-group">
<label>Email</label>
<input type="email" name="email" value="<?php echo $email; ?>">
</div>
<div class="input-group">
<label>Password</label>
<input type="password" name="password_1">
</div>
<div class="input-group">
<label>Confirm password</label>
<input type="password" name="password_2">
</div>
<div class="input-group">

176
ALI RAZA MANZOOR (WEB DEVELOPER)
<button type="submit" class="btn" name="reg_user">Register</button>
</div>
<p>
Already a member? <a href="loginuser.php">Sign in</a>
</p>
</form>
</body>
</html>

Server file:
Server.php file name
In this file session and check login authentication
<?php
session_start();include("conect.php");
$username = ""; $email = ""; $errors = array();
if (isset($_POST['reg_user'])) {
$username = mysqli_real_escape_string($conn, $_POST['username']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password_1 = mysqli_real_escape_string($conn, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($conn, $_POST['password_2']);
if (empty($username)) { array_push($errors, "Username is required"); }
if (empty($email)) { array_push($errors, "Email is required"); }
if (empty($password_1)) { array_push($errors, "Password is required"); }
if ($password_1 != $password_2) { array_push($errors, "The two passwords
do not match"); }
$user_check_query = "SELECT * FROM users WHERE username='$username' OR
email='$email' LIMIT 1";
$result = mysqli_query($conn, $user_check_query);
$user = mysqli_fetch_assoc($result);
if ($user) {
if ($user['username'] === $username) {

177
ALI RAZA MANZOOR (WEB DEVELOPER)
array_push($errors, "Username already exists"); }
if ($user['email'] === $email) {
array_push($errors, "email already exists"); } }
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in
the database
$query = "INSERT INTO users (username, email, password)
VALUES('$username', '$email', '$password')";
mysqli_query($conn, $query);
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in"; header('location:
index.php'); } }
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
if (empty($username)) {
array_push($errors, "Username is required"); }
if (empty($password)) {
array_push($errors, "Password is required"); }
if (count($errors) == 0) { $password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND
password='$password'";
$results = mysqli_query($conn, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}else { array_push($errors, "Wrong username/password
combination"); } } }
?>

178
ALI RAZA MANZOOR (WEB DEVELOPER)
Error file:
Error.php in this file if error accrued then error show
<?php if (count($errors) > 0) : ?>
<div class="error">
<?php foreach ($errors as $error) : ?>
<p><?php echo $error ?></p>
<?php endforeach ?>
</div>
<?php endif ?>

login file:
login.php in this main login page when user login
<?php include('server.php');
include('errors.php'); ?>
<!DOCTYPE html>
<html>
<head>
<title>Registration system PHP and MySQL</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="header">
<h2>Login</h2>
</div>
<form method="post" action="loginuser.php">
<p><a href="loginuser.php">userlogin</a>
<a href="register.php">Register</a>
<a href="changepassword.php">chk password</a></p>
<?php ?>
<div class="input-group">

179
ALI RAZA MANZOOR (WEB DEVELOPER)
<label>Login id</label>
<input type="text" name="username" >
</div>
<div class="input-group">
<label>Password</label>
<input type="password" name="password">
</div>
<div class="input-group">
<button type="submit" class="btn" name="login_user">Login</button>
</div>
</form>
</body>
</html>

Change password file:


Changepassword.php in this file password change coding
<?php
session_start();
include 'conect.php';
$username = $_POST['username'];
$password = $_POST['password'];
$newpassword = $_POST['newpassword'];
$confirmnewpassword = $_POST['confirmnewpassword'];
$result = mysqli_query($conn,"SELECT password FROM users WHERE
username='$username'");
if(!$result)
{ echo "The username you entered does not exist"; }
else if($password!= mysqli_result($result, 0))
{ echo "You entered an incorrect password"; }
if($newpassword=$confirmnewpassword)

180
ALI RAZA MANZOOR (WEB DEVELOPER)
$sql=mysqli_query("UPDATE users SET password='$newpassword' where
username='$username'");
if($sql)
{ echo "Congratulations You have successfully changed your password"; }
else
{ echo "Passwords do not match"; }
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Password Change</title>
</head>
<body><h1>Change Password</h1>
<form method="POST" action="changepassword.php">
<table><tr><td>Enter your UserName</td>
<td><input type="username" size="10" name="username"></td>
</tr>
<tr><td>Enter your existing password:</td>
<td><input type="password" size="10" name="password"></td>
</tr>
<tr><td>Enter your new password:</td>
<td><input type="password" size="10" name="newpassword"></td>
</tr>
<tr><td>Re-enter your new password:</td>
<td><input type="password" size="10" name="confirmnewpassword"></td></tr>
</table>
<p><input type="submit" value="Update Password">
</form>
<p><a href="logout.php">Logout</a>
</body> </html>

181
ALI RAZA MANZOOR (WEB DEVELOPER)

S-ar putea să vă placă și