You are on page 1of 238

FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

Hamdard Institute of Engineering & Technology


Hamdard University

Web Engineering
Laboratory Manual

CSE-326
Semester 6th

Name: _______________________________________________

Roll Number: _________________________________________

Computer Systems Engineering Department


Hamdard Institute of Engineering & Technology
Hamdard University

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
List of Experiments
Lab Topics Remarks Mapping
No
1 Introduction to Web Engineering and Internet CLO_
Programming
2 Introduction to Dream viewer CLO_
3 Hyper Text Mark Up Language CLO_
4 Cascading Style Sheets CLO_
5 JavaScript Part-1 CLO_
6 JavaScript Part-2 CLO-
7 JavaScript Part-3 CLO_
8 Introduction to PHP CLO_
9 Programming with PHP CLO-
10 Creating Dynamic Websites CLO_
11 CLO_
Structured Query Language
12 PHP and MySQL CLO_
13 Cookies and Sessions CLO_
14 Site Building with Photoshop and Dream weaver CLO_

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Marks Evaluation

Marks
Class Experiment Experiment Total
Experiment No.
Participation Performance Reporting (1)
(0.3) (0.5) (0.2)
1
2
3
4
5
6

7
8
9
10
11
12
13
14

Total

Instructor’s signature

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
General Laboratory Procedure:
While there is no specific document to be submitted at the beginning of the Lab –unless your
instructor advises you otherwise-, you are expected to read the experiment fully before you come
to the laboratory? Interestingly, you can even try parts of the experiment at home. Here is a list
of programs that will equip you with a virtual lab at your home:
Troubleshooting

Things will not always go as expected; this is the nature of the learning process. While
conducting the Experiment think before you do anything. If you do so you will avoid wasting
time going down dead-end streets. Be logical and systematic. First, look for obvious errors that
are easy to fix. Is your measuring device correctly set and connected? Are you looking at the
proper scale? Is the power supply set for the correct voltage? Is the signal generator correctly set
and connected? How are the variables in the code set? Is there a syntax error? And so on. Next,
check for obvious misconnections or broken connections, at least in simple circuits.
As you work through your circuit, use your Lab Manual record tests and changes that you make
as you go along; don't rely on your memory for what you have tried. Identify some test points in
the system at which you know what the signal should be and work your way backwards from the
output through the test points until you find a good signal.

Neatness

When you have finished for the day, return all modules to their proper storage bins, return all test
leads and probes to their storage racks, return all equipment to its correct location, and clean up
the lab station. If appropriate switch off the unneeded equipment. Save your files in the
Computer and on any USB device for your records because you might not get the same PC
System again for the next experiment. Also email your file contents to your email address as a
backup.

Laboratory Safety
Always pay attention to what you are doing and you’re surrounding during the experiments and
notify the Instructor for any unlikely event or mishap and leave the Laboratory with the
permission of Instructor immediately.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
All students must read and understand the information in
this document with regard to laboratory safety and emergency procedures prior to the first
laboratory session.

Your personal laboratory safety depends mostly on YOU. Effort has been made to address
situations that may pose a hazard in the lab but the information and instructions provided cannot
be considered all-inclusive.

Students must adhere to written and verbal safety instructions throughout the academic term.
Since additional instructions may be given at the beginning of laboratory sessions, it is important
that all students arrive at each session on time. With good judgment, the chance of an accident in
this course is very small. Nevertheless, research and teaching workplaces (labs, shops, etc.) are
full of potential hazards that can cause serious injury and or damage to the equipment. Working
alone and unsupervised in laboratories is forbidden if you are working with hazardous substances
or equipment. With prior approval, at least two people should be present so that one can shut
down equipment and call for help in the event of an emergency. Safety training and/or
information should be provided by a faculty member, teaching assistant, lab safety contact, or
staff member at the beginning of a new assignment or when a new hazard is introduced into the
workplace.
Emergency Response

1. It is your responsibility to read safety and fire alarm posters and follow the instructions
during an emergency
2. Know the location of the fire extinguisher, eye wash, and safety shower in your lab and
know how to use them.
3. Notify your instructor immediately after any injury, fire or explosion, or spill.
4. Know the building evacuation procedures.

Common Sense

Good common sense is needed for safety in a laboratory. It is expected that each student will
work in a responsible manner and exercise good judgment and common sense. If at any time you
are not sure how to handle a particular situation, ask your Teaching Assistant or Instructor for
advice.DO NOT TOUCH ANYTHING WITH WHICH YOU ARE NOT COMPLETELY
FAMILIAR!!! It is always better to ask questions than to risk harm to yourself or damage to the
equipment.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Personal and General laboratory safety

1. Never eat, drink, or smoke while working in the laboratory.


2. Read labels carefully.
3. Do not use any equipment unless you are trained and approved as a user by your
supervisor.
4. Wear safety glasses or face shields when working with hazardous materials and/or
equipment.
5. Wear gloves when using any hazardous or toxic agent.
6. Clothing: When handling dangerous substances, wear gloves, laboratory coats, and safety
shield or glasses. Shorts and sandals should not be worn in the lab at any time. Shoes are
required when working in the machine shops.
7. If you have long hair or loose clothes, make sure it is tied back or confined.
8. Keep the work area clear of all materials except those needed for your work. Coats should
be hung in the hall or placed in a locker. Extra books, purses, etc. should be kept away
from equipment that requires air flow or ventilation to prevent overheating.
9. Disposal - Students are responsible for the proper disposal of used material if any in
appropriate containers.

10. Equipment Failure - If a piece of equipment fails while being used, report it
immediately to your lab assistant or tutor. Never try to fix the problem yourself because
you could harm yourself and others.
11. If leaving a lab unattended, turn off all ignition sources and lock the doors.
12. Never pipette anything by mouth.
13. Clean up your work area before leaving.
14. Wash hands before leaving the lab and before eating.
15. Unauthorized person(s) shall not be allowed in a laboratory for any reason

Electrical safety

1. Obtain permission before operating any high voltage equipment.


2. Maintain an unobstructed access to all electrical panels.
3. Wiring or other electrical modifications must be referred to the Electronics Shop or the
Building Coordinator.
4. Avoid using extension cords whenever possible. If you must use one, obtain a heavy-
duty one that is electrically grounded, with its own fuse, and install it safely. Extension

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
cords should not go under doors, across aisles, be hung from the ceiling, or plugged into
other extension cords.
5. Never, ever modify, attach or otherwise change any high voltage equipment.
6. Always make sure all capacitors are discharged (using a grounded cable with an
insulating handle) before touching high voltage leads or the "inside" of any equipment
even after it has been turned off. Capacitors can hold charge for many hours after the
equipment has been turned off.
7. When you are adjusting any high voltage equipment or a laser which is powered with a
high voltage supply, USE ONLY ONE HAND. Your other hand is best placed in a
pocket or behind your back. This procedure eliminates the possibility of an accident
where high voltage current flows up one arm, through your chest, and down the other
arm.
8. Discard damaged cords, cords that become hot, or cords with exposed wiring.
9. Before equipment is energized ensure, (1) circuit connections and layout have been
checked by a Teaching Assistant (TA) and (2) all colleagues in your group give their
assent.
10. Know the correct handling, storage and disposal procedures for batteries, cells,
capacitors, inductors and other high energy-storage devices.
11. Experiments left unattended should be isolated from the power supplies. If for a
special reason, it must be left on, a barrier and a warning notice are required.
12. Equipment found to be faulty in any way should be reported to the Lab Engineer
immediately and taken out of service until inspected and declared safe.
13. Voltages above 50 V RMS AC and 120 V DC are always dangerous. Extra
precautions should be considered as voltage levels are increased.
14. Never make any changes to circuits or mechanical layout without first isolating
the circuit by switching off and removing connections to power supplies.
15. Know what you must do in an emergency.
16. Emergency Power Off: Every lab is equipped with and Emergency Power Off
System.
17. Only authorized personnel are permitted to reset power once the Emergency
Power Off system has been engaged.

Electrical Emergency Response


The following instructions provide guidelines for handling two types of electrical emergencies:
1. When someone suffers serious electrical shock, he or she may be knocked unconscious.
If the victim is still in contact with the electrical current, immediately turn off the
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
electrical power source. If you cannot disconnect the power source, depress the
Emergency Power Off switch.
2. Do not touch a victim that is still in contact with a live power source; you could be
electrocuted.
3. Have someone call for emergency medical assistance immediately. Administer first-aid,
as appropriate.
4. If an electrical fire occurs, try to disconnect the electrical power source, if possible. If the
fire is small and you are not in immediate danger; and you have been properly trained in
fighting fires, use the correct type of fire extinguisher to extinguish the fire. When in
doubt, push in the Emergency Power Off button.

5. NEVER use water to extinguish an electrical fire.

Mechanical safety
1. When using compressed air, use only approved nozzles and never direct the air towards
any person.
2. Guards on machinery must be in place during operation.
3. Exercise care when working with or near hydraulically- or pneumatically-driven
equipment. Sudden or unexpected motion can inflict serious injury.
Additional Safety Guidelines

1. Never do unauthorized experiments.


2. Never work alone in laboratory.
3. Keep your lab space clean and organized.
4. Do not leave an on-going experiment unattended.
5. Always inform your instructor if you break a thermometer. Do not clean mercury
yourself!!
6. Never taste anything. Never pipette by mouth; use a bulb.
7. Never use open flames in laboratory unless instructed by TA.
8. Check your glassware for cracks and chips each time you use it. Cracks could cause
the glassware to fail during use and cause serious injury to you or lab mates.
9. Maintain unobstructed access to all exits, fire extinguishers, electrical panels,
emergency showers, and eye washes.
10. Do not use corridors for storage or work areas.
11. Do not store heavy items above table height. Any overhead storage of supplies on
top of cabinets should be limited to lightweight items only. Also, remember that a
36" diameter area around all fire sprinkler heads must be kept clear at all times.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
12. Areas containing lasers, biohazards, radioisotopes, and carcinogens should be posted
accordingly. However, do not post areas unnecessarily and be sure that the labels are
removed when the hazards are no longer present.
13. Be careful when lifting heavy objects. Only shop staff may operate forklifts or
cranes.
14. Clean your lab bench and equipment, and lock the door before you leave the
laboratory.
Clothing
1. Dress properly during a laboratory activity.

2. Long hair, dangling jewelry, and loose or baggy

Clothing are a hazard in the laboratory.

3. Long hair must be tied back, and dangling jewelry and baggy clothing must be secured.

4. Shoes must completely cover the foot.

5. No sandals allowed on lab days.

6. A lab coat or smock should be worn during laboratory experiments.


Accidents and Injuries
1. Do not panic.

2. Report any accident (spill, breakage, etc.) or injury (cut, burn,


etc.) to the teacher immediately, no matter how trivial it seems.

3. If you or your lab partner is hurt, immediately (and loudly) yell


out the teacher's name to get the teacher's attention.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
General Warning Signs

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
LAB # 01
Introduction to Web Engineering and Internet Programming

Objectives:
 Be able to learn theoretical concept related to Web Engineering & Internet programming
 Be able to understand the different web protocols and their usage in Web Architecture.

Theory:
Web Engineering
Web Engineering is the application of systematic, disciplined, and quantified approaches to development,
operation and maintenance of web based applications.

World Wide Web:


The World Wide Web (abbreviated as WWW or W3, commonly known as the Web), is a system of
interlinked hypertext documents accessed via the Internet. With a web browser, one can view web pages
that may contain text, images, videos, and other multimedia, and navigate between them via hyperlinks.
The terms Internet and World Wide Web are often used in everyday speech without much distinction.
However, the Internet and the World Wide Web are not the same. The Internet is a global system of
interconnected computer networks. In contrast, the Web is one of the services that run on the Internet. It is
a collection of text documents and other resources, linked by hyperlinks and URLs, usually accessed by
web browsers from web servers. In short, the Web can be thought of as an application "running" on the
Internet

Web Servers:
Web server can refer to either the hardware (the computer) or the software (the computer application) that
helps to deliver Web content that can be accessed through the Internet. The most common use of web
servers is to host websites.

Web Browsers:
A web browser is a software application for retrieving, presenting and traversing information resources on
the World Wide Web. A web browser can also be defined as an application software or program designed
to enable users to access, retrieve and view documents and other resources on the Internet. The major web
browsers are Chrome, Firefox, Internet Explorer, Opera, and Safari.

Web Pages:
A web page or webpage is a document or information resource that is suitable for the World Wide Web
and can be accessed through a web browser and displayed on a monitor or mobile device. This
information is usually in HTML or XHTML format, and may provide navigation to other web pages via
hypertext links. Web pages frequently subsume other resources such as style sheets, scripts and images
into their final presentation.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Web pages are requested and served from web servers using Hypertext Transfer Protocol (HTTP).
Webpages are of two types:

 Static Web Pages : Web pages may consist of files of static text and other content stored
within the web server's file system
 Dynamic Web Pages: Web pages which are constructed by server-side software when
they are requested

Uniform Resource Identifier (URI)


A uniform resource identifier (URI) is a string of characters used to identify a name or a resource. Such
identification enables interaction with representations of the resource over a network typically the World
Wide Web using specific protocols.

Uniform Resource Locator (URL):


A uniform resource locator, abbreviated URL, also known as web address, is a specific character string
that constitutes a reference to a resource. In most web browsers, the URL of a web page is displayed on
top inside an address bar.

Uniform Resource name (URN):


A URN (Uniform Resource Name) is an Internet resource with a name that, unlike a URL, has persistent
significance - that is, the owner of the URN can expect that someone else (or a program) will always be
able to find the resource.

Relation of URL and URN with URI


URIs can be classified as locators (URLs), as names (URNs), or as both. A uniform resource name
(URN) functions like a person's name, while a uniform resource locator (URL) resembles that person's
street address. In other words, the URN defines an item's identity, while the URL provides a method for
finding it.

Anatomy of URL:
Consider the web address http://www.googleguide.com/searchEngines/google/searchLeader.html . Here’s what it
all means:

http transfer protocol (type of information being transferred)


www.googleguide.com website name, host name
googleguide second-level domain name
com top-level domain name
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
searchEngines directory name (major category)
google sub-directory name (sub-category)
searchLeader file name (a file within the directory)
html file format

Hyper Link:
A hyperlink (or link) is a reference to data that the reader can directly follow, or that is followed
automatically. A hyperlink points to a whole document or to a specific element within a document.
Hypertext is text with hyperlinks. A user following hyperlinks is said to navigate or browse the hypertext.

How Does WWW Work?


Viewing a web page on the World Wide Web normally begins either by typing the URL of the page into a
web browser or by following a hyperlink to that page or resource. The web browser then initiates a series
of communication messages, behind the scenes, in order to fetch and display it.
First, the browser resolves the server-name portion of the URL (example.org) into an Internet Protocol
address using the globally distributed database known as the Domain Name System (DNS); this lookup
returns an IP address such as 208.80.152.2. The browser then requests the resource by sending an HTTP
request across the Internet to the computer at that particular address. It makes the request to a particular
application port in the underlying Internet Protocol Suite so that the computer receiving the request can
distinguish an HTTP request from other network protocols it may be servicing such as e-mail delivery;
the HTTP protocol normally uses port 80.

Internet Protocols:
The Internet uses different standards to transfer information to and from remote computers and networks.
These standards, known as protocols, allow computers to communicate with one another in a structured
method. Internet protocols are at work when a user visits his favorite video site or signs into a social
network as well as when a user checks her new mail messages or composes a message to her boss.
Here is the list of the common Internet Protocols:

1) HTTP
2) HTTPS
3) FTP
4) TCP/IP

HTTP

The protocol commonly known as HTTP is an acronym for Hyper Text Transfer Protocol. These
four letters are likely to appear in lowercase in the address bar of a web browser while viewing
this article. They are located at the beginning of the address and are used to tell the browser how
to properly process the data on the page and display the data to a computer user. The word hyper

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
in the acronym is used to specify that the text is not linear and can actually be linked in many
ways. HTTP was originally used as a way to display text, but browsers have evolved to be able
to display much more using the protocol.

HTTPS

Occasionally, you might notice that a website URL starts with https:. This indicates that the
document is using the Hypertext Transfer Protocol over Secure Socket Layer or Hypertext
Transfer Protocol Secure. Online banking websites may use this protocol to protect sensitive
information such as account and routing numbers.

In addition to the https; at the front of the webpage address, the browser may display a small
padlock icon to illustrate to the user that the webpage is using this protocol. Firefox 3.0 and
Internet Explorer 7.0 and later also show that this protocol is active by altering the address bar
when the website relies on a Secure Sockets Layer to encrypt data. In Internet Explorer, the
address bar will appear green while Firefox will show the name of the institution--such as a
bank--on the left side of the address bar.

FTP

The primary protocol used to transfer large amounts of data from place to place across the
Internet is known as FTP. FTP is an acronym that appropriately stands for File Transfer Protocol.
Computers known as FTP servers are places on the Internet where files can be stored and
accessed via File Transfer Protocol. A computer user may access an FTP server using FTP client
software. Popular web browsers are also able to access files that are located on an FTP server.
An FTP server basically appears to a computer user as a remote hard drive and browsing the files
on an FTP server is similar to browsing a computer's hard drive with a file manager.

TCP/IP

The network protocol suite that is primarily responsible for the transfer of raw data across the
Internet is known as TCP/IP. The acronym stands for a combination of Transfer Control Protocol
and Internet Protocol. The TCP side primarily describes how computers connect and how data is
to be transmitted across the Internet properly. Internet network addressing concepts such as an IP
address are part of the IP side of the TCP/IP protocol suite. Each connection to the Internet has a
unique numeric address known as an IP address. Alphanumeric web addresses such as Google's
web address are actually translated into a numeric IP address and a computer known as a web
server is contacted at the remote IP address to provide the page seen in a browser where the
alphanumeric address was typed.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Internet Programming:
Internet programming is defined as the client server communication established with the help of scripting
and markup languages following all the communication protocols and transmission protocols.
Client Side Internet Programming:

 Supports the interaction within a webpage.


 The code required to process user-input is downloaded and compiled by the browser or
plug-in.
 Example: Html, CSS, JavaScript etc.

Server Side Internet Programming:

 With server-side scripting, completing an activity involves sending information to


another computer (server) across the internet. The server then runs programs that process
the information and returns the results, typically a webpage.
 Search engines use server-side processing. When a keyword is sent, a program on a
server matches the word or phrase entered against an index of website content.
 Server-side scripting languages include ASP and PHP.

Conclusion
In this lab you have got enough idea about what is internet programming and why it is used.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Tasks:

Q1. What is server client architecture?


Client-server architecture is a computing model in which the server hosts, delivers and
manages most ofthe resources and services to be consumed by the client. This type of
architecture has one or more client computers connected to a central server over a network or
internet connection. Client-server architecture is also known as a networking computing
model or client-server network because all the requests and services are delivered over a
network.
Q2. What is internet?
The Internet is a global network of billions of computers and other electronic devices. With the
Internet, it's possible to access almost any information, communicate with anyone else in the world,
and do much more. You can do all of this by connecting a computer to the Internet, which is also
called going online

Q3. What is a protocol? And how many types of internet protocols are there?
In networking, a protocol is a set of rules for formatting and processing data. Network protocols
are like a common language for computers. The computers within a network may use vastly
different software and hardware; however, the use of protocols enables them to communicate with
each other regardless.
There are 10 types of protocol name as follows

1. Transmission Control Protocol (TCP)


2. Internet Protocol (IP)
3. User Datagram Protocol (UDP)
4. Post office Protocol (POP)
5. Simple mail transport Protocol (SMTP)
6. File Transfer Protocol (FTP)
7. Hyper Text Transfer Protocol (HTTP)
8. Hyper Text Transfer Protocol Secure (HTTPS)
9. Telnet
10. Gopher

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Q4. What is difference between HTTP and HTTPS?
https  is htpp with encryption. The only difference between the two protocols is that HTTPS
uses TLs (SSL) to encrypt normal HTTP requests and responses. As a result, HTTPS is far more
secure than HTTP. A website that uses HTTP has http:// in its URL, while a website that uses
HTTPS has https://
Q5. Difference between Static and Dynamic web pages.

Difference between static web pages and dynamic


web pages

In static web pages, Pages will remain same until In dynamic web pages, Content of pages are
someone changes it manually. different for different visitors.

Static Web Pages are simple in terms of


Dynamic web pages are complicated.
complexity.

In dynamic web page, Information are change


In static web pages, Information are change rarely.
frequently.

Static Web Page takes less time for loading than


Dynamic web page takes more time for loading.
dynamic web page.

Q6. Search for the name of Five FTP sites. Also gives short definition of them.

1: JSCAPE :

Securely managing your file transfer Managed file transfer software


processes. and services.

GoAnywhere:
Secure exchange of data.Managed file transfer solution.

Progress MOVEit:
Advanced security features MFT Software

FileZilla:
Free FTP solutions, Client & Server. Free and open-source FTP & FTPS Server

Cerberus:
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Flexibility to support any protocol Powerful Secure File Transfer

Q7. How do you connect to FTP server? Attach snapshot of every step.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

Learning outcomes:

This Lab covers the basic Web Engineering & Internet programming introductions theoretically.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

Lab # 02
Introduction to Dreamweaver
Objectives:
In this lab you will learn how to install dream viewer. How and why it is used.

Theory:
What is Dreamweaver?
Adobe Dreamweaver is a proprietary web development application developed by Adobe Systems.
Dreamweaver was originally developed by Macromedia in 1997, and was maintained by them until
Macromedia was acquired by Adobe Systems in 2005.

Features of Dreamweaver:
 Adobe Dreamweaver is a web design and development application that provides a visual
WYSIWYG editor.

 A code editor with standard features such as syntax highlighting, code completion, etc.
for generating code hints to assist the user in writing code.

 The Design view facilitates rapid layout design and code generation as it allows users to
quickly create and manipulate the layout of HTML elements.

 Dreamweaver features an integrated browser for previewing developed webpages in the


program's own preview pane in addition to allowing content to be open in locally
installed web browsers.

 It provides transfer and synchronization features, the ability to find and replace lines of
text or code by search terms or regular expressions across the entire site.

 The behaviors panel also enables use of basic JavaScript without any coding knowledge.

 Dreamweaver can use third-party "Extensions" to extend core functionality of the


application. Dreamweaver is supported by a large community of extension developers
who make extensions available (both commercial and free) for most web development
tasks from simple rollover effects to full-featured shopping carts.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Download Dreamweaver:
You can download the latest version of Dreamweaver from the adobe site or you can download through
torrent. Installation of Dreamweaver:

1. Run the setup.

2. The installer will initialize

3. Accept the agreement

4. Select Install as trial, select Language and click Next

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

5. Select the desired options and click Next

6. The installation will begin

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

7. After the installation is finished click Done.

8. Installation is completed

Cracking the Dreamweaver:


1. Either enters the serial key if you have purchased it or if you have downloaded the serial
key through torrent then also you must be having it.
2. The alternate way if you don’t have the serial key is to replace the amtlib.dll file. Copy
this dll file and paste and replace at the following location : C:\Program Files\Adobe\
Adobe Dreamweaver CS5.5
3. Now your Dreamweaver is ready to use.

Conclusion
We have learned step by step installation of Dreamweaver. Now we will be using it in the next labs.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Tasks:

Install the Dreamweaver at your home PCs.

Note: Attach a snap shot of every above mentioned task.

Learning outcomes:

On the completion of this lab we have acknowledged of basic introduction to Dreamweaver programming

Software.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

Lab # 03
Hyper Text Markup Language
Objective:

 To learn about HTML.

Theory:
What is HTML?
HTML stands for Hyper Text Markup Language. Hypertext is simply a piece of text that works as a link.
Markup Language is a way of writing layout information within documents. A markup language is a set
of markup tags. The tags describe document content

An HTML document is a plain text file that contains text and nothing else. When a browser opens an
HTML file, the browser will look for HTML codes in the text and use them to change the layout, insert
images, or create links to other pages.Since HTML documents are just text files they can be written in
even the simplest text editor.

Why Do We Study HTML?


It is possible to create webpages without knowing anything about the HTML source behind the page.
There are excellent editors on the market that will take care of the HTML parts. All you need to do is
layout the page. However, if you want to make it above average in webdesign, it is strongly
recommended that you understand these tags.

The most important benefits are:

 You can use tags the editor does not support.


 You can read the code of other people's pages, and "borrow" the cool effects.
 You can do the work yourself, when the editor simply refuses to create the effectsyou
want.

You can write your HTML by hand with almost any available text editor, including notepad that comes as
a standard program with Windows. All you need to do is type in the code, then save the document,
making sure to put an .html extension or an .htm extension to the file.

HTML Tags:
HTML markup tags are usually called HTML tags. Basically, a computer sees an "A" as simply an "A" -
whether it is bold, italic, big or small. To tell the browser that an "A" should be bold we need to put a
markup in front of the A. Such a markup is called a Tag. All HTML tags are enclosed in < and >.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

Syntax:
<tagname>content</tagname>
HTML Page Structure:
<html>

<
<head></head>

<body></body>

</html>

 All webpages have an <html> tag at the beginning and the end, telling the browser where
the document starts and where it stops.
 The head is used for text and tags that do not show directly on the page.
 The body is used for text and tags that are shown directly on the page.

Head Section:
The head section of the webpage includes all the stuff that does not show directly on the resulting page.

The <title> and </title> tags encapsulate the title of your page. The title is what shows in the top of your
browser window when the page is loaded.
Another thing you will often see in the head section is Meta tags. Meta tags are used for, among other
things, to improve the rankings in search engines.
Quite often the head section contains JavaScript which is a programming language for more complex
HTML pages.
Finally, more and more pages contain codes for cascading style sheets (CSS).CSS is a rather new
technique for optimizing the layout of major websites.

Body Section:
The body of the document contains all that can be seen when the user loads the page.

In the rest of this lab you can learn in detail about all the different aspects of HTML, including:
 Text
o Formatting
o Resizing
o Layout
o Listing
 Links
o To local pages

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
o To pages at other sites
o To bookmarks
 Images
o Inserting images (GIF and jpg)
o Adding a link to an image
 Backgrounds
o Colors
o Images
o Fixed Image
 Tables
 Frames
 Forms
 Metatags
 Hexadecimal Colors

The <!DOCTYPE>Declaration:
The <!DOCTYPE> declaration helps the browser to display a web page correctly.

There are many different documents on the web, and a browser can only display an HTML page 100%
correctly if it knows the HTML type and version used.

Example:
<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>

<p>My first paragraph.</p>

</body>
</html>
 The DOCTYPE declaration defines the document type
 The text between <html> and </html> describes the web page
 The text between <body> and </body> is the visible page content
 The text between <h1> and </h1> is displayed as a heading
 The text between <p> and </p> is displayed as a paragraph

Writing HTML Using Notepad or TextEdit


HTML can be edited by using a professional HTML editor like:
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
 Adobe Dreamweaver
 Microsoft Expression Web
 CoffeeCup HTML Editor

However, for learning HTML we recommend a text editor like Notepad (PC) or TextEdit (Mac). We
believe using a simple text editor is a good way to learn HTML. Follow the 4 steps below to create your
first web page with Notepad.

Step 1: Start Notepad

To start Notepad go to:


Start
    All Programs
        Accessories
            Notepad

Step 2: Edit Your HTML with Notepad

Type your HTML code into your Notepad:

Step 3: Save Your HTML

Select Save as.. in Notepad's file menu.


When you save an HTML file, you can use either the .htm or the .html file extension. There is no
difference, it is entirely up to you.

Step 4: Run the HTML in Your Browser

Start your web browser and open your html file from the File, Open menu, or just browse the folder and
double-click your HTML file.

HTML Headings
HTML headings are defined with the <h1> to <h6> tags.

Example
<!DOCTYPE html>
<html>
This is heading 1
<body> This is heading 2
This is heading 3
<h1>This is heading 1</h1> This is heading 4
<h2>This is heading 2</h2>
<h3>This is heading 3</h3> This is heading 5
<h4>This is heading 4</h4> This is heading 6
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>

</body>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
</html>

HTML Paragraphs
HTML paragraphs are defined with the <p> tag.

Example
<!DOCTYPE html> This is a paragraph.
<html>
<body>
This is a paragraph.
<p>This is a paragraph.</p>
<p>This is a paragraph.</p> This is a paragraph.
<p>This is a paragraph.</p>

</body>
</html>
HTML Links
HTML links are defined with the <a> tag.

Example
<!DOCTYPE html> This is a link
<html>
<body>
<a href="http://www.hamdard.edu.pk">
This is a link</a>

</body>
</html>
HTML Images
HTML images are defined with the <img> tag.
<!DOCTYPE html>
<html>
<body>
<imgsrc="hamdard.jpg" width="104"
height="142"></body>
</html>

HTML Elements
An HTML element is everything from the start tag to the end tag.

Start tag * Element content End tag *

<p> This is a paragraph </p>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

<a href="default.htm"> This is a link </a>

<br>

*The start tag is often called the opening tag. The end tag is often called the closing tag.

HTML Element Syntax

 An HTML element starts with a start tag / opening tag


 An HTML element ends with an end tag / closing tag
 The element content is everything between the start and the end tag
 Some HTML elements have empty content
 Empty elements are closed in the start tag
 Most HTML elements can have attributes

Example
<!DOCTYPE html>
<html>
<body>
<p>This is my first paragraph.</p>
</body>
</html>

The example above contains 3 HTML elements: <html> element, <body> element and <p> element.
Empty HTML Elements
HTML elements with no content are called empty elements. <br> is an empty element without a closing
tag (the <br> tag defines a line break).

HTML Attributes
Attributes provide additional information about HTML elements.

 HTML elements can have attributes


 Attributes provide additional information about an element
 Attributes are always specified in the start tag
 Attributes come in name/value pairs like: name="value"
 Attribute values should always be enclosed in quotes.
 Double style quotes are the most common, but single style quotes are also allowed.

HTML links are defined with the <a> tag. The link address is specified in the href attribute:

<!DOCTYPE html> This is a link


<html>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
<body>
<a href="http://www.hamdard.edu.pk">
This is a link</a>

</body>
</html>
Below is a list of some attributes that can be used on any HTML element:

Attribute Description

Specifies one or more classnames for an element (refers to a class in a style


class
sheet)

id Specifies a unique id for an element

style Specifies an inline CSS style for an element

title Specifies extra information about an element (displayed as a tool tip)

HTML Lines
The <hr>tag creates a horizontal line in an HTML page. The hr element can be used to separate content:
<!DOCTYPE html> The hr tag defines a horizontal rule:
<html>
<body> This is a paragraph.
<p>The hr tag defines a horizontal rule:</p>
<hr> This is a paragraph.
<p>This is a paragraph.</p>
<hr>
<p>This is a paragraph.</p>
This is a paragraph.
<hr>
<p>This is a paragraph.</p>
</body>
</html>
HTML Comments
Comments can be inserted into the HTML code to make it more readable and understandable. Comments
are ignored by the browser and are not displayed. Comments are written like this:
<!DOCTYPE html> This is a regular paragraph
<html>
<body>

<!--This comment will not be displayed-->


<p>This is a regular paragraph</p>

</body>
</html>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

HTML Text Formatting


Tag Description

<b> Defines bold text

<em> Defines emphasized text

<i> Defines a part of text in an alternate voice or mood

<small> Defines smaller text

<strong> Defines important text

<sub> Defines subscripted text

<sup> Defines superscripted text

<ins> Defines inserted text

<del> Defines deleted text

Example
<!DOCTYPE html> This text is bold
<html>
<body> This text is strong
<p><b>This text is bold</b></p>
<p><strong>This text is strong</strong></p> This text is italic
<p><i>This text is italic</i></p>
<p><em>This text is emphasized</em></p> This text is emphasized
<p>This is<sub> subscript</sub> and
<sup>superscript</sup></p> This is subscript and superscript
</body>
</html>
HTML Hyperlinks (Links)
The HTML <a> tag defines a hyperlink.
A hyperlink (or link) is a word, group of words, or image that you can click on to jump to another
document.
When you move the cursor over a link in a Web page, the arrow will turn into a little hand.
The most important attribute of the <a> element is the href attribute, which indicates the link’s
destination.
By default, links will appear as follows in all browsers:
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
 An unvisited link is underlined and blue
 A visited link is underlined and purple
 An active link is underlined and red

Syntax
The HTML code for a link is simple. It looks like this:
<a href="url">Link text</a>
The href attribute specifies the destination of a link.

Example
<a href="http://www.hamdard.edu.pk/">Visit Hamdard</a>
which will display like this: Visit Hamdard
Clicking on this hyperlink will send the user to Hamdard's homepage.
Tip: The "Link text" doesn't have to be text. It can be an image or any other HTML element.

HTML Links - The target Attribute


The target attribute specifies where to open the linked document.
The example below will open the linked document in a new browser window or a new tab:
<!DOCTYPE html> Visit Hamdard!
<html> If you set the target attribute to "_blank", the link will
<body> open in a new browser window/tab.

<a href="http://www.hamdard.edu.pk"
target="_blank">Visit Hamdard!</a>

<p>If you set the target attribute to "_blank", the link


will open in a new browser window/tab.</p>

</body>
</html>
HTML Links - The id Attribute
The id attribute can be used to create a bookmark inside an HTML document.
Tip: Bookmarks are not displayed in any special way. They are invisible to the reader.
Example
An anchor with an id inside an HTML document:
<a id="tips">Useful Tips Section</a>

Create a link to the "Useful Tips Section" inside the same document:
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
<a href="#tips">Visit the Useful Tips Section</a>
Or, create a link to the "Useful Tips Section" from another page:
<a href="http://www.w3schools.com/html_links.htm#tips">
Visit the Useful Tips Section</a>
HTML Tables
Tables are defined with the <table> tag.
A table is divided into rows (with the <tr> tag), and each row is divided into data cells (with the <td>
tag). td stands for "table data," and holds the content of a data cell. A <td> tag can contain text, links,
images, lists, forms, other tables, etc.
<table border="1"> row 1, cell 1 row 1, cell 2
<tr>
<td>row 1, cell 1</td> row 2, cell 1 row 2, cell 2
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
HTML Tables and the Border Attribute
If you do not specify a border attribute, the table will be displayed without borders. Sometimes this can be
useful, but most of the time, we want the borders to show.
To display a table with borders, specify the border attribute:
<table border="1">
<tr>
<td>Row 1, cell 1</td>
<td>Row 1, cell 2</td>
</tr>
</table>
HTML Table Tags
Tag Description

<table> Defines a table

<th> Defines a header cell in a table

<tr> Defines a row in a table

<td> Defines a cell in a table

<caption> Defines a table caption

<colgroup> Specifies a group of one or more columns in a table for formatting

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
<col> Specifies column properties for each column within a <colgroup> element

<thead> Groups the header content in a table

<tbody> Groups the body content in a table

<tfoot> Groups the footer content in a table

HTML Lists
An ordered list: An unordered list:

1. The first list item  List item


2. The second list item  List item
3. The third list item  List item

HTML Unordered Lists


An unordered list starts with the <ul> tag. Each list item starts with the <li> tag. The list items are marked
with bullets (typically small black circles).
<ul>  Coffee
<li>Coffee</li>  Milk
<li>Milk</li>
</ul>
HTML Ordered Lists
An ordered list starts with the <ol> tag. Each list item starts with the <li> tag. The list items are marked
with numbers.
<ol> 1. Coffee
<li>Coffee</li> 2. Milk
<li>Milk</li>
</ol>
HTML Definition Lists
A definition list is a list of items, with a description of each item. The <dl> tag defines a definition list.
The <dl> tag is used in conjunction with <dt> (defines the item in the list) and <dd> (describes the item
in the list):
<dl> Coffee
<dt>Coffee</dt> - black hot drink
<dd>- black hot drink</dd> Milk
<dt>Milk</dt> - white cold drink
<dd>- white cold drink</dd>
</dl>
HTML List Tags
Tag Description

<ol> Defines an ordered list

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
<ul> Defines an unordered list

<li> Defines a list item

<dl> Defines a definition list

<dt> Defines an item in a definition list

<dd> Defines a description of an item in a definition list

HTML Block and Inline Elements:


HTML Block Elements
Most HTML elements are defined as block level elements or as inline elements. Block level elements
normally start (and end) with a new line when displayed in a browser. Examples: <h1>, <p>, <ul>,
<table>

HTML Inline Elements


Inline elements are normally displayed without starting a new line. Examples: <b>, <td>, <a>, <img>

The HTML <div> Element


The HTML <div> element is a block level element that can be used as a container for grouping other
HTML elements.  The <div> element has no special meaning. Except that, because it is a block level
element, the browser will display a line break before and after it.
When used together with CSS, the <div> element can be used to set style attributes to large blocks of
content.
Another common use of the <div> element, is for document layout. It replaces the "old way" of defining
layout using tables. Using tables is not the correct use of the <table> element. The purpose of the <table>
element is to display tabular data.

The HTML <span> Element


The HTML <span> element is an inline element that can be used as a container for text. The <span>
element has no special meaning.
When used together with CSS, the <span> element can be used to set style attributes to parts of the text.

HTML Grouping Tags

Tag Description

<div> Defines a section in a document (block-level)

<span> Defines a section in a document (inline)

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
HTML Forms
HTML forms are used to pass data to a server. An HTML form can contain input elements like text fields,
checkboxes, radio-buttons, submit buttons and more. A form can also contain select lists, textarea,
fieldset, legend, and label elements.
The <form> tag is used to create an HTML form:
<form>
.
input elements
.
</form>
HTML Forms - The Input Element
The most important form element is the <input> element. The <input> element is used to select user
information.
An <input> element can vary in many ways, depending on the type attribute. An <input> element can be
of type text field, checkbox, password, radio button, submit button, and more.
The most common input types are described below.

Text Fields
<input type="text"> defines a one-line input field that a user can enter text into:
<form>
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname"> First name:
</form> Last name:

Password Field
<input type="password"> defines a password field:
<form>
Password: <input type="password" name="pwd">
</form> Password:
Bottom of Form
Note: The characters in a password field are masked
(shown as asterisks or circles).

Radio Buttons
<input type="radio"> defines a radio button. Radio buttons let a user select ONLY ONE of a limited
number of choices:
<form>
<input type="radio" name="gender"
value="male">Male<br> Male
<input type="radio" name="gender" Female
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
value="female">Female
</form>
Checkboxes
<input type="checkbox"> defines a checkbox. Checkboxes let a user select ZERO or MORE options of a
limited number of choices.
<form>
<input type="checkbox" name="vehicle" value="Bike">I
have a bike<br> I have a bike
<input type="checkbox" name="vehicle" value="Car">I I have a car
have a car
</form>
Submit Button
<input type="submit"> defines a submit button.
A submit button is used to send form data to a server. The data is sent to the page specified in the form's
action attribute. The file defined in the action attribute usually does something with the received input:
<form name="input" action="html_form_action.asp"
method="get">
Username: <input type="text" name="user"> Username:
<input type="submit" value="Submit">
</form>

HTML Iframe:
An iframe is used to display a web page within a web page. Syntax for adding an iframe:
<iframe src="URL"></iframe>
The URL points to the location of the separate page.

Conclusion
This lab has taught you how to use HTML to create your own web site.
HTML is the universal markup language for the Web. HTML lets you format text, add graphics, create
links, input forms, frames and tables, etc., and save it all in a text file that any browser can read and
display.
The key to HTML is the tags, which indicates what content is coming up.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Tasks:

Q1. Create WebPages that display the timetable of eight semester of your discipline.
Code:
<!DOCTYPE html>
<html>

<body>
<h1 align="center">TIME TABLE</h1>
<table border="5" cellspacing="0" align="center">

<tr>
<td align="center" height="50"
width="100"><br>
<b>Day</b></br>
</td>
<td align="center" height="50"
width="100">
<b>Monday</b>
</td>
<td align="center" height="50"
width="100">
<b>Tuesday</b>
</td>
<td align="center" height="50"
width="100">
<b>Wednesday</b>
</td>
<td align="center" height="50"
width="100">
<b>Thursday</b>
</td>
<td align="center" height="50"
width="100">
<b>Friday</b>
</td>

</tr>
<tr>
<td align="center" height="50">
<b>1<br> 08:30-09:25</b></td>
<td align="center" height="50" rowspan="2">NA<br>Ambreen
Zehra</td>
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
<td align="center" height="50" rowspan="3">TA Shaikh<br>DSD
LAB</td>
<td align="center" height="50">OS<br>M Shakir</td>
<td align="center" height="50">
DSD<br>TA Shaikh
</td>
<td align="center" height="50"></td>
</tr>
<tr>
<td align="center" height="50">
<b>2<br>09:25-10:20</b>
</td>
<td align="center"
height="50"rowspan="2">DSD<br>TA Shaikh
</td>
<td align="center" height="50" rowspan="2">SE-1<br>Zaheen
Fatima</td>
<td align="center" height="50"></td>

</tr>
<tr>
<td align="center" height="50">
<b>3<br>10:20-11:15</b>
</td>
<td align="center" height="50">OS<br>M Shakir</td>
<td align="center" height="50"></td>

</tr>
<tr>
<td align="center" height="50">
<b>4<br>11:15-12:10</b>
</td>
<td align="center" height="50">WE-11<br>Zaheen fatima</td>
<td align="center" height="50">WE-11<br>Zaheen fatima</td>
<td align="center" height="50" rowspan="3">WE-11-L<br>Zaheen
fatima</td>
<td align="center"
height="50"rowspan="3">OS-L<br>M Shakir
</td>
<td align="center" height="50"></td>
</tr>
<tr>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
<td align="center" height="50">
<b>5<br>12:10-01:05</b>
</td>
<td align="center"
height="50">SE-1<br>Zaheen Fatima
</td>
<td align="center" height="50">OS<br>M Shakir</td>

<td align="center" height="50"></td>


</tr>
<tr>
<td align="center" height="50">
<b>6<br>01:05-02:00</b>
</td>
<td align="center" height="50">WE-11<br>Zaheen Fatima</td>
<td align="center" height="50">NA<br>Ambreen Zehra</td>
<td align="center" height="50"></td>

</tr>
</table>
</body>

</html>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Q2. Create students registration form with all concerned fields that are used by the university.
CODE:
<Html>
<head>
<title>
Registration Page
</title>
</head>
<body >
<br>
<br>
<form>

<label> Firstname </label>


<input type="text" name="firstname" size="15"/> <br> <br>

<label> Lastname: </label>


<input type="text" name="lastname" size="15"/> <br> <br>

<label>
Course :
</label>
<select>
<option value="Course">Course</option>
<option value="BCA">BCA</option>
<option value="BBA">BBA</option>
<option value="B.Tech">B.Tech</option>
<option value="MBA">MBA</option>
<option value="MCA">MCA</option>
<option value="M.Tech">M.Tech</option>
</select>

<br>
<br>
<label>
Gender :
</label><br>
<input type="radio" name="male"/> Male <br>
<input type="radio" name="female"/> Female <br>
<input type="radio" name="other"/> Other
<br>
<br>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
<label>
Phone :
</label>
<input type="text" name="country code" value="+92" size="2"/>
<input type="text" name="phone" size="10"/> <br> <br>
Address
<br>
<textarea cols="80" rows="5" value="address">
</textarea>
<br> <br>
Email:
<input type="email" id="email" name="email"/> <br>
<br> <br>
Password:
<input type="Password" id="pass" name="pass"> <br>
<br> <br>
Re-type password:
<input type="Password" id="repass" name="repass"> <br> <br>
<input type="button" value="Submit"/>
</form>
</body>
</html>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

Q3. Implement the different types of lists used in html to obtain following on web browser.(hint:
use all three lists)

CODE:

<!DOCTYPE html>

<html>

<head>

<title> list </title>

<style>

body{

h1{

color:blue;

p{

color:blue;

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
}

</style>

</head>

<body>

<ol>

<li>Coffee</li>

<dd>-a hot drink made from the roasted and ground bean -like seeds of a tropical shrub</dd>

<li>Tea</li>

<ul>

<li>Black tea</li>

<ul>

<li>tea served without milk</li>

<li>tea of the most usual type,that is fully fermented before drying</li>

</ul>

<li>Green tea</li>

<dd>-tea made from unfermented leaves that that is pale in color.....</dd>

</ul>

<li>Pina Colada</li>

<dd>-a cocktail made with rum,pineapple,juice and coconut</dd>

</ol>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

</body>

</html>

Note: Attach a snap shot of every above mentioned task.

Learning outcomes:

This lab has covered so many HTML basic and general command knowledge, on the completion of this

Lab students can create ordered and & un-ordered listings easily.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

Lab # 04
Cascading Style Sheets
Objectives:
In this lab you will learn about adding styles to your webpage and DHTML concepts.

Theory:
What is CSS?
Cascading Style Sheets (CSS) is a style sheet language used for describing the presentation semantics (the
look and formatting) of a document written in a markup language. Its most common application is to style
web pages written in HTML.
CSS is designed primarily to enable the separation of document content (written in HTML or a similar
markup language) from document presentation, including elements such as the layout, colors, and fonts.
This separation can improve content accessibility, provide more flexibility and control in the specification
of presentation characteristics, enable multiple pages to share formatting, and reduce complexity and
repetition in the structural content.

Advantages of CSS
-CSS saves time
-Pages Load Faster
-Easy Maintenance
-Superior Styles to HTML
-Multiple Device Compatibility
-Global Web Standards
-Offline Browsing
-Platform Independence

CSS Syntax
CSS has a simple syntax and uses a number of English keywords to specify the names of various style
properties.
A style sheet consists of a list of rules. Each rule or rule-set consists of one or more selectors, and a
declaration block. A declaration-block consists of a list of declarations in braces. Each declaration itself
consists of a property, a colon (:), and a value. If there are multiple declarations in a block, a semi-colon
(;) must be inserted to separate each declaration. In CSS, selectors are used to declare which part of the
markup a style applies to, a kind of match expression. Selectors may apply to all elements of a specific
type, to elements specified by attribute, or to elements depending on how they are placed relative to, or
nested within, others in the document tree.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

Example:
p {color:red;text-align:center;}
OR
p
{
color:red;
text-align:center;
}

Ways to Insert CSS


There are three ways of inserting a style sheet:

 External style sheet


 Internal style sheet
 Inline style

External Style Sheet


An external style sheet is ideal when the style is applied to many pages. With an external style sheet, you
can change the look of an entire Web site by changing one file. Each page must link to the style sheet
using the <link> tag. The <link> tag goes inside the head section:
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>

An external style sheet can be written in any text editor. The file should not contain any html tags. Your
style sheet should be saved with a .css extension. An example of a style sheet file is shown below:

hr {color:sienna;}
p {margin-left:20px;}
body {background-image:url("images/back40.gif");}
Internal Style Sheet
An internal style sheet should be used when a single document has a unique style. You define internal
styles in the head section of an HTML page, by using the <style> tag, like this:

<head>
<style>
hr {color:sienna;}

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
p {margin-left:20px;}
body {background-image:url("images/back40.gif");}
</style>
</head>
Inline Styles
An inline style loses many of the advantages of style sheets by mixing content with presentation. Use this
method sparingly! To use inline styles you use the style attribute in the relevant tag. The style attribute
can contain any CSS property. The example shows how to change the color and the left margin of a
paragraph:

<p style="color:sienna;margin-left:20px">This is a paragraph.</p>


The id Selector
The id selector is used to specify a style for a single, unique element. The id selector uses the id attribute
of the HTML element, and is defined with” #". The style rule below will be applied to the element with
id="para1".
<!DOCTYPE html> Hello World!
<html>
<head> This paragraph is not affected by the style.
<style>
#para1
{
text-align:center;
color:red;
}
</style>
</head>

<body>
<p id="para1">Hello World!</p>
<p>This paragraph is not affected by the style.</p>
</body>
</html>

The class Selector


The class selector is used to specify a style for a group of elements. Unlike the id selector, the class
selector is most often used on several elements. This allows you to set a particular style for many HTML
elements with the same class. The class selector uses the HTML class attribute, and is defined with a "."In
the example below, all HTML elements with class="center" will be center-aligned.
<!DOCTYPE html>
<html>
Center-aligned heading
<head>
<style> Center-aligned paragraph.
.center
{
text-align:center;
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
color:red;
}
</style>
</head>

<body>
<h1 class="center">Center-aligned heading</h1>
<p class="center">Center-aligned paragraph.</p>
</body>
</html>

You can also specify that only specific HTML elements should be affected by a class. In the example
below, all p elements with class="center" will be center-aligned:
<!DOCTYPE html>
<html>
This heading will not be affected
<head>
<style> This paragraph will be center-aligned.
p.center
{ Simple paragraph tag
text-align:center;
}
</style>
</head>

<body>
<h1 class="center">This heading will not be
affected</h1>
<p class="center">This paragraph will be center-
aligned.</p>
<p>Simple paragraph tag</p>
</body>
</html>

Multiple Style Sheets


If some properties have been set for the same selector in different style sheets, the values will be inherited
from the more specific style sheet. 
For example, an external style sheet has these properties for the h3 selector:
h3
{
color:red;
text-align:left;
font-size:8pt;
}

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
And an internal style sheet has these properties for the h3 selector:

h3
{
text-align:right;
font-size:20pt;
}

If the page with the internal style sheet also links to the external style sheet the properties for h3 will be:

color:red;
text-align:right;
font-size:20pt;

The color is inherited from the external style sheet and the text-alignment and the font-size is replaced by
the internal style sheet.

Multiple Styles Will Cascade into One


Cascading order
What style will be used when there is more than one style specified for an HTML element?
Generally all the styles will "cascade" into a new "virtual" style sheet by the following rules, where
number four has the highest priority:

1. Browser default
2. External style sheet
3. Internal style sheet (in the head section)
4. Inline style (inside an HTML element)

So, an inline style (inside an HTML element) has the highest priority, which means that it will override a
style defined inside the <head> tag, or in an external style sheet, or in a browser (a default value).

CSS Styling
1. CSS Background
Property Description
background Sets all the background properties in one declaration
background- Sets whether a background image is fixed or scrolls with the rest of the
attachment page
background-color Sets the background color of an element
background-image Sets the background image for an element
background-position Sets the starting position of a background image
background-repeat Sets how a background image will be repeated

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
2. CSS Text
Property Description
color Sets the color of text
direction Specifies the text direction/writing direction
letter-spacing Increases or decreases the space between characters in a text
line-height Sets the line height
text-align Specifies the horizontal alignment of text
text-decoration Specifies the decoration added to text
text-indent Specifies the indentation of the first line in a text-block
text-shadow Specifies the shadow effect added to text
text-transform Controls the capitalization of text
unicode-bidi
vertical-align Sets the vertical alignment of an element
white-space Specifies how white-space inside an element is handled
word-spacing Increases or decreases the space between words in a text

3. CSS Fonts
Property Description
font Sets all the font properties in one declaration
font-family Specifies the font family for text
font-size Specifies the font size of text
font-style Specifies the font style for text
font-variant Specifies whether or not a text should be displayed in a small-caps font
font-weight Specifies the weight of a font

4. CSS Links
The four links states are:

1. a:link - a normal, unvisited link


2. a:visited - a link the user has visited
3. a:hover - a link when the user mouse over it
4. a:active - a link the moment it is clicked

When setting the style for several link states, there are some order rules:

 a:hover MUST come after a:link and a:visited


 a:active MUST come after a:hover

Property Description
background-color The background-color property specifies the background color for links
text-decoration The text-decoration property is mostly used to remove underlines from links

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

5. CSS Lists
The CSS list properties allow you to:

 Set different list item markers for ordered lists


 Set different list item markers for unordered lists
 Set an image as the list item marker

Property Description
list-style Sets all the properties for a list in one declaration
list-style-image Specifies an image as the list-item marker
list-style-position Specifies if the list-item markers should appear inside or outside the content
flow
list-style-type Specifies the type of list-item marker

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Tasks:
1. Create an HTML page having title “lab 2 task 1”, the page should include text boxes and
button (with no function) as shown in picture below. An external style sheets is to be
inserted.
 Make the page responsive.
 The form should be at the center of page.
 For styling of text boxes and button, use id selector or class selector or use html
tags in style sheet.
 Textboxes for password should use appropriate input type.
 Follow the link below for further help and make sure your page is look alike
o file:///Y:/Sarah%20Anwar/F17/Web%20Engineering/Lab%20Manual/
WebE%20tasks/lab%2002/task%201.html

<div class="heading">Sign UP</div>


(Implement a class selector)

FORM

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

<div class="heading">Sign UP</div>


(Implement a class selector)

FORM

HTML CODE:
<html>

<head>

<meta name="viewport" content="width=device-width,initial-scale=1.0"/>

<link href="contact_form_style.css" type="text/css" rel="stylesheet"/>

</head>

<body>

<div id="wrapper">

<div id="contact_form_div">

<p id="contact_label">Sign-Up</p>

<form method="post" action="">


Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
<p><input type="text"id="lab4" placeholder="Student Name"></p>

<p><input type="number"id="lab4" placeholder="Enrollment Number"></p>

<p><input type="password"id="lab4" placeholder="Password"></p>

<p><input type="password"id="lab4" placeholder="Confirm Password"></p>

<p><input type="submit"id="lab4" value="SUBMIT"></p>

</form>

</div>

</div>

</body>

</html>

EXTERNAL CSS CODE:


body

margin:0 auto;

padding:0px;

text-align:center;

width:100%;

font-family: "Myriad Pro","Helvetica Neue",Helvetica,Arial,Sans-Serif;

//background-color:#AED6F1;

#wrapper

margin:0 auto;

padding:0px;

text-align:center;

width:995px;
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
}

#wrapper h1

margin-top:50px;

font-size:45px;

color:#1B4F72;

#wrapper h1 p

font-size:18px;

#contact_form_div

width:330px;

margin-left:320px;

padding:10px;

background-color:white;

border-style: solid;

border-width: 2px;

border-color:#DCDCDC;

#contact_label

color:#00CED1;

margin:15px;

margin-bottom:30px;

}
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
#contact_form_div

margin:15px;

margin-bottom:30px;

font-size:25px;

font-weight:bold;

color:white;

text-decoration:underline;

#lab4

width:230px;

height:40px;

border-radius:2px;

font-size:17px;

padding-left:5px;

border:none;

background-color:#9370DB;

color:#2F4F4F;

#contact_form_div input[type="submit"]

width:230px;

height:40px;

border:none;
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
border-radius:2px;

font-size:17px;

background-color:blue;

border-bottom:3px solid #3498DB;

color:white;

font-weight:bold;

@media only screen and (min-width:700px) and (max-width:995px)

#wrapper

width:100%;

#wrapper h1

font-size:30px;

#contact_form_div

width:50%;

margin-left:25%;

padding-left:0px;

padding-right:0px;

#contact_form_div #lab4

{
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
width:80%;

#contact_form_div #lab4

width:80%;

#contact_form_div input[type="submit"]

width:80%;

Note: Attach a snap shot of every above mentioned task and bring colored copy of browser
display.

Learning outcomes:

This lab gave the knowledge for how to make simple HTML web pages beautiful with Cascading Style

Sheet (CSS), basic CSS programs has been covered in this lab.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Lab # 05
JavaScript Part 1
Objectives:

 To learn the basic structure of JavaScript.

Theory:
JavaScript a Scripting Language:
 A scripting language is a lightweight programming language.
 JavaScript is programming code that can be inserted into HTML pages.
 JavaScript inserted into HTML pages, can be executed by all modern web browsers.
 JavaScript is easy to learn.
What is JavaScript?
 JavaScript and Java are two different computer languages.
 It is an object-oriented computer programming language commonly used to create
interactive effects within web browsers.
 JavaScript, is a text-based object-oriented computer programming language meant to run
as part of a web-based application and to create interactive effects within web browsers.
 One of the three pillars of web development—the other two being HTML and CSS.
How to Script?
JavaScripts in HTML must be inserted between <script> and </script> tags.JavaScripts can be put in the
<body> and in the <head> section of an HTML page.

The <script> Tag


To insert a JavaScript into an HTML page, use the <script> tag.The <script> and </script> tells where the
JavaScript starts and ends.The lines between the <script> and </script> contain the JavaScript:

Syntax
<script>
Js code
</script>

JavaScript in <head> or <body>


You can place an unlimited number of scripts in an HTML document. Scripts can be in the <body> or in
the <head> section of HTML, and/or in both. It is a common practice to put functions in the <head>
section, or at the bottom of the page. This way they are all in one place and do not interfere with page
content.

JavaScript in <body>
In this example, JavaScript writes into the HTML <body> while the page loads:
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

<!DOCTYPE html> JavaScript can write directly into the HTML output
<html> stream:
<body>
This is a heading
This is a paragraph.
<p>
JavaScript can write directly into the HTML output You can only use document.write in the HTML
stream: output. If you use it after the document has loaded (e.g.
</p> in a function), the whole document will be overwritten.

<script>
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
</script>

<p>
You can only use <strong>document.write</strong> in
the HTML output.
If you use it after the document has loaded (e.g. in a
function), the whole document will be overwritten.
</p>

</body>
</html>

A JavaScript Function
A function is a JavaScript procedure—a set of statements that performs a task or calculates a value. To
use a function, you must define it somewhere in the scope from which you wish to call it.
 JavaScript functions are defined with the function keyword.
 You can use a function declaration or a function expression.

Function Declarations
Syntax
Function functionName(parameters) {
   code to be executed
}

Declared functions are not executed immediately. They are "saved for later use", and will be executed
later, when they are invoked (called upon).
Example

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
function myFunction(a, b) {
     return a * b;
}

Function Expressions
A JavaScript function can also be defined using an expression.
A function expression can be stored in a variable:
Example
var x = function (a, b) {return a * b};

A JavaScript Function in <head>


In this example, a JavaScript function is placed in the <head> section of an HTML page.

<!DOCTYPE html>
<html>
My Web Page
<head> A Paragraph.
<script> On Click
function myFunction() My Web Page
{
document.getElementById("demo").innerHTML="My
My First JavaScript Function
First JavaScript Function";
}
</script>
</head>

<body>

<h1>My Web Page</h1>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try


it</button>

</body>
</html>

A JavaScript Function in <body>


In this example, a JavaScript function is placed in the <body> section of an HTML page.
The function is called when a button is clicked:

<!DOCTYPE html>
<html>
My Web Page
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
<body> A Paragraph.
On Click
<h1>My First Web Page</h1>
My Web Page
<p id="demo">A Paragraph.</p> My First JavaScript Function
<button type="button" onclick="myFunction()">Try
it</button>

<script>
function myFunction()
{
document.getElementById("demo").innerHTML="My
First JavaScript Function";
}
</script>

</body>
</html>

External JavaScripts
Scripts can also be placed in external files. External files often contain code to be used by several
different web pages.External JavaScript files have the file extension .js.To use an external script, point to
the .js file in the "src" attribute of the <script> tag:

My Web Page
A Paragraph.
On Click
My Web Page
My First External JavaScript
Note: myFunction is stored in an external
file called "myScript.js".

JavaScript Outputs:
Manipulating HTML Elements
To access an HTML element from JavaScript, you can use the document.getElementById(id) method.
Use the "id" attribute to identify the HTML element:

<!DOCTYPE html>
<html>
My First Web Page
<body> My First JavaScript
<h1>My First Web Page</h1>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
<p id="demo">My First Paragraph.</p>

<script>
document.getElementById("demo").innerHTML="My
First JavaScript";
</script>

</body>
</html>

The JavaScript is executed by the web browser. In this case, the browser will access the HTML element
with id="demo", and replace its content (innerHTML) with "My First JavaScript".
Writing to The Document Output
The example below writes a <p> element directly into the HTML document output:

<!DOCTYPE html>
<html>
My First Web Page
<body> My First JavaScript
<h1>My First Web Page</h1>

<script>
document.write("<p>My First JavaScript</p>");
</script>

</body>
</html>

Warning
Use document.write() only to write directly into the document output. If you execute document.write after
the document has finished loading, the entire HTML page will be overwritten:

<!DOCTYPE html>
<html>
My First Web Page
<body> My First Paragraph.
After click
<h1>My First Web Page</h1>
Oops! The document disappeared!
<p>My First Paragraph.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
document.write("Oops! The document disappeared!");
}

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
</script>

</body>
</html>

JavaScript Statements
 JavaScript is a sequence of statements to be executed by the browser.
 JavaScript statements are "commands" to the browser. The purpose of the statements is to
tell the browser what to do.
 This JavaScript statement tells the browser to write "Hello Dolly" inside an HTML
element with id="demo":

document.getElementById("demo").innerHTML="Hello Dolly";

Semicolon “;”
 Semicolon separates JavaScript statements.
 Normally you add a semicolon at the end of each executable statement.
 Using semicolons also makes it possible to write many statements on one line.

JavaScript Code
 JavaScript code (or just JavaScript) is a sequence of JavaScript statements.
 Each statement is executed by the browser in the sequence they are written.
 This example will manipulate two HTML elements:

<!DOCTYPE html>
<html>
My Web Page
<body> Hello Dolly
How are you?
<h1>My Web Page</h1>

<p id="demo">A Paragraph.</p>

<div id="myDIV">A DIV.</div>

<script>
document.getElementById("demo").innerHTML="Hello
Dolly";
document.getElementById("myDIV").innerHTML="How
are you?";
</script>

</body>
</html>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

JavaScript Code Blocks


 JavaScript statements can be grouped together in blocks.
 Blocks start with a left curly bracket, and end with a right curly bracket.
 The purpose of a block is to make the sequence of statements execute together.
 A good example of statements grouped together in blocks, are JavaScript functions.
 This example will run a function that will manipulate two HTML elements:

<!DOCTYPE html>
<html>
My Web Page
<body> I am a paragraph.
I am a div.
<h1>My Web Page</h1> When you click on "Try it", the two
<p id="myPar">I am a paragraph.</p> elements will change.
<div id="myDiv">I am a div.</div> After Click
My Web Page
<p>
Hello Dolly
<button type="button" onclick="myFunction()">Try
it</button> How are you?
</p>

<script>
function myFunction()
{
document.getElementById("myPar").innerHTML="Hello
Dolly";
document.getElementById("myDiv").innerHTML="How
are you?";
}
</script>

<p>When you click on "Try it", the two elements will


change.</p>

</body>
</html>

JavaScript is Case Sensitive


 JavaScript is case sensitive.
 Watch your capitalization closely when you write JavaScript statements:
 A function getElementById is not the same as getElementbyID.
 A variable named myVariable is not the same as MyVariable.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
White Space
JavaScript ignores extra spaces. You can add white space to your script to make it more readable. The
following lines are equivalent:
var name="Hege";
var name = "Hege";

Break up a Code Line


You can break up a code line within a text string with a backslash. The example below will be displayed
properly:

document.write("Hello \
World!");

However, you cannot break up a code line like this:

document.write \
("Hello World!");

JavaScript Comments
 JavaScript comments can be used to make the code more readable.
 Comments will not be executed by JavaScript.
 Comments can be added to explain the JavaScript, or to make the code more readable.
 Single line comments start with //.
 The following example uses single line comments to explain the code:

<!DOCTYPE html>
<html>
Welcome to my Homepage
<body> This is my first paragraph.
Note: The comments are not executed.
<h1 id="myH1"></h1>

<p id="myP"></p>

<script>
// Write to a heading:
document.getElementById("myH1").innerHTML="Welcome
to my Homepage";
// Write to a paragraph:
document.getElementById("myP").innerHTML="This is my
first paragraph.";
</script>

<p><strong>Note:</strong> The comments are not


executed.</p>

</body>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
</html>
JavaScript Multi-Line Comments
 Multi line comments start with /* and end with */.
 The following example uses a multi-line comment to explain the code:

<!DOCTYPE html> Welcome to my


<html> Homepage
<body>
This is my first paragraph.
<h1 id="myH1"></h1> Note: The comment-block
is not executed.
<p id="myP"></p>

<script>
/*
The code below will write
to a heading and to a paragraph,
and will represent the start of
my homepage:
*/
document.getElementById("myH1").innerHTML="Welcome
to my Homepage";
document.getElementById("myP").innerHTML="This is
my first paragraph.";
</script>

<p><strong>Note:</strong> The comment-block is not


executed.</p>

</body>
</html>

JavaScript Variables
JavaScript variables are "containers" for storing information:

<!DOCTYPE html> 5
<html>
<body> 6
11
<script>
var x=5;
var y=6;
var z=x+y;

document.write(x + "<br>");
document.write(y + "<br>");
document.write(z + "<br>");
</script>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

</body>
</html>

As with algebra, JavaScript variables can be used to hold values (x=5) or expressions (z=x+y). Variable
can have short names (like x and y) or more descriptive names (age, sum, totalvolume).
 Variable names must begin with a letter
 Variable names can also begin with $ and _ (but we will not use it)
 Variable names are case sensitive (y and Y are different variables)

JavaScript Data Types


 JavaScript variables can also hold other types of data, like text values (name="John
Doe").
 In JavaScript a text like "John Doe" is called a string.
 There are many types of JavaScript variables, but for now, just think of numbers and
strings.
 When you assign a text value to a variable, put double or single quotes around the value.
 When you assign a numeric value to a variable, do not put quotes around the value. If you
put quotes around a numeric value, it will be treated as text.

<!DOCTYPE html> 3.14


<html>
<body>
John Doe
Yes I am!
<script>
var pi=3.14;
var name="John Doe";
var answer='Yes I am!';

document.write(pi + "<br>");
document.write(name + "<br>");
document.write(answer + "<br>");
</script>

</body>
</html>

Declaring (Creating) JavaScript Variables


Creating a variable in JavaScript is most often referred to as "declaring" a variable.
You declare JavaScript variables with the var keyword:
var carname;

After the declaration, the variable is empty (it has no value).


To assign a value to the variable, use the equal sign:
carname="Volvo";

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

However, you can also assign a value to the variable when you declare it:
var carname="Volvo";

In the example below we create a variable called carname, assigns the value "Volvo" to it, and put the
value inside the HTML paragraph with id="demo":

<!DOCTYPE html> After Click


<html>
<body> Volvo

<p>Click the button to create a variable, and display the


result.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction()
{
varcarname="Volvo";
document.getElementById("demo").innerHTML=carname;
}
</script>

</body>
</html>

JavaScript Data Types
String, Number, Boolean, Array, Object, Null, Undefined.

JavaScript Has Dynamic Types


JavaScript has dynamic types. This means that the same variable can be used as different types:
var x;               // Now x is undefined
var x = 5;           // Now x is a Number
var x = "John";      // Now x is a String

JavaScript Strings
A string is a variable which stores a series of characters like "John Doe". A string can be any text inside
quotes. You can use single or double quotes:
var carname="Volvo XC60";
var carname='Volvo XC60';

You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
var answer="It's alright";
var answer="He is called 'Johnny'";

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
var answer='He is called "Johnny"';

JavaScript Numbers
JavaScript has only one type of numbers. Numbers can be written with, or without decimals:
var x1=34.00;      //Written with decimals
var x2=34;         //Written without decimals

Extra large or extra small numbers can be written with scientific (exponential) notation:
var y=123e5;      // 12300000
var z=123e-5;     // 0.00123

JavaScript Booleans
Booleans can only have two values: true or false.
var x=true;
var y=false;

JavaScript Arrays
The following code creates an Array called cars:
var cars=new Array();
cars[0]="Saab";
cars[1]="Volvo";
cars[2]="BMW";
or (condensed array):
var cars=new Array("Saab","Volvo","BMW");
or (literal array):
var cars=["Saab","Volvo","BMW"];

JavaScript Objects
An object is delimited by curly braces. Inside the braces the object's properties are defined as name and
value pairs (name : value). The properties are separated by commas:
var person={firstname:"John", lastname:"Doe", id:5566};
The object (person) in the example above has 3 properties: firstname, lastname, and id.
Spaces and line breaks are not important. Your declaration can span multiple lines:
var person={
firstname : "John",
lastname  : "Doe",
id        :  5566
};

You can address the object properties in two ways:


name=person.lastname;
name=person["lastname"];

Undefined and Null


Undefined is the value of a variable with no value. Variables can be emptied by setting the value to null;

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
cars=null;
person=null;

Declaring Variable Types


When you declare a new variable, you can declare its type using the "new" keyword:
varcarname=new String;
var x=      new Number;
var y=      new Boolean;
var cars=   new Array;
var person= new Object;

JavaScript Objects
"Everything" in JavaScript is an Object: a String, a Number, an Array, a Date. In JavaScript, an object is
data, with properties and methods.

Properties and Methods


Properties are values associated with an object.
Methods are actions that can be performed on objects.

A Real Life Object. A Car:


The properties of the car include name, model, weight, color, etc.
All cars have these properties, but the values of those properties differ from car to car.
The methods of the car could be start(), drive(), brake(), etc.
All cars have these methods, but they are performed at different times.

Creating JavaScript Objects


Almost "everything" in JavaScript is an object. Strings, Dates, Arrays, Functions. You can also create
your own objects.
This example creates an object called "person", and adds four properties to it:

<!DOCTYPE html> John is 50 years old.


<html>
<body>

<script>
var person=new Object();
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";
document.write(person.firstname + " is " + person.age +
" years old.");
</script>

</body>
</html>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Accessing Object Properties
The syntax for accessing the property of an object is:
objectName.propertyName
This example uses the length property of the String object to find the length of a string:
var message="Hello World!";
var x=message.length;

The value of x, after execution of the code above will be:


12

Accessing Object Methods


You can call a method with the following syntax:
objectName.methodName()

This example uses the toUpperCase() method of the String object, to convert a text to uppercase:
var message="Hello world!";
var x=message.toUpperCase();

The value of x, after execution of the code above will be:


HELLO WORLD!

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Tasks:

Q1. Create a webpage that declares a variable, assigns a value to it, displays the value, change
the value, and displays the value again and print the values on the webpage.
Code:

<html>
<head>
</html>
<body>
<script type=”text/javascript”>
document.write(“<h3ign=center>Lab Task 1.</h3>”);
var a;
a=10;
var b;
b=2;
document.write(“a = 10”);
document.write(“<br);
document.write(“b = 2”);
document.write(“<br);
document.write(“Sum = a+b”);
document.write(“<br);
Sum=a+b;
document.write(Sum);
document.write(“<br);
document.write(“Product = a*b”);
document.write(“<br);
document.write(Product=a*b);
document.write(“<br);
document.write(product);
</script>
</body>
</html>
Output:

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

Q2. Create a webpage that inputs the name of the user using prompt box, welcomes the user
when the page is loaded, tells the length of the name entered and convert the name to the
upper case.
Hint : to get input from user use the following:
var text = prompt('Enter your name ','Name' );
alert("Welcome "+ text);

code:
<html >

<head>

<title>lab5</title>

<script>

function askname()

var x;

var person=prompt(“Please enter your name”,”Name”);

if (person!=null)

x=”Welcome ” + person + “! How you doing?<br/>”;

document.write(x);

document.write(“The length of your name is: ” +person.length+”<br/>”);

document.write(“Name in upper case: “+person.toUpperCase());

</script>

</head>

<body>

<h1 >

My First JavaScript </h1>


Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
<p>Click the button to demonstrate the prompt box.</p>

<button onclick="askname()">Try it</button>

</body>

</html>

Q3. Create an object Employee which has the following properties, id, name, designation, salary,
phone number and city. Create a webpage that inputs the data and on clicking the submit
button display the data in a dialogue box.
Code:
<html>

<head>

<title>lab5task3</title>

<script>

function objectFunction(form)

var name=form.firstN.value;

var id=form.Id.value;

var salary=form.salary.value;

var ph=form.phone.value;

var city=form.city.value;

alert(“Employee Name: “+name+

“\nEmployee Id: “+id+

“\nEmployee Phone# : “+ph+

“\nEmployee City: “+city);

</script>

</head>

<body>
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
<h2 >

JavaScript objects using form</h2>

<table border=”0″ align=”center”>

<form >

<tr><td>Name:</td> <td><input name=”firstN” type=”text” /></td>

<tr><td>Id:</td> <td><input name=”Id” type=”text” /></td>

<tr><td>Salary:</td> <td><input name=”salary” type=”text” /></td>

<tr><td>Phone # :</td> <td><input name=”phone” type=”text” /></td>

<tr><td>City:</td> <td> <input name=”city” type=”text” /></td>

<tr><td><input type=”submit” onclick=”objectFunction(this.form)” value=”submit”/></td>

</form>

</table>

</body>

</html>

Note: Attach a snap shot of every above mentioned task.

Learning outcomes:

In this lab we have covered the scripting language used in HTML web pages which is JavaScript, this lab

have all basics of JavaScript language .

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

Lab # 06
JavaScript Part 2
Objective

 In this lab you will learn more about JavaScript.


 JS Function(functions with arguments and/or return values)
 JS variable, Data Types and Objects

Theory
Theory and background has already been discussed in Lab # 4 i.e. JavaScript Part 1.

JavaScript Functions
A function is a block of code that will be executed when "someone" calls it:.

JavaScript Function Syntax


Afunction is written as a code block(inside curly { } braces), preceded by the function keyword:

Syntax
Function functionName(parameters) {
   code to be executed
}

Declared functions are not executed immediately. They are "saved for later use", and will be
executed later, when they are invoked (called upon).
The function can be called directly when an event occurs (like when a user clicks a button), and
it can be called from "anywhere" by JavaScript code.

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("Hello World!");
}
</script>
</head>

<body>
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
<button onclick="myFunction()">Try it</button>
</body>
</html>

Calling a Function with Arguments


When you call a function, you can pass along some values to it, these values are
called arguments or parameters.
These arguments can be used inside the function.
You can send as many arguments as you like, separated by commas (,)

Function myFunction(argument1,argument2)

Declare the argument, as variables, when you declare the function:


function myFunction(var1,var2)
{
//some code
}

The variables and the arguments must be in the expected order. The first variable is given the
value of the first passed argument etc.

<!DOCTYPE html> Click the button to call a function with arguments


<html>
<body>

<p>Click the button to call a function with


arguments</p>

<button onclick="myFunction('Harry
Potter','Wizard')">Try it</button>

<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>

</body>
</html>

The function above will alert "Welcome Harry Potter, the Wizard" when the button is clicked.
Functions with a Return Value
Sometimes you want your function to return a value back to where the call was made. This is
possible by using the return statement. When using the return statement, the function will stop
executing, and return the specified value.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

Example
function myFunction()
{
var x=5;
return x;
}

The function above will return the value 5.


Note: It is not the entire JavaScript that will stop executing, only the function. JavaScript will
continue executing code, where the function-call was made from.
The function-call will be replaced with the returnvalue:

VarmyVar=myFunction();

The variable myVar holds the value 5, which is what the function "myFunction()" returns.
You can also use the returnvalue without storing it as a variable:

document.getElementById("demo").innerHTML=myFunction();

The innerHTML of the "demo" element will be 5, which is what the function "myFunction()"
returns.
You can make a returnvalue based on arguments passed into the function:
Calculate the product of two numbers, and return the result:

Example
<!DOCTYPE html> This example calls a function
<html> which performs a calculation, and
<body> returns the result:
12
<p>This example calls a function which performs a calculation, and
returns the result:</p>

<p id="demo"></p>

<script>
function myFunction(a,b)
{
return a*b;
}

document.getElementById("demo").innerHTML=myFunction(4,3);
</script>

</body>
</html>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

Local JavaScript Variables


 A variable declared (using var) within a JavaScript function becomes  LOCAL and can
only be accessed from within that function. (the variable has local scope).
 You can have local variables with the same name in different functions, because local
variables are only recognized by the function in which they are declared.
 Local variables are deleted as soon as the function is completed.

Global JavaScript Variables


Variables declared outside a function, become GLOBAL, and all scripts and functions on the
web page can access it.

The Lifetime of JavaScript Variables


 The lifetime JavaScript variables starts when they are declared.
 Local variables are deleted when the function is completed.
 Global variables are deleted when you close the page.

JavaScript Operators
Arithmetic Operators
Operator Description Example Result of x Result of y
+ Addition x=y+2 7 5
- Subtraction x=y-2 3 5
* Multiplication x=y*2 10 5
/ Division x=y/2 2.5 5
% Modulus (division remainder) x=y%2 1 5
++ Increment x=++y 6 6
x=y++ 5 6
-- Decrement x=--y 4 4
x=y-- 5 4

Assignment Operators
Operator Example Same As Result
= x=y x=5
+= x+=y x=x+y x=15
-= x-=y x=x-y x=5
*= x*=y x=x*y x=50
/= x/=y x=x/y x=2
%= x%=y x=x%y x=0

The + Operator Used on Strings


The + operator can also be used to add string variables or text values together.
<!DOCTYPE html> What a verynice day
<html>
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
<body>

<p>Click the button to create and add string variables.</p>


<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction()
{
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
document.getElementById("demo").innerHTML=txt3;
}
</script>

</body>
</html>

Adding Strings and Numbers


Adding two numbers, will return the sum, but adding a number and a string will return a string:
<!DOCTYPE html> 10
<html>
<body> 55
Hello5
<p>Click the button to add numbers and
strings.</p>
<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction()
{
var x=5+5;
var y="5"+5;
var z="Hello"+5;

vardemoP=document.getElementById("demo");
demoP.innerHTML=x + "<br>" + y + "<br>" + z;
}
</script>

</body>
</html>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
JavaScript Comparison and Logical Operators
Comparison Operators
Comparison operators are used in logical statements to determine equality or difference between
variables or values.
Given that x=5, the table below explains the comparison operators:
Operator Description Comparing Returns
== is equal to x==8 false
x==5 true
=== is exactly equal to (value and type) x==="5" false
x===5 true
!= is not equal x!=8 true
!== is not equal (neither value nor type) x!=="5" true
x!==5 false
> is greater than x>8 false
< is less than x<8 true
>= is greater than or equal to x>=8 false
<= is less than or equal to x<=8 true

How Can it be Used


Comparison operators can be used in conditional statements to compare values and take action
depending on the result:
if (age<18) x="Too young";

Logical Operators
Logical operators are used to determine the logic between variables or values. Given that  x=6
and y=3, the table below explains the logical operators:
Operator Description Example
&& AND (x < 10 && y > 1) is true
|| OR (x==5 || y==5) is false
! NOT !(x==y) is true

Conditional Operator
JavaScript also contains a conditional operator that assigns a value to a variable based on some
condition.

Syntax
variablename=(condition)?value1:value2

Example
If the variable age is a value below 18, the value of the variable voteable will be "Too young,
otherwise the value of voteable will be "Old enough":
voteable=(age<18)?"Too young":"Old enough";

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Conditional Statements
Very often when you write code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
 if statement - use this statement to execute some code only if a specified condition is true
 if...else statement - use this statement to execute some code if the condition is true and
another code if the condition is false
 if...else if....else statement - use this statement to select one of many blocks of code to be
executed
 switch statement - use this statement to select one of many blocks of code to be executed

If Statement
Use the if statement to execute some code only if a specified condition is true.
Syntax
if (condition)
 {
  code to be executed if condition is true
 }

Note that if is written in lowercase letters. Using uppercase letters (IF) will generate a JavaScript
error!
Example
Make a "Good day" greeting if the time is less than 20:00:
if (time<20)
  {
  x="Good day";
  }
The result of x will be:
Good day

Notice that there is no ..else.. in this syntax. You tell the browser to execute some code only if
the specified condition is true.
If...else Statement
Use the if....else statement to execute some code if a condition is true and another code if the
condition is not true.
Syntax
if (condition)
 {
  code to be executed if condition is true
 }
else
 {
  code to be executed if condition is not true

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
 }

Example
If the time is less than 20:00, you will get a "Good day" greeting, otherwise you will get a "Good evening"
greeting
if (time<20)
  {
  x="Good day";
  }
else
  {
  x="Good evening";
  }
The result of x will be:
Good day

If...else if...else Statement


Use the if....else if...else statement to select one of several blocks of code to be executed.

Syntax
if (condition1)
 {
  code to be executed if condition1 is true
 }
else if (condition2)
 {
  code to be executed if condition2 is true
 }
else
 {
  code to be executed if neither condition1 nor condition2 is true
 }

Example
If the time is less than 10:00, you will get a "Good morning" greeting, if not, but the time is less than
20:00, you will get a "Good day" greeting, otherwise you will get a "Good evening" greeting:
if (time<10)
  {
  x="Good morning";
  }
else if (time<20)
  {
  x="Good day";
  }
else
  {
  x="Good evening";
  }
The result of x will be:
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Good morning

The JavaScript Switch Statement


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

Syntax
switch(n)
{
case 1:
  execute code block 1
  break;
case 2:
  execute code block 2
  break;
default:
  code to be executed if n is different from case 1 and 2
}
This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case in the
structure. If there is a match, the block of code associated with that case is executed.
Use break to prevent the code from running into the next case automatically.

Example
Display today's weekday-name. Note that Sunday=0, Monday=1, Tuesday=2, etc:
var day=new Date().getDay();
switch (day)
{
case 0:
  x="Today it's Sunday";
  break;
case 1:
  x="Today it's Monday";
  break;
case 2:
  x="Today it's Tuesday";
  break;
case 3:
  x="Today it's Wednesday";
  break;
case 4:
  x="Today it's Thursday";
  break;
case 5:
  x="Today it's Friday";
  break;
case 6:
  x="Today it's Saturday";
  break;

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
}
The result of x will be:
Today it's Monday

The default Keyword
Use the default keyword to specify what to do if there is no match:
Example
If it is NOT Saturday or Sunday, then write a default message:
var day=new Date().getDay();
switch (day)
{
case 6:
  x="Today it's Saturday";
  break;
case 0:
  x="Today it's Sunday";
  break;
default:
  x="Looking forward to the Weekend";
}
The result of x will be:
Looking forward to the Weekend

JavaScript For Loop
Loops can execute a block of code a number of times.

JavaScript Loops
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:
Instead of writing:
document.write(cars[0] + "<br>"); 
document.write(cars[1] + "<br>"); 
document.write(cars[2] + "<br>"); 
document.write(cars[3] + "<br>"); 
document.write(cars[4] + "<br>"); 
document.write(cars[5] + "<br>");

You can write:


for (vari=0;i<cars.length;i++)

document.write(cars[i] + "<br>");
}

Different Kinds of Loops


JavaScript supports different kinds of loops:

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
 for - loops through a block of code a number of times
 for/in - loops through the properties of an object
 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 is often the tool you will use when you want to create a loop.
The for loop has the following syntax:
for (statement 1; statement 2; statement 3)
 {
  the code block to be executed
 }

Statement 1 is executed before the loop (the code block) starts.
Statement 2 defines the condition for running the loop (the code block).
Statement 3 is executed each time after the loop (the code block) has been executed.

Example
for (vari=0; i<5; i++)
 {
  x=x + "The number is " + i + "<br>";
 }
From the example above, you can read:
Statement 1 sets a variable before the loop starts (vari=0).
Statement 2 defines the condition for the loop to run (i must be less than 5).
Statement 3 increases a value (i++) each time the code block in the loop has been executed.

Statement 1
Normally you will use statement 1 to initiate the variable used in the loop (vari=0). This is not
always the case, JavaScript doesn't care, and statement 1 is optional. You can initiate any (or
many) values in statement 1:

Example:
for (vari=0,len=cars.length; i<len; i++)

document.write(cars[i] + "<br>");
}

And you can omit statement 1 (like when your values are set before the loop starts):
Example:
vari=2,len=cars.length;
for (; i<len; i++)

document.write(cars[i] + "<br>");
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
}

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, and statement 2 is optional.
If statement 2 returns true, the loop will start over again, if it returns false, the loop will end.

Statement 3
Often statement 3 increases the initial variable. This is not always the case, JavaScript doesn't
care, and statement 3 is optional. Statement 3 could do anything. The increment could be
negative (i--), or larger (i=i+15). Statement 3 can also be omitted (like when you have
corresponding code inside the loop):

Example:
vari=0,len=cars.length;
for (; i<len; )

document.write(cars[i] + "<br>");
i++;
}

The For/In Loop


The JavaScript for/in statement loops through the properties of an object:
Example
var person={fname:"John",lname:"Doe",age:25}; 

for (x in person)
 {
  txt=txt + person[x];
 }

JavaScript While Loop
Loops can execute a block of code as long as a specified condition is true.
The While Loop
The while loop loops through a block of code as long as a specified condition is true.
Syntax
while (condition)
 {
  code block to be executed
 }

Example
The loop in this example will continue to run as long as the variable i is less than 5:
while (i<5)

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
 {
  x=x + "The number is " + i + "<br>";
  i++;
 }

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
 {
  code block to be executed
  }
while (condition);

Example
The example below uses a do/while loop. The loop will always be executed at least once, even if
the condition is false, because the code block is executed before the condition is tested:
do
 {
  x=x + "The number is " + i + "<br>";
  i++;
 }
while (i<5);
Do not forget to increase the variable used in the condition, otherwise the loop will never end!

Comparing For and While


If you have read the previous chapter, about the for loop, you will discover that a while loop is
much the same as a for loop, with statement 1 and statement 3 omitted.
The loop in this example uses a for loop to display all the values in the cars array:
Example
cars=["BMW","Volvo","Saab","Ford"];
vari=0;
for (;cars[i];)
{
document.write(cars[i] + "<br>");
i++;
}

The loop in this example uses a while loop to display all the values in the cars array:

Example
cars=["BMW","Volvo","Saab","Ford"];
vari=0;

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
while (cars[i])
{
document.write(cars[i] + "<br>");
i++;
}

JavaScript Break and Continue


 The break statement "jumps out" of a loop.
 The continue statement "jumps over" one iteration in the loop.

The Break Statement


You have already seen the break statement used in an earlier chapter of this tutorial. It was used
to "jump out" of a switch() statement.
The break statement can also be used to jump out of a loop.  
The break statement breaks the loop and continues executing the code after the loop (if any):

Example
for (i=0;i<10;i++)
 {
  if (i==3)
    {
    break;
    }
  x=x + "The number is " + i + "<br>";
 }
Since the if statement has only one single line of code, the braces can be omitted:
for (i=0;i<10;i++)
 {
  if (i==3) break;
  x=x + "The number is " + i + "<br>";
 }

The Continue Statement


The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.
This example skips the value of 3:
Example
for (i=0;i<=10;i++)
 {
 if (i==3) continue;
  x=x + "The number is " + i + "<br>";
 }

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Exercise
1. Write a JavaScript program to find the perimeter of a triangle where lengths of the three
of its sides are provided by user at run time. (Hint: Perimeter = side A + side B + side
C).
Code:
<html>

<head>

<script>

const side1 = parseInt(prompt('Enter sideA: '));

const side2 = parseInt(prompt('Enter sideB: '));

const side3 = parseInt(prompt('Enter sideC: '));

// calculate the semi-perimeter

const s = (sideA + sideB + sideC) ;

document.write(s);

//calculate the area

</script>

</head>

<body>

<h2>Perimeter of a triangle</h2>

</body>

</html>

2. Write a java script program that takes input from user in web page, and prompt the result
about the number being even or odd.
CODE:

<html>

<head>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
<script>

const number = prompt("Enter a number: ");

if(number % 2 == 0) {

document.write("The number is even.");

// if the number is odd

else {

document.write("The number is odd.");

</script>

</head>

<body>

</body>

</html>

3. Write a program in javascript that takes two numbers and one operator(operator to be
selected from ddl) in webpage from user, add a button to perform that basic arithmetic
operation on those numbers.
Code:

<html>

<head>

<script>

function ADD()

var num1 = document.getElementById("firstNumber").value;

var num2 = document.getElementById("secondNumber").value;

var ddlOperator = document.getElementById("ddlOperator").value;

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
let x;

if (ddlOperator.value == "") {

alert("Please select an option!");

else if(ddlOperator.value==1)

x=num1+num2;

else if(ddlOperator.value==2)

x=num1-num2;

else if(ddlOperator.value==3)

x=num1*num2;

else if(ddlOperator.value==4)

x=num1/num2;

else{

x=null;

document.getElementById("result").innerHTML = x;

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
}

</script>

</head>

<body>

<body>

<form>

1st Number : <input type="text" id="firstNumber" /><br>

2nd Number: <input type="text" id="secondNumber" /><br>

Select operator:

<select id="ddlOperator">

<option value=""></option>

<option value="1">Addition</option>

<option value="2">Subtraction</option>

<option value="3">Multiplication</option>

<option value="3">Division</option>

</select>

<input type="submit" value="Submit" onclick=" ADD()" />

</form>

<p>The Result is : <br>

<span id = "result"></span>

</p>

</body>

</html>

</body>

</html>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
4. Create a webpage that is used to fill the application form of some specific job. There
should be some mendatory fields such as Name, CNIC number, email address etc, and
check its validation using JavaScript.
Code:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Simple HTML Form</title>

<link rel="stylesheet" href="style.css">

<script src="validator.js"></script>

</head>

<body>

<form name="contactForm" onsubmit="return validateForm()" action="confirmation.php"


method="post">

<h2>Application Form</h2>

<div class="row">

<label>Full Name</label>

<input type="text" name="name">

<div class="error" id="nameErr"></div>

</div>

<div class="row">

<label>Email Address</label>

<input type="text" name="email">

<div class="error" id="emailErr"></div>

</div>

<div class="row">

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
<label>Mobile Number</label>

<input type="text" name="mobile" maxlength="10">

<div class="error" id="mobileErr"></div>

</div>

<div class="row">

<label>Country</label>

<select name="country">

<option>Select</option>

<option>Australia</option>

<option>India</option>

<option>United States</option>

<option>United Kingdom</option>

</select>

<div class="error" id="countryErr"></div>

</div>

<div class="row">

<label>Gender</label>

<div class="form-inline">

<label><input type="radio" name="gender" value="male"> Male</label>

<label><input type="radio" name="gender" value="female"> Female</label>

</div>

<div class="error" id="genderErr"></div>

</div>

<div class="row">

<label>Hobbies <i>(Optional)</i></label>

<div class="form-inline">
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
<label><input type="checkbox" name="hobbies[]" value="sports"> Sports</label>

<label><input type="checkbox" name="hobbies[]" value="movies"> Movies</label>

<label><input type="checkbox" name="hobbies[]" value="music"> Music</label>

</div>

</div>

<div class="row">

<input type="submit" value="Submit">

</div>

</form>

</body>

</html>

JAVASCRIPT CODE:

// Defining a function to display error message

function printError(elemId, hintMsg) {

document.getElementById(elemId).innerHTML = hintMsg;

// Defining a function to validate form

function validateForm() {

// Retrieving the values of form elements

var name = document.contactForm.name.value;

var email = document.contactForm.email.value;

var mobile = document.contactForm.mobile.value;

var country = document.contactForm.country.value;

var gender = document.contactForm.gender.value;

var hobbies = [];

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
var checkboxes = document.getElementsByName("hobbies[]");

for(var i=0; i < checkboxes.length; i++) {

if(checkboxes[i].checked) {

// Populate hobbies array with selected values

hobbies.push(checkboxes[i].value);

// Defining error variables with a default value

var nameErr = emailErr = mobileErr = countryErr = genderErr = true;

// Validate name

if(name == "") {

printError("nameErr", "Please enter your name");

} else {

var regex = /^[a-zA-Z\s]+$/;

if(regex.test(name) === false) {

printError("nameErr", "Please enter a valid name");

} else {

printError("nameErr", "");

nameErr = false;

// Validate email address

if(email == "") {

printError("emailErr", "Please enter your email address");


Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
} else {

// Regular expression for basic email validation

var regex = /^\S+@\S+\.\S+$/;

if(regex.test(email) === false) {

printError("emailErr", "Please enter a valid email address");

} else{

printError("emailErr", "");

emailErr = false;

// Validate mobile number

if(mobile == "") {

printError("mobileErr", "Please enter your mobile number");

} else {

var regex = /^[1-9]\d{9}$/;

if(regex.test(mobile) === false) {

printError("mobileErr", "Please enter a valid 10 digit mobile number");

} else{

printError("mobileErr", "");

mobileErr = false;

// Validate country

if(country == "Select") {

printError("countryErr", "Please select your country");


Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
} else {

printError("countryErr", "");

countryErr = false;

// Validate gender

if(gender == "") {

printError("genderErr", "Please select your gender");

} else {

printError("genderErr", "");

genderErr = false;

// Prevent the form from being submitted if there are any errors

if((nameErr || emailErr || mobileErr || countryErr || genderErr) == true) {

return false;

} else {

// Creating a string from input data for preview

var dataPreview = "You've entered the following details: \n" +

"Full Name: " + name + "\n" +

"Email Address: " + email + "\n" +

"Mobile Number: " + mobile + "\n" +

"Country: " + country + "\n" +

"Gender: " + gender + "\n";

if(hobbies.length) {

dataPreview += "Hobbies: " + hobbies.join(", ");

}
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
// Display input data in a dialog box before submitting the form

alert(dataPreview);

};

Note: Attach a snap shot of every above mentioned task.

Learning outcomes:

This lab have covered the JavaScript Functions programming and JavaScript calling functions

programming and how to make JavaScript syntaxes.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Lab # 07
JavaScript Part 3
DOM

Objective

 In this lab you will learn more about JavaScript.


 Document Object Model
 Finding HTML Elements
 Manipulating HTML elements

Theory
Theory and background has already been discussed in JavaScript Part 1 and 2.

Document Object Model


Every web page resides inside a browser window which can be considered as an object.
A Document object represents the HTML document that is displayed in that window. The
Document object has various properties that refer to other objects which allow access to and
modification of document content.
The way a document content is accessed and modified is called the Document Object Model,
or DOM. The Objects are organized in a hierarchy. This hierarchical structure applies to the
organization of objects in a Web document.
 Window object − Top of the hierarchy. It is the outmost element of the object hierarchy.
 Document object − Each HTML document that gets loaded into a window becomes a
document object. The document contains the contents of the page.
 Form object − Everything enclosed in the <form>...</form> tags sets the form object.
 Form control elements − The form object contains all the elements defined for that
object such as text fields, buttons, radio buttons, and checkboxes.

DOM standard is separated into 3 different parts:


 Core DOM - standard model for all document types
 XML DOM - standard model for XML documents
 HTML DOM - standard model for HTML documents

The HTML DOM (Document Object Model)


The HTML DOM is a standard object model and programming interface for HTML. It defines:
 The HTML elements as objects
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
 The properties of all HTML elements
 The methods to access all HTML elements
 The events for all HTML elements
In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML
elements.

When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects:

With a programmable object model, JavaScript gets all the power it needs to create dynamic
HTML:
 JavaScript can change all the HTML elements in the page
 JavaScript can change all the HTML attributes in the page
 JavaScript can change all the CSS styles in the page
 JavaScript can react to all the events in the page

Finding HTML Elements


Often, with JavaScript, you want to manipulate HTML elements. To do so, you have to find the
elements first. There are a couple of ways to do this:
 Finding HTML elements by id
 Finding HTML elements by tag name
 Finding HTML elements by class name

Finding HTML Elements by Id


The easiest way to find HTML elements in the DOM, is by using the element id. This example
finds the element with id="intro":
<!DOCTYPE html> Hello World!
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
<html> This example demonstrates
<body> the getElementById method!
The text from the intro paragraph: Hello
<p id="intro">Hello World!</p> World!
<p>This example demonstrates the
<b>getElementById</b>method!</p>

<script>
x=document.getElementById("intro");
document.write("<p>The text from the intro
paragraph: " + x.innerHTML + "</p>");
</script>

</body>
</html>

Finding HTML Elements by Tag Name


This example finds the element with id="main", and then finds all <p> elements inside "main":
<!DOCTYPE html> Hello World!
<html> The DOM is very useful.
<body> This example demonstrates
the getElementsByTagName method
<p>Hello World!</p> First paragraph inside "main" is The DOM is
very useful.
<div id="main">
<p>The DOM is very useful.</p>
<p>This example demonstrates the
<b>getElementsByTagName</b> method</p>
</div>
<script>
var x=document.getElementById("main");
var y=x.getElementsByTagName("p");
document.write('First paragraph inside "main"
is ' + y[0].innerHTML);
</script>

</body>
</html>
DOM HTML:
Changing the HTML Output Stream
JavaScript can create dynamic HTML content:
In JavaScript, document.write() can be used to write directly to the HTML output stream:
<!DOCTYPE html> Sun Mar 17 2013 21:16:29 GMT+0500

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
<html> (Pakistan Standard Time)
<body>

<script>
document.write(Date());
</script>

</body>
</html>

Changing HTML Content


The easiest way to modify the content of an HTML element is by using
the innerHTML property. To change the content of an HTML element, use this syntax:

document.getElementById(id).innerHTML=new HTML

This example changes the content of a <p> element:


<!DOCTYPE html> New text!
<html> The paragraph above was changed by a
<body> script.

<p id="p1">Hello World!</p>

<script>
document.getElementById("p1").innerHTML="Ne
w text!";
</script>

<p>The paragraph above was changed by a


script.</p>

</body>
</html>

This example changes the content of an <h1> element:

<!DOCTYPE html> New Header


<html> "Old Header" was changed to "New Header"
<body>

<h1 id="header">Old Header</h1>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
<script>
var
element=document.getElementById("header");
element.innerHTML="New Header";
</script>

<p>"Old Header" was changed to "New


Header"</p>

</body>
</html>
Example explained:
 The HTML document above contains an <h1> element with id="header"
 We use the HTML DOM to get the element with id="header"
 A JavaScript changes the content (innerHTML) of that element

Changing an HTML Attribute


To change the attribute of an HTML element, use this syntax:
document.getElementById(id).attribute=new value

This example changes the src attribute of an <img> element:


<!DOCTYPE html>
<html>
<body>

<img id="image" src="smiley.gif" width="160"


height="120">

<script> The original image was smiley.gif,


document.getElementById("image").src="landscape.jpg"; but the script changed it to
</script> landscape.jpg

<p>The original image was smiley.gif, but the script


changed it to landscape.jpg</p>

</body>
</html>

Example explained:
 The HTML document above contains an <img> element with id="image"
 We use the HTML DOM to get the element with id="image"

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
 A JavaScript changes the src attribute of that element from "smiley.gif" to
"landscape.jpg"
DOM CSS:
Changing HTML Style
To change the style of an HTML element, use this syntax:
document.getElementById(id).style.property=new style

The following example changes the style of a <p> element:


<!DOCTYPE html> Hello World!
<html> Hello World!
<body> The paragraph above was changed
by a script.
<p id="p1">Hello World!</p>
<p id="p2">Hello World!</p>

<script>
document.getElementById("p2").style.color="blue";
document.getElementById("p2").style.fontFamily="Arial"
;
document.getElementById("p2").style.fontSize="larger";
</script>

<p>The paragraph above was changed by a script.</p>

</body>
</html>

This example changes the style of the HTML element with id="id1", when the user clicks a
button:
<!DOCTYPE html> My Heading 1
<html>
<body> after click
My Heading 1
<h1 id="id1">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color='red'">
Click Me!</button>

</body>
</html>

JavaScript HTML DOM


HTML DOM allows JavaScript to react to HTML events.
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Reacting to Events
A JavaScript can be executed when an event occurs, like when a user clicks on an HTML
element.
To execute code when a user clicks on an element, add JavaScript code to an HTML event
attribute:
onclick=JavaScript

Examples of HTML events:


 When a user clicks the mouse
 When a web page has loaded
 When an image has been loaded
 When the mouse moves over an element
 When an input field is changed
 When an HTML form is submitted
 When a user strikes a key

In this example, the content of the <h1> element is changed when a user clicks on it:
<!DOCTYPE html>
<html>
<body>
<h1 onclick="this.innerHTML='Ooops!'">Click on this text!</h1>
</body>
</html>

In this example, a function is called from the event handler:


<!DOCTYPE html>
<html>
<head>
<script>
function changetext(id)
{
id.innerHTML="Ooops!";
}
</script>
</head>
<body>
<h1 onclick="changetext(para1)">Click on this text!</h1>
<p id="para1">para 1</p>
</body>
</html>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
HTML Event Attributes
To assign events to HTML elements you can use event attributes.
<button onclick="displayDate()">Try it</button>

Assign Events Using the HTML DOM


The HTML DOM allows you to assign events to HTML elements using JavaScript:
Assign an onclick event to a button element:
<script>
document.getElementById("myBtn").onclick=function(){displayDate()};
</script>

Mouse Events
Property Description
onclick The event occurs when the user clicks on an element
ondblclick The event occurs when the user double-clicks on an element
onmousedown The event occurs when a user presses a mouse button over an element
onmousemove The event occurs when the pointer is moving while it is over an element
onmouseover The event occurs when the pointer is moved onto an element
onmouseout The event occurs when a user moves the mouse pointer out of an element
onmouseup The event occurs when a user releases a mouse button over an element

Keyboard Events
Attribute Description
onkeydown The event occurs when the user is pressing a key
onkeypress The event occurs when the user presses a key
onkeyup The event occurs when the user releases a key

Frame/Object Events
Attribute Description
onabort The event occurs when an image is stopped from loading before completely
loaded (for <object>)
onerror The event occurs when an image does not load properly (for <object>, <body>
and <frameset>)
onload The event occurs when a document, frameset, or <object> has been loaded
onresize The event occurs when a document view is resized
onscroll The event occurs when a document view is scrolled
onunload The event occurs once a page has unloaded (for <body> and <frameset>)

Form Events
Attribute Description
onblur The event occurs when a form element loses focus

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
onchange The event occurs when the content of a form element, the selection, or the
checked state have changed (for <input>, <select>, and <textarea>)
onfocus The event occurs when an element gets focus (for <label>, <input>, <select>,
textarea>, and <button>)
onreset The event occurs when a form is reset
onselect The event occurs when a user selects some  text (for <input> and <textarea>)
onsubmit The event occurs when a form is submitted

Event Object
Constants
Constant Description
CAPTURING_PHASE The current event phase is the capture phase (3)
AT_TARGET The current event is in the target phase, i.e. it is being evaluated at the event
target (1)
BUBBLING_PHASE The current event phase is the bubbling phase (2)

Properties
Property Description
bubbles Returns whether or not an event is a bubbling event
cancelable Returns whether or not an event can have its default action prevented
currentTarget Returns the element whose event listeners triggered the event
eventPhase Returns which phase of the event flow is currently being evaluated
target Returns the element that triggered the event
timeStamp Returns the time (in milliseconds relative to the epoch) at which the event was
created
type Returns the name of the event

Methods
Method Description
initEvent() Specifies the event type, whether or not the event can bubble, whether or not the
event's default action can be prevented
preventDefault() To cancel the event if it is cancelable, meaning that any default action normally
taken by the implementation as a result of the event will not occur
stopPropagation() To prevent further propagation of an event during event flow

EventTarget Object
Methods
Method Description
addEventListener() Allows the registration of event listeners on the event target (IE8 =
attachEvent())
dispatchEvent() Allows to send the event to the subscribed event listeners (IE8 = fireEvent())
removeEventListener() Allows the removal of event listeners on the event target (IE8 =

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
detachEvent())
EventListener Object
Methods
Method Description
handleEvent() Called whenever an event occurs of the event type for which the EventListener
interface was registered

DocumentEvent Object
Methods
Method Description
createEvent()

MouseEvent/KeyboardEvent Object
Properties
Property Description
altKey Returns whether or not the "ALT" key was pressed when an event was triggered
button Returns which mouse button was clicked when an event was triggered
clientX Returns the horizontal coordinate of the mouse pointer, relative to the current
window, when an event was triggered
clientY Returns the vertical coordinate of the mouse pointer, relative to the current
window, when an event was triggered
ctrlKey Returns whether or not the "CTRL" key was pressed when an event was
triggered
keyIdentifier Returns the identifier of a key
keyLocation Returns the location of the key on the advice
metaKey Returns whether or not the "meta" key was pressed when an event was triggered
relatedTarget Returns the element related to the element that triggered the event
screenX Returns the horizontal coordinate of the mouse pointer, relative to the screen,
when an event was triggered
screenY Returns the vertical coordinate of the mouse pointer, relative to the screen, when
an event was triggered
shiftKey Returns whether or not the "SHIFT" key was pressed when an event was
triggered
Methods
Method Description
initMouseEvent() Initializes the value of a MouseEvent object
initKeyboardEvent( Initializes the value of a KeyboardEvent object
)

Tasks:

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Q1. Create a webpage of your choice, when the page loads a message box that should display the URL
and the title of the webpage.

Q2. Create a webpage of your choice, when the page loads a message box should display the date when
the webpage was last modified.

Q3. Create a web page that returns the mouse button pressed information.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

Q4. Create a webpage that returns the coordinates of the mouse cursor.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

Note: Attach a snap shot of every above mentioned task.

Learning outcomes:
This lab is about more of JavaScript DOM Document Object Model, how to find elements in HTML and
how to manipulate HTML elements

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Lab # 08

Introduction to PHP
Objective

 In this lab you will learn the basic concepts of PHP.

Theory
What is PHP?
 PHP stands 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

How PHP Works


PHP is generally used as a server-side scripting language; it is especially well-suited for creating dynamic
web pages. The scripting language features integrated support for interfacing with databases such
asMySQL, which makes it a prime candidate for building all manner of web applications, from simple
personal web sites to complex enterprise-level applications.
Unlike HTML, which is parsed by a browser when a page loads, PHP is preprocessed by the machine that
serves the document (this machine is referred to as a server). All PHP code contained with the document
is processed by the server before the document is sent to the visitor’s browser.
PHP is a scripted language, which is another great advantage for PHP programmers. Many programming
languages require that you compile files into machine code before they can be run, which is a time-
consuming process. Bypassing the need to compile means you’re able to edit and test code much more
quickly.
Because PHP is a server-side language, running PHP scripts on your local machine requires installing a
server on your local machine, as well. The examples in this book rely on the Apache web server to deliver
your web pages.

Server-Side vs. Client-Side Scripting


The Internet features two main kinds of scripting: server-side and client-side. Client-side scripting is
comprised mainly of JavaScript, which is responsible for many of the web features that you can actually
see happening, such as pop-up windows, some animations, and other site features like drop-down menus.
The r eason this is called “client-side” scripting because the code is executed on the user’s machine, after
the page has been loaded.

What is a PHP File?


 PHP files can contain text, HTML, JavaScript code, and PHP code

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
 PHP code are executed on the server, and the result is returned to the browser as plain
HTML
 PHP files have a default file extension of ".php"

What Can PHP Do?


 PHP can generate dynamic page content
 PHP can create, open, read, write, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can restrict users to access some pages on your website
 PHP can encrypt data
 With PHP you are not limited to output HTML. You can output images, PDF files, and
even Flash movies. You can also output any text, such as XHTML and XML.

Why PHP?
 PHP runs on different platforms (Windows, Linux, Unix, Mac OS X, etc.)
 PHP is compatible with almost all servers used today (Apache, IIS, etc.)
 PHP has support for a wide range of databases
 PHP is easy to learn and runs efficiently on the server side

What Do You Need?


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.

Use a Web Host with PHP Support


 If your server has activated support for PHP you do not need to do anything.
 Just create some .php files, place them in your web directory, and the server will
automatically parse them for you.
 You do not need to compile anything or install any extra tools.
 Because PHP is free, most web hosts offer PHP support.

Set Up PHP on Your Own PC


 However, if your server does not support PHP, you must:
 install a web server

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
 install PHP
 install a database, such as MySQL

Basic PHP Syntax


A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>:
<?php
// PHP code goes here
?>
The default file extension for PHP files is ".php".
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that sends the text "Hello World!"
back to the browser:
<!DOCTYPE html> My first PHP page
<html> Hello World!
<body>

<h1>My first PHP page</h1>

<?php
echo "Hello World!";
?>  

</body>
</html>
Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish
one set of instructions from another.
With PHP, there are two basic statements to output text in the browser: echo and print.
Comments in PHP
Example
<!DOCTYPE html>
<html>
<body>

<?php
//This is a PHP comment line

/*
This is
a PHP comment
block
*/
?>
</body>
</html>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
PHP Variables
As with algebra, PHP variables can be used to hold values (x=5) or expressions (z=x+y).
Variable can have short names (like x and y) or more descriptive names (age, carname, totalvolume).
Rules for PHP variables:
 A variable starts with the $ sign, followed by the name of the variable
 A variable name must begin with a letter or the underscore character
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
 A variable name should not contain spaces
 Variable names are case sensitive ($y and $Y are two different variables)

Creating (Declaring) PHP Variables


PHP has no command for declaring a variable.
A variable is created the moment you first assign a value to it:
$txt="Hello world!";
$x=5;
After the execution of the statements above, the variable txt will hold the value Hello world!, and the
variable xwill hold the value 5.
Note: When you assign a text value to a variable, put quotes around the value.

PHP is a Loosely Typed Language


In the example above, notice that we did not have to tell PHP which data type the variable is.
PHP automatically converts the variable to the correct data type, depending on its value.
In a strongly typed programming language, we will have to declare (define) the type and name of
the variable before using it.

PHP Variable Scopes


The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has four different variable scopes:
 local
 global
 static
 parameter
Local Scope
A variable declared within a PHP function is local and can only be accessed within that function:
Example
<?php
$x=5; // global scope

function myTest()
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
{
echo $x; // local scope
}

myTest();
?>

The script above will not produce any output because the echo statement refers to the local scope variable
$x, which has not been assigned a value within this scope.
You can have local variables with the same name in different functions, because local variables are only
recognized by the function in which they are declared.
Local variables are deleted as soon as the function is completed.

Global Scope
A variable that is defined outside of any function has a global scope.
Global variables can be accessed from any part of the script, EXCEPT from within a function.
To access a global variable from within a function, use the global keyword:
Example
<?php
$x=5; // global scope
$y=10; // global scope

function myTest()
{
global $x,$y;
$y=$x+$y;
}

myTest();
echo $y; // outputs 15
?>

PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name of
the variable. This array is also accessible from within functions and can be used to update global variables
directly.
The example above can be rewritten like this:
Example
<?php
$x=5;
$y=10;

function myTest()
{
$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y'];

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
myTest();
echo $y;
?>

Static Scope
When a function is completed, all of its variables are normally deleted. However, sometimes you want a
local variable to not be deleted.
To do this, use the static keyword when you first declare the variable:
Example
<?php

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

myTest();
myTest();
myTest();

?>

Then, each time the function is called, that variable will still have the information it contained from the
last time the function was called.
Note: The variable is still local to the function.
Parameter Scope
A parameter is a local variable whose value is passed to the function by the calling code.
Parameters are declared in a parameter list as part of the function declaration:
Example
<?php

function myTest($x)
{
echo $x;
}

myTest(5);
?>

Parameters are also called arguments.

String Variables in PHP


String variables are used for values that contain characters.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
After we have created a string variable we can manipulate it. A string can be used directly in a function or
it can be stored in a variable.
In the example below, we create a string variable called txt, then we assign the text "Hello world!" to it.
Then we write the value of the txt variable to the output:
<!DOCTYPE html> Hello world!
<html>
<body>

<?php
$txt="Hello world!";
echo $txt;
?>

</body>
</html>

The PHP Concatenation Operator


There is only one string operator in PHP.
The concatenation operator (.)  is used to join two string values together.
The example below shows how to concatenate two string variables together:
<!DOCTYPE html> Hello world! What a nice day!
<html>
<body>

<?php
$txt1="Hello world!";
$txt2="What a nice day!";
echo $txt1 . " " . $txt2;
?>  
  
</body>
</html>
The PHP strlen() function
Sometimes it is useful to know the length of a string value.The strlen() function returns the length of a
string, in characters.The example below returns the length of the string "Hello world!":
<!DOCTYPE html> 12
<html>
<body>

<?php
echo strlen("Hello world!");
?>  
  
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
</body>
</html>

The PHP strpos() function


The strpos() function is used to search for a character or a specific text within a string.
If a match is found, it will return the character position of the first match. If no match is found, it will
return FALSE.
The example below searches for the text "world" in the string "Hello world!":
<!DOCTYPE html> 6
<html>
<body>

<?php
echo strpos("Hello
world!","world");
?>  
  
</body>
</html>

PHP Operators
The assignment operator = is used to assign values to variables in PHP.
The arithmetic operator + is used to add values together in PHP.

PHP Arithmetic Operators


Operato
Name Description Example Result
r
x+y Addition Sum of x and y 2+2 4
x-y Subtraction Difference of x and y 5-2 3
x*y Multiplication Product of x and y 5*2 10
x/y Division Quotient of x and y 15 / 5 3
5 % 2 1
Remainder of x divided by
x%y Modulus 10 % 8 2
y
10 % 2 0
-x Negation Opposite of x -2
a.b Concatenation Concatenate two strings "Hi" . "Ha" HiHa

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
PHP Assignment Operators
The basic assignment operator in PHP is "=". It means that the left operand gets set to the value
of the expression on the right. That is, the value of "$x = 5" is 5.
Assignmen
Same as... Description
t
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
a .= b a=a.b Concatenate two strings

PHP Incrementing/Decrementing Operators


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
x -- Post-decrement Returns x, then decrements x by one
PHP Comparison Operators
Comparison operators allows you to compare two values:
Operato Name Description Example
r
x == y Equal True if x is equal to y 5==8 returns false
x === y Identical True if x is equal to y, and they are of same type 5==="5" returns false
x != y Not equal True if x is not equal to y 5!=8 returns true
x <> y Not equal True if x is not equal to y 5<>8 returns true
x !== y Not identical True if x is not equal to y, or they are not of same type 5!=="5" returns true
x>y Greater than True if x is greater than y 5>8 returns false
x<y Less than True if x is less than y 5<8 returns true
x >= y Greater than or equal to True if x is greater than or equal to y 5>=8 returns false
x <= y Less than or equal to True if x is less than or equal to y 5<=8 returns true
PHP Logical Operators
Operator Name Description Example
x=6
x and y And True if both x and y are true y=3 
(x < 10 and y > 1) returns true
x=6
x or y Or True if either or both x and y are true y=3 
(x==6 or y==5) returns true
x=6
True if either x or y is true, but not
x xor y Xor y=3 
both
(x==6 xor y==3) returns false
x=6
x && y And True if both x and y are true y=3
(x < 10 && y > 1) returns true
x=6
x || y Or True if either or both x and y are true y=3
(x==5 || y==5) returns false
!x Not True if x is not true x=6
y=3

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
!(x==y) returns true
PHP Array Operators
Operator Name Description
x+y Union Union of x and y
x == y Equality True if x and y have the same key/value pairs
True if x and y have the same key/value pairs in the same order and are of the same
x === y Identity
type
x != y Inequality True if x is not equal to y
x <> y Inequality True if x is not equal to y
x !== y Non-identity True if x is not identical to y

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Tasks:

Q1. Write the php code that declares a variable and prints their value on the webpage.

Q2. Write a php code that creates two string variables and perform the following and show the result on
the webpage
a. Length of the string
b. Concatenates the string
c. Find the position of letter ‘a’ in both the strings

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Q3. Write a php code that creates two global variables and access them in a function ‘sum’ using global
array.

Note: Attach a snap shot of every above mentioned task.

Learning outcomes:

Upon the completion of this lab we have learnt the basics of PHP language and how to use PHP in Web

Pages is covered in this lab.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Lab # 09
Programming with PHP
Objective

 In this lab you will learn how to program using php.


 XMLHttpRequest Object Methods & properties

Theory
PHP If...Else Statements
Conditional statements are used to perform different actions based on different conditions.
PHP Conditional Statements
Very often when you write code, you want to perform different actions for different decisions. You can
use conditional statements in your code to do this.
In PHP we have the following conditional statements:
 if statement - executes some code only if a specified condition is true
 if...else statement - executes some code if a condition is true and another code if the
condition is false
 if...else if....else statement - selects one of several blocks of code to be executed
 switch statement - selects one of many blocks of code to be executed
PHP - The if Statement
The if statement is used to execute some code only if a specified condition is true.
Syntax
if (condition)
 {
  code to be executed if condition is true;
  }
<!DOCTYPE html> Have a good day!
<html>
<body>

<?php
$t=date("H");
if ($t<"20")
   {
   echo "Have a good day!";
   }
?>
  </body>
</html>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
PHP - The if...else Statement
Use the if....else statement to execute some code if a condition is true and another code if the
condition is false.
Syntax
if (condition)
 {
  code to be executed if condition is true;
 }
else
 {
  code to be executed if condition is false;
 }
The example below will output "Have a good day!" if the current time is less than 20, and "Have a good
night!" otherwise:
<!DOCTYPE html> Have a good day!
<html>
<body>

<?php
$t=date("H");
if ($t<"20")
   {
   echo "Have a good day!";
   }
else
   {
   echo "Have a good night!";
   }
?>
  
</body>
</html>
PHP - The if...else if....else Statement
Use the if....else if...else statement to select one of several blocks of code to be executed.
Syntax
if (condition)
 {
  code to be executed if condition is true;
  }
else if (condition)
 {
  code to be executed if condition is true;
 }
else
 {

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
  code to be executed if condition is false;
 }
The example below will output "Have a good morning!" if the current time is less than 10, and "Have a
good day!" if the current time is less than 20. Otherwise it will output "Have a good night!":
<!DOCTYPE html> Have a good morning!
<html>
<body>

<?php
$t=date("H");
if ($t<"10")
   {
   echo "Have a good morning!";
   }
else if ($t<"20")
   {
   echo "Have a good day!";
   }
else
   {
   echo "Have a good night!";
   }
?>
  
</body>
</html>
The PHP Switch Statement
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch (n)
{
case label1:
  code to be executed if n=label1;
  break;
case label2:
  code to be executed if n=label2;
  break;
default:
  code to be executed if n is different from both label1 and label2;
}
This is how it works: First we have a single expression n (most often a variable), that is evaluated once.
The value of the expression is then compared with the values for each case in the structure. If there is a
match, the block of code associated with that case is executed. Use break to prevent the code from
running into the next case automatically. The default statement is used if no match is found.
<!DOCTYPE html> Your favorite color is red!
<html>
<body>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

<?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, or
green!";
}
?>
  
</body>
</html>

PHP Arrays
An array stores multiple values in one single variable:
<!DOCTYPE html> I like Volvo, BMW and Toyota.
<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";
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!

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
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 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):
$cars=array("Volvo","BMW","Toyota");
or the index can be assigned manually:
$cars[0]="Volvo";
$cars[1]="BMW";
$cars[2]="Toyota";
The following example creates an indexed array named $cars, assigns three elements to it, and then prints
a text containing the array values:
<!DOCTYPE html> I like Volvo, BMW and Toyota.
<html>
<body>

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

</body>
</html>

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

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

</body>
</html>
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

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:
<!DOCTYPE html> Volvo
<html> BMW
<body> Toyota

<?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: 
<!DOCTYPE html> Peter is 35 years old.
<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> Key=Peter, Value=35
<html> Key=Ben, Value=37
<body> Key=Joe, Value=43

<?php
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
$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 - Sort Functions For Arrays


 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
Loops execute a block of code a specified number of times, or while a specified condition is true.
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 lines in a script we can use loops to perform a task
like this.
In PHP, we have the following looping statements:
 while - loops through a block of code while a specified condition is true
 do...while - loops through a block of code once, and then repeats the loop as long as a
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 while Loop


The while loop executes a block of code while a condition is true.
Syntax
while (condition)
 {
  code to be executed;
 }
Example
The example below first sets a variable i to 1 ($i=1;).
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Then, the while loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each
time the loop runs:
<html> The number is 1
<body> The number is 2
The number is 3
<?php The number is 4
$i=1; The number is 5
while($i<=5)
  {
  echo "The number is " . $i . "<br>";
  $i++;
  }
?>

</body>
</html>

The do...while Statement


The do...while statement will always execute the block of code once, it will then check the condition, and
repeat the loop while the condition is true.
Syntax
do
 {
  code to be executed;
  }
while (condition);
Example
The example below first sets a variable i to 1 ($i=1;).
Then, it starts the do...while loop. The loop will increment the variable i with 1, and then write some
output. Then the condition is checked (is i less than, or equal to 5), and the loop will continue to run as
long as i is less than, or equal to 5:
<html> The number is 2
<body> The number is 3
The number is 4
<?php The number is 5
$i=1; The number is 6
do
  {
  $i++;
  echo "The number is " . $i . "<br>";
  }
while ($i<=5);

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
?>

</body>
</html>

The for Loop


The for loop is used when you know in advance how many times the script should run.
Syntax
for (init; condition; increment)
 {
  code to be executed;
 }
Parameters:
init: Mostly used to set a counter (but can be any code to be executed once at the beginning of the loop)
condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to
FALSE, the loop ends.
increment: Mostly used to increment a counter (but can be any code to be executed at the end of the
iteration)
Note: The init and increment parameters above can be empty or have multiple expressions (separated by
commas).
Example
The example below defines a loop that starts with i=1. The loop will continue to run as long as the
variable i is less than, or equal to 5. The variable i will increase by 1 each time the loop runs:
<html> The number is 1
<body> The number is 2
The number is 3
<?php The number is 4
for ($i=1; $i<=5; $i++) The number is 5
 {
  echo "The number is " . $i . "<br>";
 }
?>

</body>
</html>

The foreach Loop


The foreach loop is used to loop through arrays.
Syntax
foreach ($array as $value)
 {

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
  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) - so on the next loop iteration, you'll be looking at the next array value.
Example
The following example demonstrates a loop that will print the values of the given array:
<html> one
<body> two
three
<?php
$x=array("one","two","three");
foreach ($x as $value)
 {
  echo $value . "<br>";
 }
?>

</body>
</html>

PHP Functions
To keep the script from being executed when the page loads, you can put it into a function.
A function will be executed by a call to the function. You may call a function from anywhere within a
page.
Create a PHP Function
A function will be executed by a call to the function.
Syntax
function functionName()
{
code to be executed;
}
PHP function guidelines:
Give the function a name that reflects what the function does
The function name can start with a letter or underscore (not a number)
Example
A simple function that writes my name when it is called:
<html> My name is Kai Jim Refsnes
<body>

<?php
function writeName()
{
echo "Kai Jim Refsnes";
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
}

echo "My name is ";


writeName();
?>

</body>
</html>

PHP Functions - Adding parameters


To add more functionality to a function, we can add parameters. A parameter is just like a variable.
Parameters are specified after the function name, inside the parentheses.
Example 1
The following example will write different first names, but equal last name:
<html> My name is Kai Jim Refsnes.
<body> My sister's name is HegeRefsnes.
My brother's name is Stale Refsnes.
<?php
function writeName($fname)
{
echo $fname . " Refsnes.<br>";
}

echo "My name is ";


writeName("Kai Jim");
echo "My sister's name is ";
writeName("Hege");
echo "My brother's name is ";
writeName("Stale");
?>

</body>
</html>

Example 2
The following function has two parameters:
<html> My name is Kai Jim Refsnes.
<body> My sister's name is HegeRefsnes!
My brother's name is StåleRefsnes?
<?php
function writeName($fname,$punctuation)
{

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
echo $fname . " Refsnes" . $punctuation .
"<br>";
}

echo "My name is ";


writeName("Kai Jim",".");
echo "My sister's name is ";
writeName("Hege","!");
echo "My brother's name is ";
writeName("Ståle","?");
?>

</body>
</html>
 
PHP Functions - Return values
To let a function return a value, use the return statement.
Example
<html> 1 + 16 = 17
<body>

<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}

echo "1 + 16 = " . add(1,16);


?>

</body>
</html>
Output:
PHP Forms and User Input
The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input.
PHP Form Handling
The most important thing to notice when dealing with HTML forms and PHP is that any form element in
an HTML page will automatically be available to your PHP scripts.
Example
The example below contains an HTML form with two input fields and a submit button:
<html> Welcome John!
<body> You are 28 years old.
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

<form action="welcome.php" method="post">


Name: <input type="text" name="fname">
Age: <input type="text" name="age">
<input type="submit">
</form>

</body>
</html>

Below is page "welcome.php"


When a user fills out the form above and clicks
on the submit button, the form data is sent to a
PHP file, called "welcome.php":
"welcome.php" looks like this:

<html>
<body>

Welcome <?php echo $_POST["fname"]; ?>!


<br>
You are <?php echo $_POST["age"]; ?> years
old.

</body>
</html>

Form Validation
User input should be validated on the browser whenever possible (by client scripts). Browser validation is
faster and reduces the server load.
You should consider server validation if the user input will be inserted into a database. A good way to
validate a form on the server is to post the form to itself, instead of jumping to a different page. The user
will then get the error messages on the same page as the form. This makes it easier to discover the error.
The $_GET Variable
The predefined $_GET variable is used to collect values in a form with method="get"
Information sent from a form with the GET method is visible to everyone (it will be displayed in the
browser's address bar) and has limits on the amount of information to send.
Example
<form action="welcome.php" method="get">
Name: <input type="text" name="fname">
Age: <input type="text" name="age">
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
<input type="submit">
</form>
When the user clicks the "Submit" button, the URL sent to the server could look something like this:
http://www.w3schools.com/welcome.php?fname=Peter&age=37
The "welcome.php" file can now use the $_GET variable to collect form data (the names of the form
fields will automatically be the keys in the $_GET array):
Welcome <?php echo $_GET["fname"]; ?>.<br>
You are <?php echo $_GET["age"]; ?> years old!
When to use method="get"?
When using method="get" in HTML forms, all variable names and values are displayed in the URL.
Note: This method should not be used when sending passwords or other sensitive information!
However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be
useful in some cases.
Note: The get method is not suitable for very large variable values. It should not be used with values
exceeding 2000 characters.
In PHP, the predefined  $_POST variable is used to collect values in a form with method="post".
The $_POST Variable
The predefined $_POST variable is used to collect values from a form sent with method="post".
Information sent from a form with the POST method is invisible to others and has no limits on the amount
of information to send.
Note: However, there is an 8 MB max size for the POST method, by default (can be changed by setting
the post_max_size in the php.ini file).
Example
<form action="welcome.php" method="post">
Name: <input type="text" name="fname">
Age: <input type="text" name="age">
<input type="submit">
</form>
When the user clicks the "Submit" button, the URL will look like this:
http://www.w3schools.com/welcome.php
The "welcome.php" file can now use the $_POST variable to collect form data (the names of the form
fields will automatically be the keys in the $_POST array):
Welcome <?php echo $_POST["fname"]; ?>!<br>
You are <?php echo $_POST["age"]; ?> years old.

When to use method="post"?


Information sent from a form with the POST method is invisible to others and has no limits on the amount
of information to send.
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
The PHP $_REQUEST Variable
The predefined $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE.
The $_REQUEST variable can be used to collect form data sent with both the GET and POST methods.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Example
Welcome <?php echo $_REQUEST["fname"]; ?>!<br>
You are <?php echo $_REQUEST["age"]; ?> years old.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Tasks:
Q1. Write a php code that creates an associative array and print the contents on the webpage

Q2. Write a php code that creates a simple calculator web based application. On each operation the
respective function of addition, subtraction, multiplication and division must be called.
The Code:
<!DOCTYPE html>

<head>
<title>Simple Calculator Program in PHP - Tutorials Class</title>
</head>

<?php
$first_num = $_POST["first_num"];
$second_num = $_POST['second_num'];
$operator = $_POST['operator'];
$result = '';
if (is_numeric($first_num) && is_numeric($second_num)) {
switch ($operator) {
case "Add":
$result = $first_num + $second_num;
break;
case "Subtract":
$result = $first_num - $second_num;
break;
case "Multiply":
$result = $first_num * $second_num;

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
break;
case "Divide":
$result = $first_num / $second_num;
}
}

?>

<body>
<div id="page-wrap">
<h1>PHP - Simple Calculator Program</h1>
<form action="" method="post" id="quiz-form">
<p>
<input type="number" name="first_num" id="first_num"

required="required" value="<?php echo $first_num; ?>" /> <b>First Number</b>


</p>
<p>
<input type="number" name="second_num" id="second_num"

required="required" value="<?php echo $second_num; ?>" /> <b>Second Number</b>


</p>
<p>
<input readonly="readonly" name="result" value="<?php echo $result;

?>"> <b>Result</b>
</p>
<input type="submit" name="operator" value="Add" />
<input type="submit" name="operator" value="Subtract" />
<input type="submit" name="operator" value="Multiply" />
<input type="submit" name="operator" value="Divide" />
</form>
</div>
</body>
</html>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Output Add:

Output Subtract:

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Output Multiply:

Output Divide:

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Q3. Write a php code that creates a form and on submission takes you to another page welcome.php.
perform the task using both get and post methods. Use GET and POST variables to collect the data of
form and print them on welcome.php
Form Using POST Method:

Page of welcome.php Using POST Method:

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Form Using GET Method:

Page of welcome_get.php Using POST Method:

Learning outcomes:

In this lab we have covered that, how to program using PHP and how the PHP becomes connected with

database and run Web Pages with Local-Host URL.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Lab # 10
Creating Dynamic Website
Objective

 In this lab you will learn the basic idea about creating dynamic website

Theory
AJAX ASP/PHP Example
The following example will demonstrate how a web page can communicate with a web server while a
user type characters in an input field:

Example
Start typing a name in the input field below:
Top of Form
First name: 
Bottom of Form
Suggestions:

Example Explained - The showHint() Function


When a user types a character in the input field above, the function "showHint()" is executed. The
function is triggered by the "onkeyup" event:
function showHint(str)
{
var xmlhttp;
if (str.length==0)
  { 
  document.getElementById("txtHint").innerHTML="";
  return;
 }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
 }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
xmlhttp.onreadystatechange=function()
 {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
 }
xmlhttp.open("GET","gethint.asp?q="+str,true);
xmlhttp.send();
}

Source code explanation:


If the input field is empty (str.length==0), the function clears the content of the txtHint placeholder and
exits the function.
If the input field is not empty, the showHint() function executes the following:
Create an XMLHttpRequest object
Create the function to be executed when the server response is ready
Send the request off to a file on the server
Notice that a parameter (q) is added to the URL (with the content of the input field)
The PHP File
Here is the code above rewritten in PHP:
<?php
// Fill up array with names
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";

//get the q parameter from URL


$q=$_GET["q"];

//lookup all hints from array if length of q>0


if (strlen($q) > 0)
 {
  $hint="";
  for($i=0; $i<count($a); $i++)
    {
    if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
      {
      if ($hint=="")
        {
        $hint=$a[$i];
        }
      else
        {
        $hint=$hint." , ".$a[$i];
        }
      }
    }
 }

// Set output to "no suggestion" if no hint were found


// or to the correct values
if ($hint == "")
 {
  $response="no suggestion";
 }
else
 {
  $response=$hint;
 }

//output the response

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
echo $response;
?>

<!DOCTYPE html> Start typing a name


<html> in the input field
<head> below:
<script>
function showHint(str) Top of Form
{
var xmlhttp; First
if (str.length==0) name: 
{
document.getElementById("txtHint").innerHTML=""; Bottom of Form
return;
} Suggestions: Diana
if (window.XMLHttpRequest) , Doris
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{

document.getElementById("txtHint").innerHTML=xmlhttp.responseTe
xt;
}
}
xmlhttp.open("GET","gethint.asp?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<h3>Start typing a name in the input field below:</h3>


<form action="">
First name: <input type="text" id="txt1"
onkeyup="showHint(this.value)" />

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
</form>
<p>Suggestions: <span id="txtHint"></span></p>

</body>
</html>
AJAX Poll
The following example will demonstrate a poll where the result is shown without reloading.
Do you like PHP and AJAX so far?
Top of Form
Yes:   
No: 
Bottom of Form

Example Explained - The HTML Page


When a user choose an option above, a function called "getVote()" is executed. The function is triggered
by the "onclick" event:
<html>
<head>
<script>
function getVote(int)
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
 }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
xmlhttp.onreadystatechange=function()
 {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("poll").innerHTML=xmlhttp.responseText;
    }
 }
xmlhttp.open("GET","poll_vote.php?vote="+int,true);
xmlhttp.send();
}
</script>
</head>
<body>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

<div id="poll">
<h3>Do you like PHP and AJAX so far?</h3>
<form>
Yes:
<input type="radio" name="vote" value="0" onclick="getVote(this.value)">
<br>No:
<input type="radio" name="vote" value="1" onclick="getVote(this.value)">
</form>
</div>

</body>
</html>

The getVote() function does the following:


 Create an XMLHttpRequest object
 Create the function to be executed when the server response is ready
 Send the request off to a file on the server
Notice that a parameter (vote) is added to the URL (with the value of the yes or no option)
The PHP File
The page on the server called by the JavaScript above is a PHP file called "poll_vote.php":
<?php
$vote = $_REQUEST['vote'];

//get content of textfile


$filename = "poll_result.txt";
$content = file($filename);

//put content in array


$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];

if ($vote == 0)
  {
  $yes = $yes + 1;
  }
if ($vote == 1)
  {
  $no = $no + 1;
  }

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
//insert votes to txt file
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
?>

<h2>Result:</h2>
<table>
<tr>
<td>Yes:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($yes/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($yes/($no+$yes),2)); ?>%
</td>
</tr>
<tr>
<td>No:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($no/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($no/($no+$yes),2)); ?>%
</td>
</tr>
</table>

The value is sent from the JavaScript, and the following happens:
 Get the content of the "poll_result.txt" file
 Put the content of the file in variables and add one to the selected variable
 Write the result to the "poll_result.txt" file
 Output a graphical representation of the poll result
The Text File
The text file (poll_result.txt) is where we store the data from the poll.
It is stored like this:
0||0
The first number represents the "Yes" votes, the second number represents the "No" votes.
Note: Remember to allow your web server to edit the text file. Do NOT give everyone access, just the
web server (PHP).
AJAX can be used to create more user-friendly and interactive searches.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
AJAX Live Search
The following example will demonstrate a live search, where you get search results while you type.
Live search has many benefits compared to traditional searching:
Results are shown as you type
Results narrow as you continue typing
If results become too narrow, remove characters to see a broader result
Search for a W3Schools page in the input field below:
Top of Form

Bottom of Form
Example Explained - The HTML Page
When a user types a character in the input field above, the function "showResult()" is executed. The
function is triggered by the "onkeyup" event:
<html>
<head>
<script>
function showResult(str)
{
if (str.length==0)
  { 
  document.getElementById("livesearch").innerHTML="";
  document.getElementById("livesearch").style.border="0px";
  return;
 }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
 }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
xmlhttp.onreadystatechange=function()
 {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("livesearch").innerHTML=xmlhttp.responseText;
    document.getElementById("livesearch").style.border="1px solid #A5ACB2";
    }
 }
xmlhttp.open("GET","livesearch.php?q="+str,true);
xmlhttp.send();
}
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
</script>
</head>
<body>

<form>
<input type="text" size="30" onkeyup="showResult(this.value)">
<div id="livesearch"></div>
</form>

</body>
</html>
Source code explanation:
If the input field is empty (str.length==0), the function clears the content of the livesearch placeholder and
exits the function.
If the input field is not empty, the showResult() function executes the following:
 Create an XMLHttpRequest object
 Create the function to be executed when the server response is ready
 Send the request off to a file on the server
Notice that a parameter (q) is added to the URL (with the content of the input field)
The PHP File
The page on the server called by the JavaScript above is a PHP file called "livesearch.php".
The source code in "livesearch.php" searches an XML file for titles matching the search string and returns
the result:
<?php
$xmlDoc=new DOMDocument();
$xmlDoc->load("links.xml");

$x=$xmlDoc->getElementsByTagName('link');

//get the q parameter from URL


$q=$_GET["q"];

//lookup all links from the xml file if length of q>0


if (strlen($q)>0)
{
$hint="";
for($i=0; $i<($x->length); $i++)
  {
  $y=$x->item($i)->getElementsByTagName('title');
  $z=$x->item($i)->getElementsByTagName('url');
  if ($y->item(0)->nodeType==1)
    {
    //find a link matching the search text
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
    if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q))
      {
      if ($hint=="")
        {
        $hint="<a href='" . 
        $z->item(0)->childNodes->item(0)->nodeValue . 
        "' target='_blank'>" . 
        $y->item(0)->childNodes->item(0)->nodeValue . "</a>";
        }
      else
        {
        $hint=$hint . "<br /><a href='" . 
        $z->item(0)->childNodes->item(0)->nodeValue . 
        "' target='_blank'>" . 
        $y->item(0)->childNodes->item(0)->nodeValue . "</a>";
        }
      }
    }
  }
}

// Set output to "no suggestion" if no hint were found


// or to the correct values
if ($hint=="")
  {
  $response="no suggestion";
  }
else
  {
  $response=$hint;
  }

//output the response


echo $response;
?>

If there is any text sent from the JavaScript (strlen($q) > 0), the following happens:
 Load an XML file into a new XML DOM object
 Loop through all <title> elements to find matches from the text sent from the JavaScript
 Sets the correct url and title in the "$response" variable. If more than one match is found,
all matches are added to the variable
If no matches are found, the $response variable is set to "no suggestion"

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Tasks:

1. Create an AJAX calendar for web pages.


The Code:
<?php
class PHPCalendar {
private $weekDayName = array ("MON","TUE","WED","THU","FRI","SAT","SUN");
private $currentDay = 0;
private $currentMonth = 0;
private $currentYear = 0;
private $currentMonthStart = null;
private $currentMonthDaysLength = null;

function __construct() {
$this->currentYear = date ( "Y", time () );
$this->currentMonth = date ( "m", time () );

if (! empty ( $_POST ['year'] )) {


$this->currentYear = $_POST ['year'];
}
if (! empty ( $_POST ['month'] )) {
$this->currentMonth = $_POST ['month'];
}
$this->currentMonthStart = $this->currentYear . '-' . $this->currentMonth . '-01';
$this->currentMonthDaysLength = date ( 't', strtotime ( $this->currentMonthStart )

);
}

function getCalendarHTML() {
$calendarHTML = '<div id="calendar-outer">';
$calendarHTML .= '<div class="calendar-nav">' . $this->getCalendarNavigation() .

'</div>';
$calendarHTML .= '<ul class="week-name-title">' . $this->getWeekDayName () .

'</ul>';
$calendarHTML .= '<ul class="week-day-cell">' . $this->getWeekDays () . '</ul>';

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
$calendarHTML .= '</div>';
return $calendarHTML;
}

function getCalendarNavigation() {
$prevMonthYear = date ( 'm,Y', strtotime ( $this->currentMonthStart. ' -1 Month'

) );
$prevMonthYearArray = explode(",",$prevMonthYear);

$nextMonthYear = date ( 'm,Y', strtotime ( $this->currentMonthStart . ' +1 Month'

) );
$nextMonthYearArray = explode(",",$nextMonthYear);

$navigationHTML = '<div class="prev" data-prev-month="' . $prevMonthYearArray[0] .

'" data-prev-year = "' . $prevMonthYearArray[1]. '"><</div>';


$navigationHTML .= '<span id="currentMonth">' . date ( 'M ', strtotime ( $this-

>currentMonthStart ) ) . '</span>';
$navigationHTML .= '<span contenteditable="true" id="currentYear">'. date (

'Y', strtotime ( $this->currentMonthStart ) ) . '</span>';


$navigationHTML .= '<div class="next" data-next-month="' . $nextMonthYearArray[0]

. '" data-next-year = "' . $nextMonthYearArray[1]. '">></div>';


return $navigationHTML;
}

function getWeekDayName() {
$WeekDayName= '';
foreach ( $this->weekDayName as $dayname ) {
$WeekDayName.= '<li>' . $dayname . '</li>';
}
return $WeekDayName;
}

function getWeekDays() {
$weekLength = $this->getWeekLengthByMonth ();

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
$firstDayOfTheWeek = date ( 'N', strtotime ( $this->currentMonthStart ) );
$weekDays = "";
for($i = 0; $i < $weekLength; $i ++) {
for($j = 1; $j <= 7; $j ++) {
$cellIndex = $i * 7 + $j;
$cellValue = null;
if ($cellIndex == $firstDayOfTheWeek) {
$this->currentDay = 1;
}
if (! empty ( $this->currentDay ) && $this->currentDay <= $this-

>currentMonthDaysLength) {
$cellValue = $this->currentDay;
$this->currentDay ++;
}
$weekDays .= '<li>' . $cellValue . '</li>';
}
}
return $weekDays;
}

function getWeekLengthByMonth() {
$weekLength = intval ( $this->currentMonthDaysLength / 7 );
if($this->currentMonthDaysLength % 7 > 0) {
$weekLength++;
}
$monthStartDay= date ( 'N', strtotime ( $this->currentMonthStart) );
$monthEndingDay= date ( 'N', strtotime ( $this->currentYear . '-' . $this-

>currentMonth . '-' . $this->currentMonthDaysLength) );


if ($monthEndingDay < $monthStartDay) {
$weekLength++;
}

return $weekLength;
}
}
?>
return $weekLength;
}
}

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
?>

The Output:

Note: Attach a snap shot of every above mentioned task.

Learning outcomes:

After Completion of this lab we have learnt the basic idea about creating dynamic website with

AJAX & PHP.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

Lab # 11
Structure Query Language
Objective

 In this lab you will learn the basic concepts of SQL.

Theory
What is DDL?
A data definition language or data description language (DDL) is syntax similar to a
computer programming language for defining data structures, especially database schemas.
DDL includes the following main queries:
1. Create
2. Drop
3. Alter
Create Statement
Create statement is used to make new database, table, index etc.
Create New Database:
Syntax:
Create database {database name};

Example:
mysql> Create database teacher;
Query OK, 1 row affected
Use Statement:
Use command is used to select a database other than default.
Syntax:
use {database name};
Example:
mysql> use teacher;
Database changed.

Create New Table:


Syntax:
CREATE TABLE [table name] ( [column definitions] ) [table parameters].

Column definitions: A comma-separated list consisting of any of the following


 Column definition: [column name] [data type] {NULL | NOT NULL} {column options}
 Primary key definition: PRIMARY KEY ( [comma separated column list] )

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
 Constraints: {CONSTRAINT} [constraint definition]
 RDBMS specific functionality
Data Types:
In MySQL there are three main types: text, number, and Date/Time types.
*Even if DATETIME and TIMESTAMP return the same format, they work very differently. In an
INSERT or UPDATE query, the TIMESTAMP automatically set itself to the current date and time.
TIMESTAMP also accepts various formats, like YYYYMMDDHHMMSS, YYMMDDHHMMSS,
YYYYMMDD, or YYMMDD.
Example:
mysql> CREATE TABLE employee (
id INTEGER PRIMARY KEY,
first_name VARCHAR(50) NULL,
last_name VARCHAR(75) NOT NULL,
dateofbirth DATE NULL
);
Query OK, 0 rows affected

desc Command:
desc command is used to show the table design view.

Syntax:
desc {table name};

Example:
mysql> desc employee;
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra|
+----------+-------------+------+-----+---------+-------+
| emp_id | int(3) | NO | PRI | NULL | |
| emp_name | varchar(25) | YES | | NULL |
| e_design | varchar(5) | YES | | NULL | |
+----------+-------------+------+-----+---------+-------+
3 rows in set
DROP Statement
Drop is used to destroy an existing database, table, etc.
Drop Database
Syntax:
Drop database {database name};

Example:
mysql> Drop database organization;
Query OK, 3 rows affected

Drop Table:

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Syntax:
Drop table {table name};

Example:
mysql> drop table teacher;
Query OK, 0 rows affected

Alter Statement
Alter statement is used to modify an existing database object.
Syntax:
ALTER {object type} {object name} {parameters};

Example:
// to add a column
mysql> alter table student add st_add varchar(50);
Query OK, 0 rows affected
Records: 0 Duplicates: 0 Warnings: 0

//to drop a column


mysql> alter table student drop st_name;
Query OK, 0 rows affected
Records: 0 Duplicates: 0 Warnings: 0
What is DML?
A data manipulation language (DML) is a family of syntax elements similar to a computer programming
language used for inserting, deleting and updating data in a database. Performing read-only queries of
data is sometimes also considered a component of DML..
DML includes the following main queries:
1. SELECT ... FROM ... WHERE ...
2. INSERT INTO ... VALUES ...
3. UPDATE ... SET ... WHERE ...
4. DELETE FROM ... WHERE ...
Insert Statement
An SQL INSERT statement adds one or more records to any single table in a relational database.
Single Row Insert:

Syntax:

INSERT INTO table (column1 [, column2, column3 ... ]) VALUES (value1 [, value2, value3 ... ])

Example:

mysql> insert into student


-> values ("003","Sukkar");
Query OK, 1 row affected

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

mysql> insert into student (st_id, st_add) Values ("002", "Punjab");


Query OK, 1 row affected

Multiple Row Insert:


Syntax:

INSERTINTOTABLE (column-a, [column-b, ...])


VALUES ('value-1a', ['value-1b', ...]),

Example:

mysql> insert into student (st_id, st_add)


-> Values ("004","Karachi"), ("005","Hyderabad");
Query OK, 2 rows affected
Records: 2 Duplicates: 0 Warnings: 0

Inserting Rows with Null Values

Example:

mysql> insert into student (st_id, st_add)


-> Values ("10",null);
Query OK, 1 row affected
Basic Select Statement
A SELECT statement retrieves information from the database. You can do the following
 Projection: You can use the projection capability in SQL to choose the column in the table that
you want returned by your query. You can choose as few or as many columns of the table as you
require.
 Selection: You can use the selection capability in SQL to choose the rows in the table that you
want returned by query. You can use various criteria to restrict the rows you want.
 Joining: You can use the join capability in SQL to bring together data that is stored in different
tables by creating a link between them.
Syntax:
SELECT *|{[DISTINCT] column|expression [alias],...}
FROM table;

Example:
mysql> select distinct * from student; //selecting all from table

mysql> select st_id as student_ID, st_add as Student_Address // changing column alias using “as”
-> from student;
+------------+-----------------------------+
| student_ID | Student_Address |
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
+------------+-----------------------------+
| 1 | Karachi |
| 2 | Punjab |
| 3 | Sukkar |
| 4 | Karachi |
| 5 | Hyderabad |
| 10 | NULL |
+------------+-----------------------------+
6 rows in set

mysql> select st_id from student; // selecting specific columns


+-------+
| st_id |
+-------+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 10 |
+-------+
6 rows in set

In its simplest form, a SELECT statement must include the following:


 A SELECT clause, which specifies the columns to be displayed
 A FROM clause, which specifies the table containing the columns listed in the SELECT clause
In the syntax:
SELECT is a list of one or more columns
* selects all columns
DISTINCT suppresses duplicates
column|expression selects the named column or the expression
alias gives selected columns different headings
FROM table specifies the table containing the columns

Note: Throughout this course, the words keyword, clause, and statement are used as follows:
 A keyword refers to an individual SQL element.
For example, SELECT and FROM are keywords.
 A clause is a part of a SQL statement.
For example, SELECT employee_id, last_name, ... is a clause.
 A statement is a combination of two or more clauses.
For example, SELECT * FROM employees is a SQL statement.
Arithmetic Operators
The table below lists the arithmetic operators available in SQL. You can use arithmetic operators in any
clause of a SQL statement except in the FROM clause.
Operator Description
+ Add
- Subtract

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
* Multiply
/ Divide

Execute the following query and check the results


SELECT last_name, salary, salary + 300
FROM employees;
Operator Precedence
If an arithmetic expression contains more than one operator, multiplication and division are evaluated
first. If operators within an expression are of same priority, then evaluation is done from left to right.
You can use parentheses to force the expression within parentheses to be evaluated first.
Execute the following query and check the results
SELECT last_name, salary, 12*salary+100
FROM employees;
The example above displays the last name, salary, and annual compensation of employees. It calculates
the annual compensation as 12 multiplied by the monthly salary, plus a one-time bonus of $100. Notice
that multiplication is performed before addition.
Note: Use parentheses to reinforce the standard order of precedence and to improve clarity. For example,
the expression on the slide can be written as (12*salary)+100 with no change in the result.
Using Parentheses
Execute the following query and check the results
SELECT last_name, salary, 12*(salary+100)
FROM employees;
You can override the rules of precedence by using parentheses to specify the order in which operators are
executed.
The example above displays the last name, salary, and annual compensation of employees. It calculates
the annual compensation as monthly salary plus a monthly bonus of $100, multiplied by 12. Because of
the parentheses, addition takes priority over multiplication .
Changing Data in a Table

UPDATE table
SET column = value [, column = value, ...]
[WHERE condition];

You can modify existing rows by using the UPDATE statement.


In the syntax:
Tableis the name of the table
Columnis the name of the column in the table to populate
Valueis the corresponding value or sub query for the column
Conditionidentifies the rows to be updated and is composed of column names expressions,
constants, sub queries, and comparison operators,

Confirm the update operation by querying the table to display the updated rows.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Note: In general, use the primary key to identify a single row. Using other columns can unexpectedly
cause several rows to be updated. For example, identifying a single row in the EMPLOYEES table by
nme is dangerous, because more than one employee may have the same name.

UPDATE employees
SET department_id = 70
WHERE employee_id = 113;

1 row updated.
The UPDATE statement modifies specific rows if the WHERE clause is specified. The slide example
transfers employee 113 (Popp) to department 70.
If you omit the WHERE clause, all the rows in the table are modified.
UPDATE copy_emp
SET department_id = 110;
22 rows updated.
Updating Two Columns with a Subquery

UPDATE employees
SET job_id = (SELECT job_id
FROM employees
WHERE employee_id = 205),
salary = (SELECT salary
FROM employees
WHERE employee_id = 205)
WHERE employee_id = 114;
You can update multiple columns in the SET clause of an UPDATE statement by writing multiple
subqueries.
Syntax
UPDATE table
SET column = (SELECT column FROM table WHERE condition)
[ column =(SELECT column FROM table WHERE condition)]
[WHERE condition ] ;

Note: If no rows are updated, a message “0 rows updated.” is returned.


Deleting a Row from a Table
Syntax:
DELETE [FROM] table
[WHERE condition];

You can remove existing rows by using the DELETE statement.


In the syntax:
Tableis the table name
Conditionidentifies the rows to be deleted and is composed of column names,
expressions, constants, subqueries, and comparison operators

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

Note: If no rows are deleted, a message “0 rows deleted.” is returned:


DELETE FROM departments
WHERE department_name = ’Finance’;

You can delete specific rows by specifying the WHERE clause in the DELETE statement. The above
example deletes the Finance department from the DEPARTMENTS table. You can confirm the delete
operation by displaying the deleted rows using the SELECT statement.
SELECT *
FROM departments
WHERE department_name = ’Finance’;

Output
No rows selected.

If you omit the WHERE clause, all rows in the table are deleted. The following example deletes all the
rows from the COPY_EMP table, because no WHERE clause has been specified.
DELETE FROM copy_emp;
22 rows deleted.
Example
Remove rows identified in the WHERE clause.
DELETE FROM employees
WHERE employee_id = 114;
1 row deleted.

DELETE FROM departments


WHERE department_id IN (30, 40);
Deleting Rows Based on Another Table
You can use subqueries to delete rows from a table based on values from another table. The example
below deletes all the employees who are in a department where the department name contains the string
“Public.” The subquery searches the DEPARTMENTS table to find the department number based on the
department name containing the string “Public.” The subquery then feeds the department number to the
main query, which deletes rows of data from the EMPLOYEES table based on this department number.
DELETE FROM employees
WHERE department_id =
(SELECT department_id
FROM departments
WHERE department_name LIKE ’%Public%’);

Deleting Rows: Integrity Constraint Error


DELETE FROM departments
WHERE department_id = 60;
DELETE FROM departments

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
*
ERROR at line 1: integrity constrain
If you attempt to delete a record with a value that is tied to an integrity constraint, an error is returned.
The example above tries to delete department number 60 from the DEPARTMENTS table, but it results
in an error because department number is used as a foreign key in the EMPLOYEES table. If the parent
record that you attempt to delete has child records, then you receive the child record found violation
The following statement works because there are no employees in department 70:
DELETE FROM departments
WHERE department_id = 70;
Updating Rows Based on another Table

UPDATE copy_emp
SET department_id = (SELECT department_id
FROM employees
WHERE employee_id = 100)
WHERE job_id = (SELECT job_id
FROM employees
WHERE employee_id = 200);
You can use subqueries in UPDATE statements to update rows in a table. The above example updates the
COPY_EMP table based on the values from the EMPLOYEES table. It changes the department number
of all employees with employee 200’s job ID to employee 100’s current department number.
Updating Rows: Integrity Constraint Error
UPDATE employees
SET department_id = 55
WHERE department_id = 110;
UPDATE employees
*
ERROR at line 1: integrity constraint (HR.EMP_DEPT_FK) violated - parent key not found
If you attempt to update a record with a value that is tied to an integrity constraint, an error is returned.
In the above example, department number 55 does not exist in the parent table, DEPARTMENTS, and so
you receive the parent key violation ORA-02291.
Note: Integrity constraints ensure that the data adheres to a predefined set of rules. A subsequent lesson
covers integrity constraints in greater depth.
Using a Subquery in an INSERT Statement

INSERT INTO
(SELECT employee_id, last_name,
email, hire_date, job_id, salary,
department_id
FROM employees
WHERE department_id = 50)
VALUES (99999, ’Taylor’, ’DTAYLOR’,
TO_DATE(’07-JUN-99’, ’DD-MON-RR’),
’ST_CLERK’, 5000, 50);
1 row created.
You can use a subquery in place of the table name in the INTO clause of the INSERT statement.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
The select list of this subquery must have the same number of columns as the column list of the VALUES
clause. Any rules on the columns of the base table must be followed in order for the INSERT statement to
work successfully. For example, you could not put in a duplicate employee ID, nor leave out a value for a
mandatory not null column.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

Exercise:
1. Create a full fledge database for employee, customers and orders and name it
e_consumer.

CREATE DATABASE e_consumer

Table "employees"

CREATE TABLE employee

emp_no INT NOT NULL, -- UNSIGNED AUTO_INCREMENT??

birth_date DATE NOT NULL,

first_name VARCHAR(14) NOT NULL,

last_name VARCHAR(16) NOT NULL,

gender ENUM ('M','F') NOT NULL, -- Enumeration of either 'M' or 'F'

hire_date DATE NOT NULL,

PRIMARY KEY (emp_no) -- Index built automatically on primary-key


column

-- INDEX (first_name)

-- INDEX (last_name)

);

Table "customers"

CREATE TABLE customer (

customers_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,

store_id TINYINT UNSIGNED NOT NULL,

first_name VARCHAR(45) NOT NULL,

last_name VARCHAR(45) NOT NULL,

email VARCHAR(50) DEFAULT NULL,

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
address_id SMALLINT UNSIGNED NOT NULL,

active BOOLEAN NOT NULL DEFAULT TRUE,

create_date DATETIME NOT NULL,

last_update TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE


CURRENT_TIMESTAMP,

PRIMARY KEY (customer_id),

KEY idx_fk_store_id (store_id),

KEY idx_fk_address_id (address_id),

KEY idx_last_name (last_name),

CONSTRAINT fk_customer_address FOREIGN KEY (address_id) REFERENCES address


(address_id)

ON DELETE RESTRICT ON UPDATE CASCADE,

CONSTRAINT fk_customer_store FOREIGN KEY (store_id) REFERENCES store (store_id)

ON DELETE RESTRICT ON UPDATE CASCADE

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Table "Orders"

CREATE TABLE order
(order_no char(9),
cust_no char(6) not null,
primary key (order_no),
foreign key (cust_no) references customer
on delete set null on update cascade);

Learning outcomes:

On the Completion of this lab I have learnt the basic concepts of SQL and how to use them easily in

Database.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Lab # 12
PHP & MYSQL
Objective

 In this lab you will learn about integrating web page and MY SQL.

Theory
PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix
platform)

Queries
A query is a question or a request.

We can query a database for specific information and have a recordset returned.

Look at the following query (using standard SQL):

SELECT LastName FROM Employees


The query above selects all the data in the "LastName" column from the "Employees" table.

Open a Connection to the MySQL Server


Before we can access data in a database, we must open a connection to the MySQL server.

In PHP, this is done with the mysqli_connect() function.

Syntax
mysqli_connect(host,username,password,dbname);

Parameter Description
host Optional. Either a host name or an IP address
username Optional. The MySQL user name
password Optional. The password to log in with
dbname Optional. The default database to be used when performing queries
Note: There are more available parameters, but the ones listed above are the most important.

In the following example we store the connection in a variable ($con) for later use in the script:

<?php
// Create connection
$con=mysqli_connect("example.com","peter","abc123","my_db");

// Check connection

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
if (mysqli_connect_errno($con))
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>
Close a Connection
The connection will be closed automatically when the script ends. To close the connection before, use the
mysqli_close() function:

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");

// Check connection
if (mysqli_connect_errno($con))
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

mysqli_close($con);
?>
A database holds one or more tables.

Create a Database
The CREATE DATABASE statement is used to create a database table in MySQL.

We must add the CREATE DATABASE statement to the mysqli_query() function to execute the
command.

The following example creates a database named "my_db":

<?php
$con=mysqli_connect("example.com","peter","abc123");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

// Create database
$sql="CREATE DATABASE my_db";
if (mysqli_query($con,$sql))
 {
  echo "Database my_db created successfully";
 }
else
 {
  echo "Error creating database: " . mysqli_error();
 }
?>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Create a Table
The CREATE TABLE statement is used to create a table in MySQL.

We must add the CREATE TABLE statement to the mysqli_query() function to execute the command.

The following example creates a table named "Persons", with three columns. The column names will be
"FirstName", "LastName" and "Age":

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

// Create table
$sql="CREATE TABLE persons(FirstName CHAR(30),LastName CHAR(30),Age INT)";

// Execute query
if (mysqli_query($con,$sql))
 {
  echo "Table persons created successfully";
 }
else
 {
  echo "Error creating table: " . mysqli_error();
 }
?>
Note: When you create a database field of type CHAR, you must specify the maximum length of the
field, e.g. CHAR(50).

The data type specifies what type of data the column can hold. For a complete reference of all the data
types available in MySQL, go to our complete Data Types reference.

Primary Keys and Auto Increment Fields


Each table in a database should have a primary key field.

A primary key is used to uniquely identify the rows in a table. Each primary key value must be unique
within the table. Furthermore, the primary key field cannot be null because the database engine requires a
value to locate the record.

The following example sets the PID field as the primary key field. The primary key field is often an ID
number, and is often used with the AUTO_INCREMENT setting. AUTO_INCREMENT automatically
increases the value of the field by 1 each time a new record is added. To ensure that the primary key field
cannot be null, we must add the NOT NULL setting to the field:

$sql = "CREATE TABLE Persons 


Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
(
PID INT NOT NULL AUTO_INCREMENT, 
PRIMARY KEY(PID),
FirstName CHAR(15),
LastName CHAR(15),
Age INT
)";
The INSERT INTO statement is used to insert new records in a table.

Insert Data into a Database Table


The INSERT INTO statement is used to add new records to a database table.

Syntax
It is possible to write the INSERT INTO statement in two forms.

The first form doesn't specify the column names where the data will be inserted, only their values:

INSERT INTO table_name


VALUES (value1, value2, value3,...)

The second form specifies both the column names and the values to be inserted:

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,...)

To learn more about SQL, please visit our SQL tutorial.


To get PHP to execute the statements above we must use the mysqli_query() function. This function is
used to send a query or command to a MySQL connection.

Example
In the previous chapter we created a table named "Persons", with three columns; "FirstName",
"LastName" and "Age". We will use the same table in this example. The following example adds two new
records to the "Persons" table:

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

mysqli_query($con,"INSERT INTO Persons (FirstName, LastName, Age)


VALUES ('Peter', 'Griffin',35)");

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
mysqli_query($con,"INSERT INTO Persons (FirstName, LastName, Age) 
VALUES ('Glenn', 'Quagmire',33)");

mysqli_close($con);
?>

Insert Data From a Form Into a Database


Now we will create an HTML form that can be used to add new records to the "Persons" table.

Here is the HTML form:

<html>
<body>

<form action="insert.php" method="post">


Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>

</body>
</html>
When a user clicks the submit button in the HTML form in the example above, the form data is sent to
"insert.php".

The "insert.php" file connects to a database, and retrieves the values from the form with the PHP $_POST
variables.

Then, the mysqli_query() function executes the INSERT INTO statement, and a new record will be added
to the "Persons" table.

Here is the "insert.php" page:

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="INSERT INTO Persons (FirstName, LastName, Age)


VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

if (!mysqli_query($con,$sql))
  {
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
  die('Error: ' . mysqli_error());
  }
echo "1 record added";

mysqli_close($con);
?>
The SELECT statement is used to select data from a database.

Select Data From a Database Table


The SELECT statement is used to select data from a database.

Syntax
SELECT column_name(s)
FROM table_name
To get PHP to execute the statement above we must use the mysqli_query() function. This function is
used to send a query or command to a MySQL connection.

Example
The following example selects all the data stored in the "Persons" table (The * character selects all the
data in the table):

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$result = mysqli_query($con,"SELECT * FROM Persons");

while($row = mysqli_fetch_array($result))
  {
  echo $row['FirstName'] . " " . $row['LastName'];
  echo "<br />";
  }

mysqli_close($con);
?>
The example above stores the data returned by the mysql_query() function in the $result variable.

Next, we use the mysqli_fetch_array() function to return the first row from the recordset as an array. Each
call to mysqli_fetch_array() returns the next row in the recordset. The while loop loops through all the
records in the recordset. To print the value of each row, we use the PHP $row variable ($row['FirstName']
and $row['LastName']).

The output of the code above will be:

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Peter Griffin
Glenn Quagmire

Display the Result in an HTML Table


The following example selects the same data as the example above, but will display the data in an HTML
table:

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$result = mysqli_query($con,"SELECT * FROM Persons");

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";

while($row = mysqli_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysqli_close($con);
?>
The output of the code above will be:

Firstname Lastname
Glenn Quagmire
Peter Griffin
The WHERE clause is used to filter records.

The WHERE clause


The WHERE clause is used to extract only those records that fulfill a specified criterion.

Syntax
SELECT column_name(s)
FROM table_name

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
WHERE column_name operator value
To get PHP to execute the statement above we must use the mysqli_query() function. This function is
used to send a query or command to a MySQL connection.

Example
The following example selects all rows from the "Persons" table where "FirstName='Peter'":

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$result = mysqli_query($con,"SELECT * FROM Persons


WHERE FirstName='Peter'");

while($row = mysqli_fetch_array($result))
  {
  echo $row['FirstName'] . " " . $row['LastName'];
  echo "<br>";
  }
?>
The output of the code above will be:

Peter Griffin
The ORDER BY keyword is used to sort the data in a recordset.

The ORDER BY Keyword


The ORDER BY keyword is used to sort the data in a recordset.

The ORDER BY keyword sort the records in ascending order by default.

If you want to sort the records in a descending order, you can use the DESC keyword.

Syntax
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC
Example
The following example selects all the data stored in the "Persons" table, and sorts the result by the "Age"
column:

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$result = mysqli_query($con,"SELECT * FROM Persons ORDER BY age");

while($row = mysqli_fetch_array($result))
  {
  echo $row['FirstName'];
  echo " " . $row['LastName'];
  echo " " . $row['Age'];
  echo "<br>";
  }

mysqli_close($con);
?>
The output of the code above will be:

Glenn Quagmire 33
Peter Griffin 35

Order by Two Columns


It is also possible to order by more than one column. When ordering by more than one column, the second
column is only used if the values in the first column are equal:

SELECT column_name(s)
FROM table_name
ORDER BY column1, column2
The UPDATE statement is used to modify data in a table.

Update Data In a Database


The UPDATE statement is used to update existing records in a table.

Syntax
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or
records that should be updated. If you omit the WHERE clause, all records will be updated!
To get PHP to execute the statement above we must use the mysqli_query() function. This function is
used to send a query or command to a MySQL connection.

Example
Earlier in the tutorial we created a table named "Persons". Here is how it looks:

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
FirstName LastName Age
Peter Griffin 35
Glenn Quagmire 33
The following example updates some data in the "Persons" table:

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

mysqli_query($con,"UPDATE Persons SET Age=36


WHERE FirstName='Peter' AND LastName='Griffin'");

mysqli_close($con);
?>
After the update, the "Persons" table will look like this:

FirstName LastName Age


Peter Griffin 36
Glenn Quagmire 33
The DELETE statement is used to delete records in a table.

Delete Data In a Database


The DELETE FROM statement is used to delete records from a database table.

Syntax
DELETE FROM table_name
WHERE some_column = some_value

Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or
records that should be deleted. If you omit the WHERE clause, all records will be deleted!
To get PHP to execute the statement above we must use the mysqli_query() function. This function is
used to send a query or command to a MySQL connection.

Example
Look at the following "Persons" table:

FirstName LastName Age


Peter Griffin 35
Glenn Quagmire 33
The following example deletes all the records in the "Persons" table where LastName='Griffin':

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

mysqli_query($con,"DELETE FROM Persons WHERE LastName='Griffin'");

mysqli_close($con);
?>
After the deletion, the table will look like this:

FirstName LastName Age


Glenn Quagmire 33
ODBC is an Application Programming Interface (API) that allows you to connect to a data source (e.g. an
MS Access database).

Create an ODBC Connection


With an ODBC connection, you can connect to any database, on any computer in your network, as long
as an ODBC connection is available.

Here is how to create an ODBC connection to a MS Access Database: 

1. Open the Administrative Tools icon in your Control Panel.


2. Double-click on the Data Sources (ODBC) icon inside.
3. Choose the System DSN tab.
4. Click on Add in the System DSN tab.
5. Select the Microsoft Access Driver. Click Finish.
6. In the next screen, click Select to locate the database.
7. Give the database a Data Source Name (DSN).
8. Click OK.

Note that this configuration has to be done on the computer where your web site is located. If you are
running Internet Information Server (IIS) on your own computer, the instructions above will work, but if
your web site is located on a remote server, you have to have physical access to that server, or ask your
web host to to set up a DSN for you to use.

Connecting to an ODBC
The odbc_connect() function is used to connect to an ODBC data source. The function takes four
parameters: the data source name, username, password, and an optional cursor type.

The odbc_exec() function is used to execute an SQL statement.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Example
The following example creates a connection to a DSN called northwind, with no username and no
password. It then creates an SQL and executes it:

$conn=odbc_connect('northwind','','');
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);
Retrieving Records
The odbc_fetch_row() function is used to return records from the result-set. This function returns true if it
is able to return rows, otherwise false.

The function takes two parameters: the ODBC result identifier and an optional row number:

odbc_fetch_row($rs)
Retrieving Fields from a Record
The odbc_result() function is used to read fields from a record. This function takes two parameters: the
ODBC result identifier and a field number or name.

The code line below returns the value of the first field from the record:

$compname=odbc_result($rs,1);
The code line below returns the value of a field called "CompanyName":

$compname=odbc_result($rs,"CompanyName");

Closing an ODBC Connection


The odbc_close() function is used to close an ODBC connection.

odbc_close($conn);

An ODBC Example
The following example shows how to first create a database connection, then a result-set, and then display
the data in an HTML table.

<html>
<body>

<?php
$conn=odbc_connect('northwind','','');
if (!$conn)
  {exit("Connection Failed: " . $conn);}
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);
if (!$rs)
  {exit("Error in SQL");}
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
echo "<table><tr>";
echo "<th>Companyname</th>";
echo "<th>Contactname</th></tr>";
while (odbc_fetch_row($rs))
  {
  $compname=odbc_result($rs,"CompanyName");
  $conname=odbc_result($rs,"ContactName");
  echo "<tr><td>$compname</td>";
  echo "<td>$conname</td></tr>";
  }
odbc_close($conn);
echo "</table>";
?>

</body>
</html>
Tasks:
1. Create a shopping website. Use php, css, ajax and javascript.
2. Connect the database classicmodel to your website

Shopping website

SQL creates a product table in the MySQL database.


<?php

CREATE TABLE `product` (

`product_id` int(11) NOT NULL,

`model` varchar(64) NOT NULL,

`sku` varchar(64) NOT NULL,

`quantity` int(4) NOT NULL DEFAULT '0',

`image` varchar(255) DEFAULT NULL,

`price` decimal(15,2) NOT NULL DEFAULT '0.00',

`date_available` date NOT NULL DEFAULT '0000-00-00',

`sort_order` int(11) NOT NULL DEFAULT '0',

`status` tinyint(1) NOT NULL DEFAULT '0',

`date_added` varchar(12) NOT NULL,

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
`date_modified` varchar(12) NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `product`

ADD PRIMARY KEY (`product_id`);

ALTER TABLE `product`

MODIFY `product_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;

?>

SQL creates a product_description table in the MySQL database.


<?php

CREATE TABLE `product_description` (

`product_id` int(11) NOT NULL,

`language_id` int(11) NOT NULL,

`slug` varchar(255) DEFAULT NULL,

`name` varchar(255) NOT NULL,

`description` text NOT NULL,

`tag` text NOT NULL,

`meta_title` varchar(255) NOT NULL,

`meta_description` varchar(255) NOT NULL,

`meta_keyword` varchar(255) NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `product_description`

ADD PRIMARY KEY (`product_id`,`language_id`),

ADD KEY `name` (`name`);

?>
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

SQL creates a product_image table in the MySQL database.


<?php

CREATE TABLE `product_image` (

`id` int(11) NOT NULL,

`product_id` int(11) NOT NULL,

`image` varchar(255) NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `product_image`

ADD PRIMARY KEY (`id`);

ALTER TABLE `product_image`

MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;

?>

SQL creates a orders table in the MySQL database.


<?php

CREATE TABLE `orders` (

`order_id` int(11) NOT NULL,

`invoice_no` varchar(16) DEFAULT NULL,

`invoice_prefix` varchar(26) NOT NULL,

`customer_id` int(11) NOT NULL DEFAULT '0',

`firstname` varchar(32) NOT NULL,

`lastname` varchar(32) NOT NULL,

`email` varchar(96) NOT NULL,

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
`phone` varchar(32) NOT NULL,

`payment_firstname` varchar(32) NOT NULL,

`payment_lastname` varchar(32) NOT NULL,

`payment_company` varchar(60) NOT NULL,

`payment_address` varchar(128) NOT NULL,

`payment_city` varchar(128) NOT NULL,

`payment_postcode` varchar(10) NOT NULL,

`payment_country` varchar(128) NOT NULL,

`payment_state` varchar(100) NOT NULL,

`payment_method` varchar(128) NOT NULL,

`payment_code` varchar(128) NOT NULL,

`comment` text NOT NULL,

`total` decimal(15,4) NOT NULL DEFAULT '0.0000',

`order_status_id` int(11) NOT NULL DEFAULT '0',

`currency_id` int(11) NOT NULL,

`currency_code` varchar(3) NOT NULL,

`currency_value` decimal(15,8) NOT NULL DEFAULT '1.00000000',

`date_added` varchar(12) NOT NULL,

`date_modified` varchar(12) NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `orders`

ADD PRIMARY KEY (`order_id`);

ALTER TABLE `orders`


Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
MODIFY `order_id` int(11) NOT NULL AUTO_INCREMENT;

?>

SQL creates a customer table in the MySQL database


<?php

CREATE TABLE `customer` (

`customer_id` int(11) NOT NULL,

`firstname` varchar(32) NOT NULL,

`lastname` varchar(32) NOT NULL,

`email` varchar(96) NOT NULL,

`phone` varchar(32) NOT NULL,

`password` varchar(40) DEFAULT NULL,

`salt` varchar(9) DEFAULT NULL,

`status` tinyint(1) NOT NULL,

`date_added` varchar(12) NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `customer`

ADD PRIMARY KEY (`customer_id`);

ALTER TABLE `customer`

MODIFY `customer_id` int(11) NOT NULL AUTO_INCREMENT;

?>

Create a model file

Create a model file named “Product_model.php” inside


“application/models” folder.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
/*

To change this license header, choose License Headers in Project Properties.

To change this template file, choose Tools | Templates

and open the template in the editor.

*/

/**

Description of Product Model: CodeIgniter

@author TechArise Team

@email info@techarise.com

*/

if (!defined('BASEPATH'))

exit('No direct script access allowed');

class Product_model extends CI_Model {

private $_productID;

private $_productName;

private $_model;

private $_price;

private $_qty;

private $_subTotal;

private $_slug;

private $_status;

private $_limit;
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
private $_pageNumber;

private $_offset;

private $_orderID;

private $_invoiceNo;

private $_invoicePrefix;

private $_customerID;

private $_firstName;

private $_lastName;

private $_email;

private $_phone;

private $_paymentFirstName;

private $_paymentLastName;

private $_paymentCompany;

private $_paymentAddress;

private $_paymentCity;

private $_paymentPostCode;

private $_paymentCountry;

private $_paymentState;

private $_paymentMethod;

private $_paymentCode;

private $_comment;

private $_total;

private $_orderStatusID;

private $_currencyID;
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
private $_currencyCode;

private $_currencyValue;

private $_timeStamp;

private $_batchData;

public function setProductID($productID) {

$this->_productID = $productID;

public function setProductName($productName) {

$this->_productName = $productName;

public function setModel($model) {

$this->_model = $model;

public function setPrice($price) {

$this->_price = $price;

public function setQty($qty) {

$this->_qty = $qty;

public function setSubTotal($subTotal) {

$this->_subTotal = $subTotal;

public function setSlug($slug) {

$this->_slug = $slug;
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
}

public function setStatus($status) {

$this->_status = $status;

public function setLimit($limit) {

$this->_limit = $limit;

public function setPageNumber($pageNumber) {

$this->_pageNumber = $pageNumber;

public function setOffset($offset) {

$this->_offset = $offset;

public function setOrderID($orderID) {

$this->_orderID = $orderID;

public function setInvoiceNo($invoiceNo) {

$this->_invoiceNo = $invoiceNo;

public function setInvoicePrefix($invoicePrefix) {

$this->_invoicePrefix = $invoicePrefix;

public function setCustomerID($customerID) {

$this->_customerID = $customerID;
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
}

public function setFirstName($firstName) {

$this->_firstName = $firstName;

public function setLastName($lastName) {

$this->_lastName = $lastName;

public function setEmail($email) {

$this->_email = $email;

public function setPhone($phone) {

$this->_phone = $phone;

public function setPaymentFirstName($paymentFirstName) {

$this->_paymentFirstName = $paymentFirstName;

public function setPaymentLastName($paymentLastName) {

$this->_paymentLastName = $paymentLastName;

public function setPaymentCompany($paymentCompany) {

$this->_paymentCompany = $paymentCompany;

public function setPaymentAddress($paymentAddress) {

$this->_paymentAddress = $paymentAddress;
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
}

public function setPaymentCity($paymentCity) {

$this->_paymentCity = $paymentCity;

public function setPaymentPostCode($paymentPostCode) {

$this->_paymentPostCode = $paymentPostCode;

public function setPaymentCountry($paymentCountry) {

$this->_paymentCountry = $paymentCountry;

public function setPaymentState($paymentState) {

$this->_paymentState = $paymentState;

public function setPaymentMethod($paymentMethod) {

$this->_paymentMethod = $paymentMethod;

public function setPaymentCode($paymentCode) {

$this->_paymentCode = $paymentCode;

public function setComment($comment) {

$this->_comment = $comment;

public function setTotal($total) {

$this->_total = $total;
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
}

public function setOrderStatusID($orderStatusID) {

$this->_orderStatusID = $orderStatusID;

public function setCurrencyID($currencyID) {

$this->_currencyID = $currencyID;

public function setCurrencyCode($currencyCode) {

$this->_currencyCode = $currencyCode;

public function setCurrencyValue($currencyValue) {

$this->_currencyValue = $currencyValue;

public function setTimeStamp($timeStamp) {

$this->_timeStamp = $timeStamp;

public function setBatchData($batchData) {

$this->_batchData = $batchData;

// count all product

public function getAllProductCount() {

$this->db->where('status', $this->_status);

$this->db->from('product');

return $this->db->count_all_results();
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
}

// Get all details ehich store in "products" table in database.

public function getProductList() {

$this->db->select(array('p.product_id', 'pd.name', 'pd.slug', 'p.sku', 'p.price', 'p.model',


'pd.description', 'p.image'));

$this->db->from('product as p');

$this->db->join('product_description as pd', 'pd.product_id = p.product_id', 'left');

$this->db->where('p.status', $this->_status);

$this->db->limit($this->_pageNumber, $this->_offset);

$query = $this->db->get();

return $query->result_array();

// get currency code

public function getCurrencyFormat() {

$this->db->select(array('c.currency_id', 'c.symbol_left', 'c.symbol_right', 'c.code', 'c.value',


'c.decimal_place'));

$this->db->from('currency as c');

$this->db->where('c.currency_id', $this->_currencyID);

$query = $this->db->get();

return $query->row_array();

// get resource centre items

public function getProduct() {

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
$this->db->select(array('p.product_id', 'pd.name', 'p.sku', 'p.price', 'p.model', 'pd.slug',
'pd.description', 'p.image'));

$this->db->from('product as p');

$this->db->join('product_description as pd', 'pd.product_id = p.product_id', 'left');

if(!empty($this->_productID)) {

$this->db->where('p.product_id', $this->_productID);

if(!empty($this->_slug)) {

$this->db->where('pd.slug', $this->_slug);

$query = $this->db->get();

return $query->row_array();

public function getProductImage() {

$this->db->select(array('m.id', 'm.product_id', 'm.image'));

$this->db->from('product_image as m');

$this->db->join('product as p', 'm.product_id = p.product_id', 'left');

$this->db->where('p.product_id', $this->_productID);

$query = $this->db->get();

return $query->result_array();

// order now

public function createOrder() {

$data = array(

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
'invoice_no' => $this->_invoiceNo,

'invoice_prefix' => $this->_invoicePrefix,

'customer_id' => $this->_customerID,

'firstname' => $this->_firstName,

'lastname' => $this->_lastName,

'email' => $this->_email,

'phone' => $this->_phone,

'payment_firstname' => $this->_paymentFirstName,

'payment_lastname' => $this->_paymentLastName,

'payment_company' => $this->_paymentCompany,

'payment_address' => $this->_paymentAddress,

'payment_city' => $this->_paymentCity,

'payment_postcode' => $this->_paymentPostCode,

'payment_country' => $this->_paymentCountry,

'payment_state' => $this->_paymentState,

'payment_method' => $this->_paymentMethod,

'payment_code' => $this->_paymentCode,

'comment' => $this->_comment,

'total' => $this->_total,

'order_status_id' => $this->_orderStatusID,

'currency_id' => $this->_currencyID,

'currency_code' => $this->_currencyCode,

'currency_value' => $this->_currencyValue,

'date_added' => $this->_timeStamp,


Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
'date_modified' => $this->_timeStamp,

);

$this->db->insert('orders', $data);

return $this->db->insert_id();

// count Invoice

public function countInvoice() {

$this->db->from('orders');

return $this->db->count_all_results();

// add order product item

public function addOrderItem() {

$data = $this->_batchData;

$this->db->insert_batch('orders_product', $data);

// create customer

public function createCustomer() {

$data = array(

'firstname' => $this->_firstName,

'lastname' => $this->_lastName,

'email' => $this->_email,

'phone' => $this->_phone,

'status' => 1,

'date_added' => $this->_timeStamp,


Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
);

$this->db->insert('customer', $data);

return $this->db->insert_id();

// email validation

public function validateEmail($email) {

return preg_match('/^[^\@]+@.*.[a-z]{2,15}$/i', $email)?TRUE:FALSE;

// mobile validation

public function validateMobile($mobile) {

return preg_match('/^[0-9]{10}+$/', $mobile)?TRUE:FALSE;

?>

Create a controller file

Next create a controller file named “Product.php” inside


“application/controllers” folder.
<?php

/*

To change this license header, choose License Headers in Project Properties.

To change this template file, choose Tools | Templates

and open the template in the editor.

*/

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
/**

@package Product : CodeIgniter

@author TechArise Team

@email info@techarise.com

Description of Product Controller

*/

if (!defined('BASEPATH'))

exit('No direct script access allowed');

class Product extends CI_Controller {

public function __construct() {

parent::__construct();

//load model

$this->load->model('Product_model', 'basket');

$this->load->library('pagination');

$this->load->library('cart');

$this->load->helper('text');

// list product

public function index() {

$data = array();

$data['page'] = 'product-list';
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
$data['title'] = 'Product | TechArise';

$data['breadcrumbs'] = array('Home' => '#');

$this->basket->setCurrencyID(5);

$currencyInfo = $this->basket->getCurrencyFormat();

$data['currency'] = $currencyInfo;

$config['total_rows'] = $this->basket->getAllProductCount();

$page_number = $this->uri->segment(3);

$config['base_url'] = base_url() . 'cart/index/';

if (empty($page_number))

$page_number = 1;

$offset = ($page_number - 1) * $this->pagination->per_page;

$this->basket->setPageNumber($this->pagination->per_page);

$this->basket->setOffset($offset);

$this->pagination->cur_page = $offset;

$this->pagination->initialize($config);

$data['page_links'] = $this->pagination->create_links();

$this->basket->setStatus(1);

$data['products'] = $this->basket->getProductList();

$this->load->view('product/index', $data);

// product description

public function single($slug='') {

$data = array();

$data['page'] = 'product-view';
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
$data['title'] = 'View Product | TechArise';

$data['breadcrumbs'] = array('Home' => site_url(), 'View' => '#');

$this->basket->setSlug($slug);

$data['productInfo'] = $this->basket->getProduct();

$this->basket->setProductID($data['productInfo']['product_id']);

$data['productImage'] = $this->basket->getProductImage();

$this->load->view('product/single', $data);

// quickView

public function quickView() {

$json = array();

$productID = $this->input->post('product_id');

$this->basket->setProductID($productID);

$json['productInfo'] = $this->basket->getProduct();

$this->output->set_header('Content-Type: application/json');

$this->load->view('product/render/view', $json);

?>

Next create a controller file named “Cart.php” inside


“application/controllers” folder.
p

/*

To change this license header, choose License Headers in Project Properties.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
To change this template file, choose Tools | Templates

and open the template in the editor.

/**

@package Cart : CodeIgniter

@author TechArise Team

@email info@techarise.com

Description of Cart Controller

*/

if (!defined('BASEPATH'))

exit('No direct script access allowed');

class Cart extends CI_Controller {

public function __construct() {

parent::__construct();

//load model

$this->load->model('Product_model', 'basket');

$this->load->library('pagination');

$this->load->library('cart');

$this->load->helper('text');

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
public function index() {

$data = array();

$data['page'] = 'shopping-cart';

$data['title'] = 'My Cart | TechArise';

$data['breadcrumbs'] = array('Home' => site_url(), 'Cart' => '#');

$data['productInfo'] = $this->cart->contents();

$this->load->view('cart/index', $data);

public function single() {

$data = array();

$data['page'] = 'shopping-cart';

$data['title'] = 'Shopping Cart | TechArise';

$data['breadcrumbs'] = array('Shopping Cart' => '#', 'List' => '#');

$this->load->view('cart/single', $data);

// product add to basket

function add() {

$json = array();

if (!empty($this->input->post('productID'))) {

$this->basket->setProductID($this->input->post('productID'));

$qty = $this->input->post('qty');

$productInfo = $this->basket->getProduct();

$cartData = array(

'id' => $productInfo['product_id'],


Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
'name' => $productInfo['name'],

'model' => $productInfo['model'],

'price' => $productInfo['price'],

'slug' => $productInfo['slug'],

'qty' => $qty,

'image' => $productInfo['image'],

);

$this->cart->insert($cartData);

$json['status'] = 1;

$json['counter'] = count($this->cart->contents());

} else {

$json['status'] = 0;

header('Content-Type: application/json');

echo json_encode($json);

// remove cart item

function remove() {

$json = array();

if (!empty($this->input->post('productID'))) {

$rowid = $this->input->post('productID');

$data = array(

'rowid' => $rowid,

'qty' => 0
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
);

$this->cart->update($data);

header('Content-Type: application/json');

echo json_encode($json);

// update cart item

function update() {

$json = array();

if (!empty($this->input->post('productID'))) {

$rowid = $this->input->post('productID');

$qty = $this->input->post('qty');

$data = array(

'rowid' => $rowid,

'qty' => $qty

);

$this->cart->update($data);

header('Content-Type: application/json');

echo json_encode($json);

// checkout item

function checkout() {

$data = array();
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
$data['metaDescription'] = 'Shopping Cart';

$data['metaKeywords'] = 'Shopping, Cart';

$data['title'] = "Shopping Cart - TechArise";

$data['breadcrumbs'] = array('Home' => site_url(), 'Checkout' => '#');

$data['productInfo'] = $this->cart->contents();

$this->load->view('cart/checkout', $data);

// order now

public function orderNow() {

$productInfo = $this->cart->contents();

$grandTotal = 0;

$productList = array();

foreach ($productInfo as $key => $element) {

$grandTotal += $element['subtotal'];

$productList[] = array(

'id' => $element['id'],

'name' => $element['name'],

'model' => $element['model'],

'price' => $element['price'],

'qty' => $element['qty'],

'subtotal' => $element['subtotal'],

);

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
$customerID = 0;

$firstname = $this->input->post('firstname');

$lastname = $this->input->post('lastname');

$email = $this->input->post('email');

$phone = $this->input->post('phone');

$company = $this->input->post('company');

$address = $this->input->post('address');

$country = $this->input->post('country');

$state = $this->input->post('state');

$city = $this->input->post('city');

$zipcode = $this->input->post('zipcode');

$timeStamp = time();

// firstname validation

if(empty(trim($firstname))){

$json['error']['firstname'] = 'Please enter first name';

// firstname validation

if(empty(trim($lastname))){

$json['error']['lastname'] = 'Please enter last name';

// email validation

if(empty(trim($email))){

$json['error']['email'] = 'Please enter email address';

}
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
// check email validation

if ($this->basket->validateEmail($email) == FALSE) {

$json['error']['email'] = 'Please enter valid email address';

// check conatct no validation

if($this->basket->validateMobile($phone) == FALSE) {

$json['error']['phone'] = 'Please enter valid contact no. format: 9000000001';

// company validation

if(empty($company)){

$json['error']['company'] = 'Please enter company';

if(empty($address)){

$json['error']['address'] = 'Please enter address name';

if(empty($address)){

$json['error']['address'] = 'Please enter address';

if(empty($country)){

$json['error']['country'] = 'Please enter country';

if(empty($state)){

$json['error']['state'] = 'Please enter state';

}
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
if(empty($city)){

$json['error']['city'] = 'Please enter city';

if(empty($zipcode)){

$json['error']['zipcode'] = 'Please enter zipcode';

if(empty($json['error'])){

$this->basket->setFirstName($firstname);

$this->basket->setLastName($lastname);

$this->basket->setEmail($email);

$this->basket->setPhone($phone);

$this->basket->setTimeStamp($timeStamp);

// create customer

$customerID = $this->basket->createCustomer();

$this->basket->setCustomerID($customerID);

$countInvoice = $this->basket->countInvoice();

$fullInvoice = 'INV-' . str_pad($countInvoice + 1, 4, '0', STR_PAD_LEFT);

$this->basket->setInvoiceNo($fullInvoice);

$this->basket->setInvoicePrefix('INV');

$this->basket->setPaymentFirstName($firstname);

$this->basket->setPaymentLastName($lastname);

$this->basket->setPaymentCompany($company);

$this->basket->setPaymentAddress($address);

$this->basket->setPaymentCity($city);
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
$this->basket->setPaymentPostCode($zipcode);

$this->basket->setPaymentCountry($country);

$this->basket->setPaymentState($state);

$this->basket->setPaymentMethod('COD');

$this->basket->setPaymentCode('COD');

$this->basket->setComment('note');

$this->basket->setTotal($grandTotal);

$this->basket->setOrderStatusID(1);

$this->basket->setCurrencyID(1);

$this->basket->setCurrencyCode('USD');

$this->basket->setCurrencyValue('0.000000000');

try {

$last_id = $this->basket->createOrder();

} catch (Exception $e) {

var_dump($e->getMessage());

if(!empty($last_id)) {

foreach ($productList as $key => $element) {

$batch[] = array(

'order_id' => $last_id,

'product_id' => $element['id'],

'model' => $element['model'],

'quantity' => $element['qty'],

'price' => $element['price'],


Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
'total' => $element['subtotal'],

);

$this->basket->setBatchData($batch);

$this->basket->addOrderItem();

$this->session->unset_userdata('cart_contents');

if (!empty($last_id) && $last_id > 0) {

$orderID = str_pad($last_id, 4, '0', STR_PAD_LEFT);

$json['order_id'] = $orderID;

$json['status'] = 'success';

$this->output->set_header('Content-Type: application/json');

echo json_encode($json);

// checkout item

function success() {

$data = array();

$data['metaDescription'] = 'Shopping Cart';

$data['metaKeywords'] = 'Shopping, Cart';

$data['title'] = "Shopping Cart - TechArise";

$data['breadcrumbs'] = array('Home' => site_url(), 'Success' => '#');

$order_id = $this->input->get('order_id');
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
$data['order_id'] = $order_id;

$this->load->view('cart/success', $data);

?>

Output :

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

Note: Attach a snap shot of every above mentioned task.

Learning outcomes:

In this lab we have covered about integrating web page and MY SQL using PHP & SQL Database

systems, this lab made us to do live time connection of database with web pages.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

Lab # 13
Cookies and Sessions
Objective

 In this lab you will learn about integerating web page and MY SQL
 A cookie is often used to identify a user.

Theory
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's
computer. Each time the same computer requests a page with a browser, it will send the cookie too. With
PHP, you can both create and retrieve cookie values.

How to Create a Cookie?


The setcookie() function is used to set a cookie.

Note: The setcookie() function must appear BEFORE the <html> tag.

Syntax
setcookie(name, value, expire, path, domain);
Example 1
In the example below, we will create a cookie named "user" and assign the value "Alex Porter" to it. We
also specify that the cookie should expire after one hour:

<?php
setcookie("user", "Alex Porter", time()+3600);
?>
<html>
Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically
decoded when received (to prevent URLencoding, use setrawcookie() instead).

Example 2
You can also set the expiration time of the cookie in another way. It may be easier than using seconds.

<?php
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
?>
<html>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours * 30 days).

How to Retrieve a Cookie Value?


The PHP $_COOKIE variable is used to retrieve a cookie value. 

In the example below, we retrieve the value of the cookie named "user" and display it on a page:

<?php
// Print a cookie
echo $_COOKIE["user"];

// A way to view all cookies


print_r($_COOKIE);
?>
In the following example we use the isset() function to find out if a cookie has been set:

<html>
<body>

<?php
if (isset($_COOKIE["user"]))
  echo "Welcome " . $_COOKIE["user"] . "!<br>";
else
  echo "Welcome guest!<br>";
?>

</body>
</html>
How to Delete a Cookie?
When deleting a cookie you should assure that the expiration date is in the past.

Delete example:

<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>
What if a Browser Does NOT Support Cookies?
If your application deals with browsers that do not support cookies, you will have to use other methods to
pass information from one page to another in your application. One method is to pass the data through
forms (forms and user input are described earlier in this tutorial).

The form below passes the user input to "welcome.php" when the user clicks on the "Submit" button:

<html>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
<body>

<form action="welcome.php" method="post">


Name: <input type="text" name="name">
Age: <input type="text" name="age">
<input type="submit">
</form>

</body>
</html>
Retrieve the values in the "welcome.php" file like this:

<html>
<body>

Welcome <?php echo $_POST["name"]; ?>.<br>


You are <?php echo $_POST["age"]; ?> years old.

</body>
</html>

A PHP session variable is used to store information about, or change settings for a user session. Session
variables hold information about one single user, and are available to all pages in one application.

PHP Session Variables


When you are working with an application, you open it, do some changes and then you close it. This is
much like a Session. The computer knows who you are. It knows when you start the application and when
you end. But on the internet there is one problem: the web server does not know who you are and what
you do because the HTTP address doesn't maintain state.

A PHP session solves this problem by allowing you to store user information on the server for later use
(i.e. username, shopping items, etc). However, session information is temporary and will be deleted after
the user has left the website. If you need a permanent storage you may want to store the data in a
database.

Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The
UID is either stored in a cookie or is propagated in the URL.

Starting a PHP Session


Before you can store user information in your PHP session, you must first start up the session.

Note: The session_start() function must appear BEFORE the <html> tag:

<?phpsession_start(); ?>

<html>

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
<body>

</body>
</html>
The code above will register the user's session with the server, allow you to start saving user information,
and assign a UID for that user's session.

Storing a Session Variable


The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:

<?php
session_start();
// store session data
$_SESSION['views']=1;
?>

<html>
<body>

<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>

</body>
</html>
<?php
session_start();
// store session data
$_SESSION['views']=1;
?>

<html>
<body>

<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>

</body>
</html>

Output:

Pageviews=1

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
In the example below, we create a simple page-views counter. The isset() function checks if the "views"
variable has already been set. If "views" has been set, we can increment our counter. If "views" doesn't
exist, we create a "views" variable, and set it to 1:

<?php
session_start();

if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>

Destroying a Session
If you wish to delete some session data, you can use the unset() or the session_destroy() function.

The unset() function is used to free the specified session variable:

<?php
session_start();
if(isset($_SESSION['views']))
  unset($_SESSION['views']);
?>
You can also completely destroy the session by calling the session_destroy() function:

<?php
session_destroy();
?>
Note: session_destroy() will reset your session and you will lose all your stored session data.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Task:

Q1. Create a login form that stores the username and password in a cookie. If remember me check is not
enabled than delete the cookie on logout.
Output with Form.php Code:

Output with Cookie.php Code:

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

Note: Attach a snap shot of every above mentioned task.

Learning outcomes:

Upon the completion of this lab we have learnt that what is the Cookie? And how a Cookie is often used

to identify the users in Web Pages.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
Lab # 14
Site Building with Photoshop and Dream weaver
Objective:

 In this lab you will learn how to Create Website using Dream weaver and Photoshop.
.

Theory:
Create a website header using Photoshop:

We are going to make a header like the banner below:

Steps to Follow :

1. Save above picture in a website folder.


2. Open Photoshop and click on File/Open and select the header image from your website folder.
3. Name the layer header in the layers panel. Right click on the layer and select Duplicate Layer.
Name the second layer candle.

4. Click on layer header and press shift+ctrl+u to desaturate the picture. You won't be able to see
the desaturation as the layer is behind the candle layer. You can close the eye of the candle
layer in the layers panel if you would like to view the effect of the desaturation.

5. Now work on the candle layer. Select Elliptical marquee tool. Drag it to the candle. Select
feather radius as 15.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University

6. Now click on Select>Inverse from the top menu and then delete.

7. Now press ctrl+D to deselect the candle. Make a new layer called candleborder on top of the
candle layer. Use the line tool to create a vertical line on the left and on the right of the lit
candle.

The above is the final effect you will create.

If you would like to use this header on creating a website layout, You have to merge the layers to
create a single graphic. You need to do the following steps :

1. Click on the link icon next to the eye icon in the layers panel for all the layers.

2. Go to Layers>Merge Linked.

Your header is ready to insert in the layout.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
We have designed a layout with a black background with an area for the logo, an eye-catching
graphical header, navigation links, content and images.

Remember while designing your layout, you need to define spaces for the following :

 Header - This could be a graphic banner


 Logo
 Buttons - Links for home, about us, contact us etc.
 Pictures
 Content area
 Copyright Information

Follow the following steps to design your website layout in Photoshop:

1. Open a new file in Photoshop by clicking on File/New and enter a width of 750pixels and height
of 450px.

2. Color the background with Black by choosing black in the foreground color and
selecting the paint bucket tool and click on the canvas. Your background will now be black.
3. Add a new layer by clicking on the Add Layer icon in the Layers panel. If your Layers panel is not
open then go to Window/Layers. Name the new layer copyright . Select Rectangle
Marquee Tool and drag to make the bottom banner with a width of 750pixels by 21 pixels.
Color this banner with color #303030.
4. Choose Horizontal Type Tool. A text layer is created automatically. Now enter the text for
Copyright, e.g. "Copyright © 2005 www.YourWebBusiness.com. All Rights Reserved.

5. Choose Horizontal Type Tool. A text layer appears automatically. Enter the button text
on the top banner too: "home l sitemap l news l downloads".
6. Add a new layer. Now make the gray horizontal line color #808080 with single Marquee
tool.Go to Edit>Stroke. Choose Stroke width 1 pixel. Color #808080. Location Center. Click
OK.

7. Right click on the layer and select duplicate layer 3 times, because you have 4 lines. Put the lines
in their corresponding place: in bottom, middle, top.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
8. Now you can enter the button text on the second top banner in a new layer e.g. About us l
services l products l clientele l contact us.
9. Now define the logo area with the rectangular marquee tool. Go to Edit>Stroke. Choose
Stroke width 1 pixel. Color is #808080. Location Center. Fill inside with Black color with Paint
tool. Name it Logo area.
10. Choose the Horizontal Type Tool and write your company name or website name.
11. Choose the Horizontal Type Tool and enter content in the middle.
12. Insert your header. This could also be any image you choose. The image needs to be a horizontal
banner. Open your image file. Go to move tool. Drag from your image file to this layout in the
middle of the layout.
13. Draw the boxes seen on the right with the Polygonal Lasso Tool.

Go to Edit>Stroke. Choose Stroke width 1 pixel. Color is


#808080. Location Center.
Name your layer borderpics. Make two more Boxes. Adjust them equally in the right side of the
layout. Insert the images by dragging them to your layout and naming the layers.
14. Drag the layer borderpics on top of the 3 pic layers. The edges of the pictures have to be cut
according to the design of the box.
15. Now create the white bands with text at the bottom of each of the right graphics with the
rectangle marquee tool. Fill the box with white color with Paint tool. Name it "whitebandpics".
Choose the Horizontal Type Tool. A text layer is created automatically. Now enter the text for
Gifts. Follow the same for the rest of the pictures. You can click here for the images - pic1, pic2,
pic3. You can drag these images to your layout.

Now when your design is ready, you can go to the next step to creating your website which is to
make slices.

Slice your layout and export images using Photoshop

We need to slice the layout to save the necessay images in web format and use them in
html.Follow these steps to slice your layout.
Hamdard Institute of Engineering & Technology, Hamdard University
Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
1. Open the file you want to slice clicking on File>Open. You can open the above layout.
Important : You have to organize your layout in such a way that you should be able to
put them into rows and columns in a table in Dreamweaver.
You can write down how you are going to slice your layout to get the idea. Anything that
is text and backround colors can be done easily in Dreamweaver. Only images and
graphis have to be sliced in Photoshop.
2. Here we will slice only 3 images i.e. the logo, banner and the graphics on the right. Now you can

start to slice your layout. Select the slice tool and draw a box to define the area you want
to slice. We will first create a slice for the logo. Next, use the slice tool again to drag across the
banner and create the next slice. Repeat for the graphics found on the right with the dotted line.
Create one slice for all the 3 images.
3. Next, we will name the slices. Go to the slice tool in the menu palette and select the Slice Select
Tool. Now double click on the slice. A screen named Slice Options will come. Enter the
type of the slice, as an image and name of the slice. For the logo slice, give the name logo.
Repeat this step to name the banner slice and the graphics slice. You can name them banner
and pic_right.
4. Go to File > Save for web. A screen named Save for web will come. Select the logo slice and
choose gif from the drop down menu. next, select the banner and pic_right slices and select
JPEG and maximum from the drop-down menus.
Tip : Remember photographs should always be exported as JPEG and solid colors can be
exported in .GIF formats Adaptive Colors 256.
5. Now the slices are ready to be exported. Select the 3 sliced images in the save for web pop-up
box by using the shift key. Click on Save.
6. A screen named Saved Optimized As will appear. Save your slices in your website folder. Make
sure your image file is in the same path as your work file. Choose the following options for the
rest of the options:
Save as type: Choose Images Only
Slices: Choose selected slices.

Now click on Save. Check that the 3 images have been saved in the images folder in your web
site folder

Creating website on dreamweaver

Let's get started with creating your website in Dreamweaver. The final and most important step!

1. Open Dreamweaver.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
2. Go to File>Site>New site. A big screen named Site definition will open where you have to give
all the instructions for your site.

Site Definition Screen.


o In the first screen you need to give a name to your site. Click Next.
o Select No, I do not want to use a server technology. Click Next.
o In the third screen, Editing Files Part 3, select your website folder using the folder icon.
Click Next. This is the folder that contains your site images and .psd file.
o In the next screen, "How do you connect to the remote server?" choose None from the
drop-down menu. Click Next.
o You will be able to view your site summary. Click on Done.
3. Now you are ready to work on your site. Create a file called my-layout.html in Dreamweaver by
clicking on File/New.

Important: You need to visualize and organize your layout in such a way that you should be
able to put them into rows and columns in a table in Dreamweaver.
4. Open my-layout.html. Click on Insert/Table to insert a table in your web page. Enter The
following :
Rows : 7
Columns : 1
Table Width : 750 pixels
Border Thickness : 0
Cell Padding : 0
Cell Spacing : 0

5. Now follow these steps :

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
 Select the table and give 750 px and background as black in the Properties panel.

 Keep your cursor in the first row and set the height as 21 pixels and choose Right from the
Horz drop-down menu in the properties instructor. Enter the text Home | Sitemap | News |
Downloads. Select the text and choose font Verdana size 10 pixels and color white in the
Properties panel. Dreamweaver will automatically create a style called style 1. We will use this
style for the rest of the links also.
We have entered 5 spaces between the links and the vertical bar. Tip: You can enter spaces by
clicking on shift+Ctrl+Space.

 For the thin line effect in Dreamweaver, keep your cursor in the second row and set the height
1 pixel and insert a spacer by choosing it from your images folder (Insert/Image). Save Spacer
Image in your images folder. Give a gray background color #808080.

 Bring your cursor to the third row and enter a height of 78 pixels in the properties panel.
Now we will insert another table (Insert/Table) with 1 row and 3 columns so that the
logo is inserted in the left and the navigation links are inserted on the right.
Column 1: Give a width of 12 pixels. This is so that the logo does not stick to the edge
of the page.
Column 2: Insert the logo image by clicking on Insert/Image and selecting logo.jpg
from the images folder.
Column 3: Enter About Us | Services | Products | Clientele | Contact Us. Select the text
and choose style 1 from the style drop-down menu. You should get the same style as the
top navigation links - Verdana size 11 pixels and color white.
 Bring your cursor to row 4 and give a height of 103px. Select Insert/Image and choose
banner.jpg from the images folder and click on ok. Your banner will be inserted here.
 Bring your cursor to row 5 and insert a table with 1 Row and 2 Columns.
Column 1: Insert a table with cell padding of 20 pixels. Your content will be inserted here. Give a
font style for the content - Font: Verdana Size : 12 pixels Color : white.
Column 2: Give a width of 167 px and insert the graphics on the right by clicking on
Insert/Image and choosing pic_right.jpg from the images folder.
 Row 6: Repeat steps of row 2 to get the thin gray line.
 Last and final row : Give the b background color as #303030 and height as 21 pixels. Enter your
copyright text and choose style 1 from the style drop-down menu in the Properties instructor.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
Hamdard Institute of Engineering & Technology
Hamdard University
To preview your website in the browser, press F12.

Task:
Q1. Make a simple layout on Photoshop and then export on dream weaver.

The Screenshot of a simple layout on Photoshop and being exporting on dream weaver is
attached above.

Learning outcomes:

In this lab we got the knowledge of that how to Create Website using Dream weaver and Photoshop and

how the layouts made on Photoshop(PS) can be exported in the dreamweaver for a web pages.

Hamdard Institute of Engineering & Technology, Hamdard University


Sharae Madinat Al-Hikmah, Muhammad Bin Qasim Avenue, Karachi 74600, Pakistan.

You might also like