You are on page 1of 393

Defining Internet Programming

What is Internet What is not Internet


Programming? Programming?
 Internet programming entails  The following should not
the following: be considered internet
 Technologies that support programming:
Web based applications
 Low level network
 Client side programming programming
 Server Side Application  Socket level programming
Programming  Implementing Network
 Database driven applications Protocols
 Common Web Based design  TCP/IP, UDP
patterns  Client side Graphical User
Interfaces
Technologies that support Web based
applications
 Most technologies that facilitate web based applications
are based on open standards, thus enabling a wide variety
of users and programmers to get involved in their
utilization to create and exchange web applications.
 These technologies based on open standards include:
 Browsers- these are able to interpret HTML, JavaScript, e.t.c.
 Network Protocols- TCP/IP, HTTP, FTP etc
 Servers-Web Servers, Server side programming environments
 Operating Systems-Linux, BSD unix, GNU software
Client-side programming
 This entails writing scripts that are executed on the client by the
user agent (an application software that can interpret HTML pages
e.g. a web browser).
 Client side programming can be considered as consisting of:
 Browser Based Clients programs- these include those based on HTML +
DHTML.
 The browser is used to execute these.
 Applets- these are small java applications that require a java based web
browser to execute.
 The applets are run in a secure environment with no access to files in the host
system.
 Application Based Client programs- these are for programs that have full
access to the host machine.
 Are classified as heavy (fully rely on facilities of local system to function) or
light (partially rely on facilities of local system to function).
Server-side Application Programming
 This entails writing scripts that execute on the server then
return results to clients. Server side programming involves
the use of:
 Web servers- e.g. Apache, Netscape Application Server, IIS
server etc. that run CGI scripts; CGI programming
environments e.g. server api, perl, php, asp
 Application Servers- e.g. Sun ONE J2EE server, BEA Weblogic,
IBM Websphere, tomcat, jboss, jonas etc. for supporting
application logic e.g. in a three-tier architecture.
Database-driven Applications
 These are internet applications that are supported by a data
base backend and posses the following advantages:
 Up to date web content
 Ease of Management
 Flexibility in Delivery- supports multiple output formats e.g.
when queried
 Individualised Web Content
Common Web-based Design Patterns
 Most internet applications are centered around the concepts
of Shopping Carts, Session Façade , Model-View-
Controller ,Web Services, and User Login.
Origins of Internet
 J.C.R. Licklider of MIT in August 1962 wrote about the Galactic
Network concept
 Became first head of Computer Research Program at DARPA
(Defense Advanced Research Projects Agency) and convinced his successors
about the importance of the project
 Leonard Kleinrock at MIT published the first paper and book in
packet switching theory in 1961 and 1964, respectively.
 Kleinrock convinced Laurence G. Roberts of the theoretical
feasibility of the project.
 In 1966, Roberts went to DARPA and started development on
ARPANET
 ARPANET grew to become the Internet we know today
Internet Timeline: 1970s
 1971: 15 nodes (23 hosts) all at US locations
 1972: Ray Tomlinson modifies email program for use on
ARPANET; it becomes a big hit
 1973: First international connections to ARPANET (England
and Norway)
 1976: Elizabeth II sends email
 1979: USENET (Newsgroups) established
 1979: Scott Fahlman suggests use of emoticons, :-) and :-(
Internet Timeline: 1980s
 1983: ARPANET split into ARPANET (civilian) and MILNET
(military)
 1983: Berkley UNIX Desktop OS includes IP networking
software
 1984: Domain Name System (DNS) introduced
 1985: File Transfer Protocol (FTP) introduced
 1987: Number of hosts exceeds 10,000
 1988: Morris Worm
 1989: 100,000 hosts
Internet Timeline: 1990s
 1990: ARPANET ceases to exist
 1990: Tim Berners-Lee (CERN) invents HTTP and
implements server and browser
 1992: Jean Armour Polly: surfing the Internet
 1993: NCSA Mosaic takes the Internet by storm
 1994: Pizza Hut takes orders online
 1995: Sun launches Java (including applets)
 1995: Netscape introduces LiveScript (JavaScript)
 1996: Beginning of Browser Wars (Mosaic vs. Netscape then
later Netscape vs. Microsoft)
Internet Timeline: 1990s (2)
 1996: US Telecoms lobby to ban Internet phones
 1997: Domain business.com sells for $150,000
 1998: Network Solutions registers 2,000,000th domain name
 1999: A forged web page raises stocks of small technology
company by 31% in one day
 1999: US DoD requires all military systems to connect via
NIPRNET, not directly to Internet
 1999: Napster popularizes peer-to-peer file sharing
Internet Timeline: 2000s
 2000: A massive DoS attack is launched against Yahoo,
Amazon, and eBay
 2000: Code Red worm and Sircam virus infect thousands of
web servers and email accounts
 2002: Weblogs (blogs) become hip
 2003:Year of viruses and worms: Slammer, Sobig.F, and
Blaster
Internet Timeline: Today
 Most widely-used Internet protocol: HTTP
 Highest bandwidth consumption: Peer-to-peer file sharing
protocols
 Most popular web browsers (April 2012)

Internet
2013 Firefox Chrome Safari Opera
Explorer
April 12.7 % 27.9 % 52.7 % 4.0 % 1.7 %
Summary of Internet History
 Internet started out as US DoD project (ARPANET)
 Major Internet Protocols and Formats
 Email (1973)
 Newsgroups (1979)
 File Transfer Protocol (1985)
 Archie, Gopher (1990s)
 Hypertext Transfer Protocol (HTTP – 19 90,1993)
 Hypertext Markup Language (HTML – 199 3)
 Real Simple Syndication (RSS - 1999)
 Major additions to HTTP and HTML
 Java (1995), JavaScript (1995), Flash and Shockwave(1996)
Online References
 The Internet Society History Page
 http://www.isoc.org/internet/history/
 Hobbes' Internet Timeline
 http://www.zakon.org/robert/internet/timeline/
 Browser Statistics
 http://www.w3schools.com/browsers/browsers_stats.asp
What is the internet?
 The Internet or the Net is a collection of computers; all
linked together, to share information globally.
Internet Protocols
 In a network, standards are needed for data representation,
signaling, authentication, error detection etc.
 In ARPANET, the network itself handled communication
protocols using NCP (Network Control program).
 This made ARPANET highly incompatible with other networks.
 In 1983, NCP was replaced by TCP/IP (Transfer Control
Protocol/ Internet Protocol).
 In TCP/IP the hosts are responsible for protocols.
Internet Protocol Suite
OSI model
 Application layer. Used by “network aware” programs to
communicate with other programs
 HTTP, SMTP, FTP, Telnet, ssh, …
 Transport layer. Ensures data arrives at destination and provides
reliability checks
 TCP
 Network layer. Determines how nodes in a network are defined.
 IP
 Data link layer. Specifies how packets are transport over the physical
layer.
 Ethernet, ISDN, WiFi
 Physical layer. The hardware that transports the data.
 Wire, radio, fibre optic
THE WORLD WIDE WEB (WWW)
Overview of WWW
 Hypertext
 A hypertext document is a text file with control instructions to cross reference with other
documents, or perform some action - “branch or perform on request” (Nelson 1970).
 Early implementations (eg Apple’s Hypercard) worked fine on non-networked computers.
But these couldn’t be used to refer to documents distributed over a network.
 World Wide Web (1990s)
 Tim Burners-Lee worked out how to use hypertext over networks. Three key inventions:
 URL: Uniform Resource Locator
 HTTP:Hypertext Transfer Protocol
 (HTML:Hypertext Mark-up Language)
 W3C
 World Wide Web Consortium. Based at MIT, USA.
 The consortium produces “recommendations” for the WWW e.g., if there are some
incompatible HTML versions from different vendors.
 W3C aims to get everyone to agree to common standards.
 Standards are crucial to effective internet programming.
Web Technologies
 Browsers
 User Friendly Browsers- NCSA Mosaic, Netscape, MS Internet Explorer (free), Safari
(Mac OS X), Eudora, Mosaic, Lynx e.t.c.
 Search Engines
 Excite, Lycos,Yahoo, Google, etc.
 Java
 Language built for the Internet.
 Characterised by a security model and can be used to write both applets and applications
in addition to server side programming.
 Linux
 Redhat, Suse, etc
 Opensource software
 GNU tools, Apache, MySQL, PostgresSQL, Jboss, Jonas
 e-Commerce
 Online business- Business 2 Business, Business 2 Consumer e.g. Amazon, eBay etc
Points to Remember
 Early government funding.
 Research projects commercialized.
 Big business backing of Internet and technologies
 Rapid growth in users and connectivity
 Importance of standards in internet programming
Understanding the Web
 I'd describe the World Wide Web as a global,
interactive, dynamic, cross-platform, distributed,
graphical hypertext information system that
runs over the Internet.
The Web is a Hypertext Information
System
 hypertext. The idea behind hypertext is that instead of reading text in
a rigid, linear structure (such as a book), you can skip easily from one
point to another.You can get more information, go back, jump to other
topics, and navigate through the text based on what interests you at the
time.
 Hypertext information doesn't take up much disk space, mostly
freely available, and you could get it reasonably quickly anytime
you wanted.
 That's just what the World Wide Web is: more information than
you could ever digest in a lifetime, linked together in various
ways, out there on the Net, available for you to browse whenever
you want. It's big, and deep, and easy to get lost in. But it's also an
immense amount of fun.
The Web Is Graphical and Easy To
Navigate
 One of the best parts of the Web, and arguably the reason it
has become so popular, is its ability to display both text and
graphics in full color on the same page.
 The Web provides capabilities for graphics, sound, and video
to be incorporated with the text, and newer software
includes even more capabilities for multimedia and
embedded applications.
 More importantly, the interface to all this is easily navigable
 just jump from link to link, from page to page, across sites and
servers.
The Web is Cross-Platform
 If you can access the Internet, you can access the World Wide
Web regardless of whether you're running on an Internet
enabled Kabambe phone, Smartphone, low-end pc, a fancy
expensive graphics workstation, or a multimillion-dollar
mainframe.
 The World Wide Web is not limited to any one kind of
machine, or developed by any one company.
 The Web is entirely cross-platform.
 All you need is a browser, like Mozilla’s Firefox or Microsoft's
Internet Explorer.
The Web is Distributed
 The Web is successful in providing so much information
because that information is distributed globally across
thousands of Web sites (a location on the Web that publishes
some kind of information), each of which contributes the
space for the information it publishes.
 You, as a consumer of that information, go to that site to view the
information. When you're done, you go somewhere else, and your
system reclaims the disk space.You don't have to install it, or change
disks, or do anything other than point your browser at that site.
 Each Web site, and each page or bit of information on that site, has a
unique address.
 This address is called a Uniform Resource Locator, or URL.
The Web is Dynamic
 Information on the Web is contained on the site that
published it
 the people who published it in the first place can update it at
any time.
 For some sites, the ability to update the site on the fly at any
moment is precisely why the site exists.
Browsers Can access Many Forms of
Internet Information
 There are dozens of different ways of getting at information
on the Net: FTP, Gopher, Usenet news, WAIS databases,
Telnet, and e-mail.
 Before the Web became as popular as it is now, to get to these
different kinds of information you had to use different tools for each
one, all of which had to be installed and all of which used different
commands.
 Although the Web itself is its own information system, with
its own Internet protocol (HTTP, the HyperText Transfer
Protocol), Web browsers can also read files from other
Internet services.
 And, even better, you can create links to information on those
systems just as you would create links to information on Web pages.
It's all seamless and all available through a single application.
The Web is Interactive
 Interactivity is the ability to "talk back" to the Web server.
 More traditional media such as television (before digital TV) isn't
interactive at all; all you do is sit and watch as shows are played at
you. Other than changing the channel, you don't have much control
over what you see.
 The Web is inherently interactive; the act of selecting a link
and jumping to another Web page to go somewhere else on
the Web is a form of interactivity. In addition, the Web
enables you:
 to communicate with the publisher of the pages you're reading and
with other readers of those pages e.g. using forms
 To get entertained by playing games
 To run complete programs from within web pages,
 to engage in real time chat e.t.c
BENEATH THE WEB
Uniform Resource Locator (URL)
 Standardized address name for resources (documents,
images, …) on the WWW.
 A URL has two parts:
 [protocol scheme] :// [target]
 e.g: http://www.jkuat.ac.ke, ftp://sysadmin.jkuat.ac.ke
Uniform Resource Identifier
 A URI is a generalized protocol element that refers to a
resource on the internet.
 It can be a name, locator, or both.
 A URL is a type of URI that provides the location of a
resource together with the means (http, ftp, …) of accessing
it.
 A URN (Uniform Resource Name) is a URI that identifies a
resource namespace, without specifying where or how it is
located.
Hypertext Transfer Protocol (HTTP)
 An application layer protocol in the internet protocol suite.
 http is a request/response protocol between clients and servers.
 Clients: usually browsers
 Web servers: software program that (usually) works as a daemon
listening to requests from clients and serving up the web
documents.
 Stateless Protocol- Server does not remember client state
between connections
 Request-response format
 HTTP/1.1 add persistent
HTTP Variations
 HTTPS:
 Secure version of HTTP.
 Encrypts the session using SSL (Secure Socket Layer) or TLS
(Transport Layer Security) protocols
 HTTP proxy:
 Clients on a network, indirectly connect to servers on the
internet via a middleman proxy server network.
Loading a web page
 What happens when I ask a
browser to load something
like
http://www.massey.ac.nz
/~jabond/index.html ?
Sending the Request
 Client makes connection to server- If port not specified,
default is port 80
 Request must specify a URL- Universal Resource Location
 Structure of Request
 Request method + e-mail like message
Client Request
Server Response
 Server waits for request string and then sends back a
response string
 Response string format:
 a status line plus an e-mail like message.
 The message comprises headers plus the document body
 The browser extracts the response body and displays it to the
users
Server Response (2)
Main HTTP Request Types
 OPTIONS - Request for communication options available for
the Request-URI.
 GET - Retrieve an entity requested in the Request-URI.
 HEAD - Identical to GET but no message-body.
 POST - Providing a block of data
 PUT - Store the supplied Request-URI.
 DELETE - Delete the resource identified by the Request-
URI.
 TRACE
 CONNECT
Examples of Status Lines
 200 OK
 404 Not Found
 301 Moved Permanently
 302 Moved Temporarily
 303 See Other (HTTP 1.1 only)
 500 Server Error
 501 Not Implemented
MIME Types
 Multipurpose Internet Mail Extensions- Specifies the file
format to follow e.g. text/html, image/jpg, application/pdf
 Your server side application must specify the correct MIME
type it is delivering
LECTURE 2:
WEB DESIGN AND HTML
Contents
 The Process of Web Design
 History of HTML
 Structure of an HTML Document
 DOCTYPE
 HEAD
 BODY
 HTML Tags
 Paragraphs and Headings
 Lists and tables
 Hyperlinks
 Conclusions and Guidelines
Web Design
The Process of Web Design
 Consider web design under the following:
1) From Concept to Execution
2) Building an Outline
3) Converting your Outline into a Site Map
4) Navigation Design
5) Click-Through Prototype
1) From Concept to execution
 Involves five activities
 Concept
 Architecture
 Design
 Execution
 Testing
a) Concept
 A website is like a meal -- get the taste wrong and they won't
come back. It's the customers who are important ... not the
cooks!
 Define the audience of the site (scope); e.g. children, stock traders,
...
 educational level, special needs , vocabulary , interaction style e.g. button
sizes
 Determine what the site is supposed to do (goals); e.g. inform,
entertain, ...
 use of animation , use of charts and diagrams , balance of text vs graphics ,
 Define how big the site needs to be (size);
 Two examples: http://www.yahooligans.com/ and
http://www.fidelity.com/, Oh, and a 3rd: http://www.mazda.ca/
b) Architecture
 Map the site out on a piece of paper
 Define the navigation structure of the web site
 Determine what technologies to use
c) Design
 Design centering
 Organization-centered
 Technology-centered
 User-centered
 With a good idea of the site's goals and structure, put a
"face" on the site
 Assemble user interface and navigation ideas
Design : Organization-centered
 Web site built from the point of view of the group that
is publishing the site.
 Structure: reflects organizational chart
 Vocabulary: language used by executives
 Content: similar to internal documents
 Example: hospital site is a table with links to Audiology,
Nephrology, podiatry, etc.
 Words mean something to the professionals, not the
average user
Design: Technology-centred
 Starts with particular set of tools
 Site built around the tools
 Example:
 use Flash, use database,
 use Active Server Pages with forms
 For a hospital site designed by multimedia expert, the Site would contain
interviews with doctors, live video stream from OR, etc
 User-centered
 Starts with target audience
 Designer defines who the visitors will be
 studies visitors to figure out what they need and how they work
 presents site in terms that the visitor can understand and in a
structure that mirrors the way that they think.
Design: User-centred
 Starts with target audience
 Designer defines who the visitors will be
 studies visitors to figure out what they need and how they work
 presents site in terms that the visitor can understand and
in a structure that mirrors the way that they think.
d) Execution
 Begin production (up to this point you are only allowed
to do a mock-up)
 Includes graphics, HTML, media, and content
e) Testing
 No web site should go "live" without being thoroughly tested
 Check for things like:
 Bugs in your code, Links that go to the wrong pages and
Spelling errors
 Also make sure the web site works on different browsers
People involved in building a website
 Besides you, the programmer, many players are involved:
 Marketing (big picture), Producers (funding) , Designers
(navigation and user interface) , Media specialists (logos,
animations, and such) , HTML coders (HTML)
 Programmers make the web site dynamic (that is,
automated)
 Web pages are created dynamically by populating templates
from a database
 Programmers are responsible for scripts, databases, etc.
2) Building an Outline
 Make a wish list
 Brainstorm on the content that the site will include. This gives you an
idea of its size and scope
 Group content
 Organize the wish list into logical groups, for example, all content
related to the company, and to products
 Create categories
 Some groups will be similar- group these groups into categories but
aim for few categories (5-7)
 Build an outline
 Categories become main ideas
 Within groups are lists of their content (no more than 2 sublevels)
Example of an Outline
Five-to-Seven Rule
 The outline is the foundation of your site structure. To
ensure that the site is easily navigable, keep the number of
categories (and items in groups as well) to between five and
seven, or less
 Categories often become navigation links
 People will have difficulty navigating, if offered too many choices
Using an Outline for Navigation
 On many web sites you
will find an outline of
the site called a "site
map"

 Although not a visual


representation of a site
map, as we will use the
term below, it helps the
user navigate the site (it
provides more of an
index)
3) Converting your Outline into a
Sitemap
 Draw a box to represent each page of your site
 One box to represent the home page
 Below this box, one box for each category on your outline
 Stack subsections (groups) below each category
 As you add detail and navigation information, this diagram
turns into a site map
A Sitemap
 A site map is a diagram that helps you visualize each page of a
web site before you build it, and its location with respect to
other web sites
Another sitemap example
Another sitemap
Sketch out Page Content
 A site map should also specify the technology used on each
page
 Ask yourself if the page will:
 use frames or tables?
 contain media that need a plug-in (such as Flash)?
 be populated from a database?
Naming Conventions
 As you add more detail, your site map should establish the
name of each page
 Naming conventions are important, because the people
working on the site must agree on how to call the pages (e.g.
when they link to them)
 On a large site indicate a naming scheme rather than naming
each page
Sitemap Showing Naming Convention
Designing a sitemap
 Showing how pages link to each other
 Showing the structure of each page
 Indicating special user interface elements
 Representing interactions with databases
Showing how pages link to each other
 Show direct links as one-way arrows between pages
Showing how pages link to each other
(2)
 Show cross-navigation as two-way arrows between pages at
the same level
Showing how pages link to each other
(3)
 Show links to shared pages -- that most pages link to -- as
symbols
Showing how pages link to each other
(4)
 Show redirection as dashed arrows (e.g. an animation flowing
into the home page)
Showing the Structure of Each Page
 Indicate a page that uses frames by using lines to segment the
page
Showing the Structure of Each Page (2)
 Show that a page is built with tables by drawing boxes inside the
page
Showing the Structure of Each Page (3)
 Label tools on a page (such as search boxes, and login fields) using
symbols, or by drawing a small box on the link connecting two pages
Indicating Special user Interface
Elements
 Draw a box and place a symbol (e.g. icon for QuickTime
movie) inside it
 Complex embedded applications should be documented
separately elsewhere
Representing Interactions with
Databases
 Indicate pages that are populated from a database by drawing
a dotted line from the page to the database; may show
templates as a stack of pages
4) Navigation Design
 Give user a sense of size and place
 How big is the site?
 Where is the user on the site?
 Make the interface idiot-proof
 User interface elements should be in prominent locations and
labeled
 Ensure consistent look-and-feel
Navigation Design: giving feedback
about location
 Cross-navigation
 Links to all main sections of the web site in one convenient location
 Appears on every web page as a tool for users to get around
 Color-coding
 Color-coding can be used to reinforce the user's sense of place
 Use a unique color scheme for each section (like Yellow Pages vs White Pages)
 Buttons in the cross-navigation system should be colored accordingly
 Tabs
 Tabs are a virtual metaphor to help users recognize how to use the cross-navigational system
 Breadcrumb trail
 Breadcrumb trails show users how deep they are in the site
 Provide users with a "lifeline" to retrace their steps through the hierarchy

 Process Steps
 This navigation device, used to keep track of the user's progress as to what stage
of a process they are in (e.g. checkout), is commonly found on e-commerce sites
Navigation Design: visual feedback
 Rollovers
 An image that changes its appearance when the mouse moves
over it
 Audio or animation
 An animated button can command the user's attention
Navigation Design: maximal use of
space
 As a designer, you face a dilemma:
 Space is at a premium, so you try to fit many small elements on a
page
 But the smaller the interface elements, the less usable the web page
becomes
 The solution is to use small elements that expand when the user
rolls over them to present more options
 Swaps change the appearance of a graphic on mouse rollover, but in
another part of the page
 Pop-up and jump menus appear when the mouse rolls over a
button
 Shrink-and-expand interfaces expend outward in an animation to
reveal more navigation choices
5) Click-Through Prototype
 To create a demonstration prototype, mock up key pages of
your site
 Illustrate how a user would walk through a particular task
(e.g. ordering a product)
 Fake what you can, without committing to a particular
design!
HTML
History of HTML
 Hypertext systems were envisioned as early as1940 by
Vannevar Bush and have a rich history
 Tim Berners-Lee and Robert Caillau at CERN, in 1989-1990
developed HTML as a simplification of SGML
 CERN launched the web in 1991 (HTML+HTTP)
 HTML is now at version 4
HTML 5?
 HTML5 will be the new standard for HTML.

 The previous version of HTML, HTML 4.01, came in 1999.


 The web has changed a lot since then.

 HTML5 is still a work in progress.


 However, the major browsers support many of the new HTML5
elements and APIs.
Development of HTML 5
 HTML5 is a cooperation between the World Wide Web Consortium
(W3C) and the Web Hypertext Application Technology Working Group
(WHATWG).
 WHATWG was working with web forms and applications, and W3C was
working with XHTML 2.0.
 In 2006, they decided to cooperate and create a new version of HTML.

 Established rules for HTML5 are:


 New features should be based on HTML, CSS, DOM, and JavaScript
 Reduce the need for external plugins (like Flash)
 Better error handling
 More markup to replace scripting
 HTML5 should be device independent
 The development process should be visible to the public
New Features for HTML 5
 In HTML5 there is only one <!doctype> declaration, and it is
very simple: <!DOCTYPE html>

 Some of the supported features are:


 New Elements,
 e.g. the <canvas> element for 2D/3D graphics
 e.g. wew content-specific elements, like <article>, <footer>, <header>,
<nav>, <section>
 New form controls, like calendar, date, time, email, url, search
 New Attributes
 Full CSS3 Support
 Local Storage
 Local SQL Database
 Web Applications
Versions of HTML
 There are several different version of HTML
 HTML 1.0, 2.0, 3.2, 4.0, 4.01
 XHTML 1.0 and 1.1
 HTML 4.01 and XHTML 1.0 come in different flavours:
 Strict: strictly compliant
 Transitional: allows some deprecated elements
 Frameset: a variant of transitional for documents that use
frames
 For these reasons, every HTML file must begin with a
DOCTYPE definition
Structure of a HTML Document
 Every document starts with a DOCTYPE, followed by an HTML
section that contains a head and body:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"


"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>The Hello World Page</title>
</head>
<body>
<p>Hello World!</p>
</body>
</html>
DOCTYPES
 A list of DOCTYPEs is available here from the World-Wide-
Web Consortium (W3C):
 http://www.w3.org/QA/2002/04/valid-dtd-list.html
 Help on choosing a DOCTYPE is also available:
 http://htmlhelp.com/tools/validator/doctype.html
 Pros and Cons of different DOCTYPEs
 Older DOCTYPEs are supported on older browsers
 Newer DOCTYPEs are generally better structured, more
standards compliant, and more modular
The Document HEAD
 The HEAD section of the document contains information
about the document as opposed to the contents of the
document
 Minimally, it should include a TITLE
 <title>My Page Title</title>
 The title typically appears in a Browser's title bar
 The HEAD may also include metadata such as character
encoding and information about how to format the
document
The Document BODY
 The BODY contains the document itself, i.e., what the user
sees
 Any text (also called character data or cdata) within the body
must be contained within some other tag
Paragraphs
 The P tag is used to enclose a paragraph of text
 Paragraphs appear formatted as you would expect
 <p>Some Text. </p>
 <p>Some more text,…</p>
Headings
 Headings are marked with H1, H2, ..., H5 tags
 Hn denotes an nth level heading
Lists
 HTML has three kinds of lists:
 Unordered information (bulleted lists)
 Ordered information (numbered lists)
 Definitions (like in a dictionary)
Unordered Lists
 The UL tag encloses an unordered list
 The individual list items are enclosed in LI tags
 <ul>
 <li>Client/server protocols</li>
 <li>Web site design</li>
 <li>Server-side scripting</li>
 <li>Client-side scripting</li>
 <li>Mixed-mode scripting</li>
 </ul>
Ordered Lists
 The OL tag denotes ordered (numbered) lists
 Again, list items are enclosed in LI tags
 <ol>
 <li>Item 1.</li>
 <li>Item 2.</li>
 <li>Item 3.</li>
 <li>Item 4.</li>
 </ol>
Definition Lists
 Definition lists use the DL tag
 Each item has two parts, the term DT and the definition DD
 <dl>
 <dt>Term 1</dt>
 <dd>The definition</dd>
 <dt>Another term</dt>
 <dd> A definition</dd>
 <dt>One more term</dt>
 <dd>another definition</dd>
 </dl>
Other Useful Tags
 To emphasize some text, use EM
 The <em>last</em> thing you should do ...
 To strongly emphasize, use STRONG
 The <strong>absolute last</strong> thing ...
 Use CODE to denote code snippets
 Use <code>cout<<user_name<<endl;</code> to output the user
name
 There are also short quotes Q, block quotes (BLOCKQUOTE),
citations (CITE), addresses (ADDRESS), insertions (INS),
deletions (DEL), typed-text (KBD), variable names (VAR), sample
output (SAMP), and preformatted text (PRE)
Simple HTML Tables
 HTML tables are created TABLE tag
 Each table contains one or more rows (TR) containing table data (TD)
or table headers (TH)
 <table>
 <tr>
 <th>Name</th>
 <th>Age</th>
 <th>County of Origin</th>
 </tr>
 <tr>
 <td>NigwendeteYamune</td>
 <td>23</td>
 <td>Kiambu</td>
 </tr>
 ...
 </table>
HTML Tables (2)
 HTML4 Tables are actually much more sophisticated than this
basic example

 All the important details can be found at the W3C


 http://www.w3.org/TR/html4/struct/tables.html
The A tag
 So far we know enough to create a simple text documents
 What about the hyper in hypertext?
 For this we use the A tag
 <p>Some of the better search sites on the Internet include <a
href=”http://www.google.com/”> Google</a>, <a href=”h
ttp://www.a9.com/” >A9</a>, and <a href=”h
ttp://www.altavista.com/”> Alta Vista</a>.
 For more information on internet searching, ... </p>
The A tag (2)
 The attribute HREF of the A tag specifies the destination the
link will take us to
 This destination can be absolute:
 href=”h ttp://www.google.com/”
 href=”h ttp://www.jkuat.ac.ke/”
 Or relative:
 href=”courses/index.html”>
 href=”/courses/ics2203/index.html”>
 Relative locations specify the location relative to the current
document and are extremely useful hen building large
websites
The A tag (3)
 The HREF attribute can even specify a target within a
document
 <a href=”http://jkuat.ac.ke/index.html#admin”>
 <a href=”#academics”>
 These link to the sections labels “admin” and “academics”
within their respective documents
 To create these targets we again use the A tag in a different
way
 <a name=”admin”> Administration Department</a>
 creates a target named admin within the current document
Images
 Images can be added to the document with the IMG tag
 The SRC attribute specifies the location of the image data
 The ALT attribute specifies some text to display if the image
can not be displayed
 <img src=“pic1.jpg" alt=“A Portrait of Jacqueline
Matendechere">
Line Breaks
 For a quick and dirty line break you can use the BR tag

 Normally you should avoid this

 Why are you breaking the line?


 For a list of items (or menu): use <ul>
 To shorten a line: let the browser wrap it
 For preformatted text: use the <pre> tag
Summary
 The five step process of web design discussed
 There are many versions of HTML
 You must specify which version using the DOCTYPE tag
 Every document has a HEAD and a BODY tag
 HEAD contains information about the document
 BODY contains the contents of the (displayed) document
 Basic document constructs are available
 Headings
 Paragraphs
 Ordered, unordered and definition lists
 Tables
 Hyperlinks and hyperlink targets
 Images
LECTURE 3:

FORMS, GRAPHIC DESIGN, CSS


Contents
 Forms
 Principles of Graphic Design
 Motivation for CSS
 How to use CSS in your documents
 Formatting text with CSS
 Font properties
 Text properties
 Formatting lists with CSS
 Summary
HTML Forms
 An HTML form is a section of a document containing
normal content plus some controls
 Checkboxes, radio buttons, menus, text fields, etc
 Every form in a document is contained in a FORM tag
 The FORM tag specifies the action that takes place when the
form is submitted
The FORM tag
 The FORM tag has two important attributes:
 ACTION – A URI specifying where the information is sent
 METHOD – How the data is sent (GET or POST)
 <form action=“URI” method="get">
 <p>Enter your name: <input type="text" name=“aname“ value=“some
default value"
 maxlength="50“></p>
 <input type="submit">
 </form>
GET or POST
 Forms should use METHOD="GET" when the form does
not modify anything on the server:
 A search engine query
 A database search
 Forms should use METHOD="POST" when the form
changes the state of the server or sends a large amount of
data
 Entering a message on a forum
 Uploading a file
 GET and POST transport the form data in different ways
Form Controls
 The devices that allow input of data onto a form are called
the controls
 These include:
 Checkboxes and radio buttons
 Menus
 Text inputs
 File selectors
 Hidden controls
 Buttons
The INPUT tag
 The INPUT tag is a multipurpose tag that creates many
different types of controls
 The type of input is controlled by the TYPE attribute
 Can be TEXT, PASSWORD, CHECKBOX, RADIO, SUBMIT,
RESET, FILE, HIDDEN, IMAGE, or BUTTON
 Almost all of these should have a NAME attribute
 Their initial state can be set with a VALUE attribute
 They can all be disabled with DISABLE
 An INPUT tag is never closed (no </input>)
Checkboxes
 <input type="checkbox" ...>
 The NAME attribute names this checkbox
 The CHECKED attribute (with no value) is used to indicate a
pre-checked checkbox
 The VALUE attribute specifies the value bound to name if
this checkbox is submitted (default = ON)
 Hobbies:<br>
 <input type="checkbox" name=“dancing“>Dancing<br>
 <input type="checkbox" name=“hiking“>Hiking<br>
TextBoxes
 <input type="text" ...>
 Allows entry of one line of text
 (Actually, not completely true – try cut and paste)
 Attribute SIZE specifies the width (in characters)
 Attribute MAXLENGTH specifies the maximum number of
characters User's full name:
 <input name="fullname" type="text" size="30“
maxlength="50">
Passwords
 <input type="password" ...>
 Identical to a text box, but text typed into the box is not
readable
 Useful for submitting sensitive information (like passwords)
Buttons
 <input type="submit" ...>
 Creates a button that submits the form to the server
 <input type="reset" ...>
 Creates a button that resets all form fields to their default state
 <input type="button" ...>
 Creates a button that does nothing
 <input type="submit" value="Submit Form Data">
Buttons (2)
 The BUTTON tag provides similar functionality but with a
bit more flexibility
 Attributes are NAME, VALUE, and TYPE
 TYPE can be SUBMIT, BUTTON, RESET
 <button name="sb" value="sbData" type="submit">
 Submit All Form Data Now
 </button>

 Main difference is that the button label is text within the tag
instead of the VALUE attribute
Image Buttons
 <input type="image" ...>
 Displays an image that behaves like a submit button
 The SRC attribute specifies the location of an image file
 The ALT attribute specifies some text to render if the image
is not displayable
 <input type="image" src="button.png" alt="Submit">
Hidden Control
 <input type="hidden" ...>
 Creates a control similar to a text control
 User does not see control
 User can not easily change the value
 Useful for keeping track of data as the user traverses a
collection of pages
 <input type="hidden" name="hiddendata“ value="Hidden Data in
Here">
Text Areas
 The TEXTAREA tag provides a multiline text entry area
 The ROWS and COLS attributes are required and they
specify the number of rows and number of columns
 <textarea rows="30" cols="50" name=“comment">
 The preformatted initial text is sandwiched within the tag.
 </textarea>
Menus
 Drop-down menus are created using the SELECT tag
 Attribute SIZE determines how many rows to display at once
 Each option is enclosed in an OPTION tag
 <select name="country" size="5">
 <option value=“KE">Kenya</option>
 ...
 <option value=“UG">Uganda</option>
 </select>
Menus (2)
 The MULTIPLE attribute of the SELECT tag creates menus
that allow multiple selections
 Options can be grouped hierarchically using the
OPTGROUP tag
Labels
 The LABEL tag specifies that the enclosed item is a label for the
named form element
 For example, clicking the label will shift the focus or change the
state of the associated form
 Check that apply<br>
 <input type="checkbox" name=“dancer" id="dogs“ checked>
 <label for="dogs">I like dogs</label>
 <br>
 <input type="checkbox" name="catlover" id="cats">
 <label for="cats">I like cats</label>
 <br>
 <input type="checkbox" name="piglover" id="pigs">
 <label for="pigs">I like pigs</label>
Fieldsets
 The FIELDSET tag is used to group together a set of related
form elements
 The LEGEND tag assigns a caption to a field set <fieldset>
 <legend>Personal Information</legend>
 First Name: <input type="text" name="fn" size="20">
 <br>
 Last Name: <input type="text" name="ln" size="20">
 <br>
 Date of Birth: <input type="text" name="dob"
 size="10">
 </fieldset>
Principles of Graphic Design
 Basic graphic design principles can be summarized in one
word:
 CRAP:
 Contrast
 Repetition
 Alignment
 Proximity
 Focus (here) is on text
Contrast
 Contrast: When two elements are not exactly the same, they
should be very different
 Otherwise it just looks like a mistake
 With text, contrast can be achieved through
 Font size: small, medium, large
 Font family: serif, sans-serif, cursive, monospace,
 Font weight: light, normal, bold
 Font style: oblique, normal, italic
 Font decoration: none, underline, shadow,
 We can also use text and/or background color
Contrast (2)
 Contrast can be used to separate different parts of a
document (e.g., navigation vs. content)
 Contrast can be used to aid the user in navigation (e.g.,
section headings)
 In the best case, weak contrast is not noticeable
 In the worst case, it just looks bad
Repetition
 Styles and visual elements should be repeated across a page
and across a web site
 Leads to a cohesive and consistent web site
 Repetition can be achieved with
 Text (font) properties: Use these the same way throughout
 Color: Consistent use of color throughout the site/document
 Background: Background images/colors
 Page and section layout: Similar elements should should be
layed out the same way
 Images: Graphics can be repeated and/or styled similarly
 Alignment: Consistent use of alignment
Repetition (2)
 Repetition lets a user know that they are still on the same
web site
 Repetition allows a visitor to learn the page (or section)
layout only once
 Another form of repetition: Web design patterns
Alignment
 Our minds like to imagine straight line grids when look at
things
 We like to see things line up
 We can't stand to see things that almost – but don't quite –
line up
 We also like to see equal distances
 This is a technique called symmetric spacing
 Things that are not aligned get treated differently
 Navigation bar text vs. body text
Proximity
 Proximity (closeness of objects) can be used to group related
items together
 Section heading close to section text
 Figure caption close to figure
 Distance can be used to visually separate unrelated items
 Extra space before section heading separates it from previous
section
 Extra space before and after figures separate them from text
and other figures
Comment on HTML
 HTML (when used correctly) describes the different parts of
a document
 Paragraphs, section headings, quotes, images, ...
 HTML (when used correctly) does not describe the
formatting of a document
 HTML is a logical markup language not a physical markup
language
 HTML was designed to be rendered on a wide
 variety of devices
 Graphical web browsers, text terminals, screen readers, ...
Cascading Style Sheets.CSS
 CSS (Cascading Style Sheets) is for the formatting side of the
Web
 CSS describes how rendered HTML documents should look
 CSS considers the physical and visual display of the document
(the Style)
Advantages of CSS
 The use of CSS separates document layout from document
content
 Different people can be responsible for the two parts
 Document author can focus on content
 Graphic designer can focus on layout

 A single file can control the look of an entire web site


 Easy to modify look of web site without affecting its contents
 Easy to obtain a consistent look (the R in CRAP)
 If done correctly, documents degrade gracefully on platforms
that don't support visual formatting
Disadvantages of CSS
 More to learn
 CSS is powerful but complex
 Not fully supported on some browsers
 Even some modern browsers are not fully CSS 2 compliant
 The formatting is separated from the document
 Makes it hard to write a document and format it simultaneously
How to Write a Document
1) Decide what you want to write
 First and foremost the content of the document is important
 Decide on the logical structure of the document
2) Write it
 Write the document content
 Markup the document's logical structure
3) Format it
 Use CSS to do formatting
 Add other formatting-specific data (e.g., navigation)
 Points 1 and 2 should take the majority of the time
Using CSS
 There are three ways to use CSS
 External Style Sheets
 Uses the LINK tag (in the document HEAD)
 <link rel=”stylesheet” href=”../myfile.css”
 type=”text/css”>

 Inline Style Sheets


 The STYLE tag (in the document HEAD)
 <style type=”text/css”>
 /* CSS information goes here */
 </style>
Using CSS (2)
 Inline STYLE Attributes
 The STYLE attribute (within another HTML tag)
 <a style=”font-size: 10pt;” href=”afile.html”>

 Don't use these


 Gives the disadvantages of CSS without the most important
advantages
Simple CSS
 An Inline CSS example that modifies some of the common HTML
tags
 <style type=”text/css”>
 h1 {
 font-size: 12pt;
 font-family: “Luxi Sans”, sans-serif;
 font-weight: bold;
 }
 p{
 font-size: 12pt;
 font-family: “Luxi Serif ”, serif;
 }
 </style>
CSS with Class
 (Almost) all HTML tags can have an optional CLASS attribute
 This works nicely in conjunction with CSS:
 <style type=”text/css”>
 p.blogentry {
 font-size: 12pt;
 font-family: “Luxi Serif ”, serif;
 }
 </style>
 ...
 <p class=”blogentry”>
 Today was the best day ever ...
 </p>
CSS with IDs
 Similarly, almost all HTML tags can have an ID attribute:
 <style type=”text/css”>
 #menubar {
 font-size: 12pt;
 font-family: “Luxi Serif ”, serif;
}
 </style>
 ...
 <ul id=”menubar”>
 <li>Item 1</li> ...
 </ul>
Notes on CLASS and ID
 Use CLASS when a document contains (or may contain)
many items of this type
 E.g.: blogEntry, nameList, properName
 Use ID when a document can only contain one item of this
type
 E.g. pageTitle, mainNavigationBar
 Choose CLASS and ID names wisely
 – Good: <a id=”properName”>Gregory Nakumicha</a>
 – Bad: <a id=”blueunderlinenowrap”>Gregory
Nakumicha</a>
The DIV and SPAN tags
 HTML has 2 tags, DIV and SPAN, that are specifically used
with CSS and CLASS and ID attributes
 A DIV tag contains a block of text
 Like a paragraph, section heading, or title
 A SPAN tag contains a short piece of text within a block
 Like a name, or a product price
Typeface: font-family
 Consists of a comma-separated list of font names
 h1 { font-family: “Times New Roman”,
 “Luxi Serif ”, “DejaVu LGC Serif ”, serif;
}
 Not all fonts are available on all systems
 Browser will try fonts in order that they are specified
 Always make the last option one of the generic fonts: serif, sans-
serif, cursive, fantasy, or monospace
Font Size: font-size
 Specified in one of the CSS size units
 1em is the width of a letter m (relative to surrounding text)
 1pt is a standard typographic point (1/72 inches)
 1px is one screen pixel
 Keywords: xx-small, x-small, small, medium, large,
 x-large, xx-large are browser dependant
 Percentages: XXX% relative to the surrounding code
 Points and pixels are extremely accurate but not resizeable
 h1 { font-size: 200%; }
 h2 { font-size: large; }
 h3 { font-size: medium; }
Bold Fonts: font-weight
 Can be one of normal, bold, bolder, lighter, 100, 200, ...,
900
 h1 { font-weight: bold;
 font-size: 200%;
 }
 h2 { font-weight: bold;
 font-size: medium;
 }
The Font Style: font-style
 Can be one of normal, italic, or oblique
 An italic font is usually slanted and maybe has some curls added
 An oblique font is a skew transformation of a regular font (not
well supported)
 em { font-style: italic; }
 h1 { font-family: sans-serif;
 font-weight: bold;
 font-style: italic;
}
Other Font Properties
 Use font-variant for producing small caps
 Use font-stretch to expand or condense a font
 Use font as a shorthand to set all font properties at once
 h1 { font: italic small-caps bold 12pt sans-serif;
}
Text Properties: color
 Can be a color name, a rgb value, or a hexadecimal value
 147 color names are at –
http://www.w3schools.com/css/css_colornames.asp
 /* Make all headings pure red */
 H1 { color: red; }
 H2 { color: rgb(255,0,0); }
 H3 { color: #ff0000; }
Text Properties: background
 The background property specifies the background colour
and/or image
 background-colour specifies a colour (named, RGB, or hex)
 background-image, background-position, background-
repeat, and/or background attachment o specify a
background image
 Usually used on the body tag
Text Properties: text-align
 Determine which side of the page (or containing box) that
text lines up with
 Can be one of left, right, center, or justify
 h1 { text-align: center; }
 p { text-align: left; }
Text Properties: text-decoration
 Add some decoration to the text
 Can be one of none, underline, over line, line-through, or
blink
 Treat blink like EBOLA
 h1 { text-decoration: underline; }
 a { text-decoration: none; }
Text Properties: text-indent
 Specifies a length by which the first line of text should be
indented
 Length can be measured in a relative unit
 em: the font-size of the current font (width of a letter m)
 ex: the x-height of the current font (height of a letter x)
 px: one screen pixel
 Or an absolute unit
 Inches (in) centimetres (cm) millimetres (mm), points (pt), or
picas (pc)
 1pt = (1/72)in and 1pc=12pt
 P { text-indent: 5em; }
Text Properties: text-transform
 Can actually transform the text
 Can be one of
 none: don't do anything to the text
 capitalize: Start each word with an uppercase letter
 uppercase: Make everything uppercase (all caps)
 lowercase: Make everything lowercase
 h1 { font-size: large;
 text-transform: capitalize;
}
 h2 { font-size: normal;
 text-transform: uppercase;
}
Text Properties: white-space
 Defines how white space (space, tabs, carriage returns) is
handled
 Can be one of
 normal: Normal formatting, wrap at white space, merge
 multiple whitespace
 pre: treat as preformatted text
 nowrap: don't wrap at whitespace
 a.properName { white-space: nowrap; }
Other Text Properties
 direction: Sets the text direction
 line-height: Sets the distance between lines
 letter-spacing: Sets the space between characters
 text-shadow: Make a colored text shadow
 unicode-bidi
 Allows english blocks to flow left-to-right and Arabic blocks
flow right-to-left on the same page
 word-spacing: Sets the space between words
 These probably should not be used unless you know a lot
about typesetting.
CSS and Lists
 Several properties are specific to lists and list items list-style-
image: sets an image to use as the bullet marker
 list-style-position: controls where the bullet appears
 list-style-type: specifies what kind of bullet to use
 none, disc, circle, square, decimal, decimal-leading-zero, lower-
roman, upper-roman, lower-alpha, upper-alpha, lowergreek,
lower-latin, upper-latin, hebrew, armenian,,georgian, cjk-
ideographic, hiragana, katakana, hiragana-iroha, katakana-iroha
CSS Lookup
 We can specify styles that apply to tags or identifiers only
when contained in other tags
 ul.menu { padding: 0; }
 ul.menu li { text-decoration: none; }
 ...
 <ul class=”menu”>
 <li>Menu item1</li>
 <li>Menu item2</li>
 </ul>
CSS and the A tag
 CSS has several options for the A tag
 A:link defines the style for normal unvisited links
 A:visited defines the style for links that have already been
visited in the past
 A:active defines the style for links after the user clicks on them
(usually while the next page loads)
 A:hover defines the style for links when the mouse pointer is
hovering over them
 A:hover is useful for making things that look like menus
Summary
 HTML forms allow users to input data that is submitted to a
web server
 Many types of controls are possible
 A style should be adopted for graphic design
 CSS provides fine-grained control over
 fonts
 text
 the display of lists
Lecture 4:

Layout with CSS


Contents
 Inline versus block elements
 Blocks
 properties
 the CSS box model
 Example layouts using blocks
 Changing the display property
 Reformatting lists
Inline vs. Block Elements
 Some HTML tags define block elements
 Normally rendered with a space before and a space after
 They take up the entire width of the browser
 Examples: P, H1, ,H2, UL, PRE, DIV
 Other HTML tags define inline elements
 These are rendered inline (to the right of the preceding
element)
 They only take up as much width as necessary
 Examples: A, EM, CODE, SPAN
 Block elements can contain inline elements but not the other
way around (try this with a validator)
Laying out Blocks
 Block elements can be used for layout (positioning) on pages
 We do this by specifying their positions, width, margins,
borders, ...
A Simple 2-Column Layout
 #content1 {
 position: absolute;
 left: 0;
 right: 50%;
 }
 #content2 {
 position: absolute;
 left: 50%;
 right: 0;
 }
The width and height Properties
 A block can be assigned a width and/or height property
 This can be auto, a percentage, or a length in inches, pixels,
cm, mm, em, etc.
 auto fills alls available width, and uses just enough height
 Percentages are treated as a percentage of enclosing box
 This defines the space available for the contents of the box. It
does not include margins, borders, or padding
 div.menu { width: 10em; }
 #firstcolumn { width: 33%; }
The position Property
 The position property determines how the properties left
and top are interpreted
 – static: The element is placed in a normal position
 the left and top properties are not used
 – relative: The element is placed relative to the normal position
 the left and top properties specify offsets from the normal
position
 absolute: The element can be placed anywhere within the
containing block
 The element's position can be specified with the left, top,
right, and bottom properties
The left, right, top, bottom Properties
 For absolute placements, the left, right, bottom, and top
properties specify the distance of a box side from its enclosing
box
 Tip: Setting bottom to 0 can be used to force a box to fill the
enclosing box
 #content1 {
 position: absolute;
 left: 0;
 right: 50%; bottom: 0;
 }
 #content2 {
 position: absolute;
 left: 50%;
 right: 0; bottom: 0;
 }
 ...
 <div id=”content1”>
 The left column text goes here
 </div>
 <div id=”content2”>
 The right column text goes here
 </div>
The CSS Box Model
 Every block is rendered as a box:
Margins, Border, and Padding
 Margins are transparent space around the outside of the box
 margin color is determined by background property of the box
that contains this one
 Border is a border around the box
 Padding is distance between the border and the contents of
the box
 padding color is determined by background property
The margin Properties
 Margins are transparent space around the outside of the box
 margin-top: The top margin size
 margin-right: The right margin size
 margin-bottom: The bottom margin size
 margin-left: The left margin size
 margin: Sets all four properties at once
The padding Properties
 Padding is space between the border and the content
 padding-top: The top margin size
 padding-right: The right margin size
 padding-bottom: The bottom margin size
 padding-left: The left margin size
 padding: Sets all four properties at once
 Don't be afraid to use lots of padding
The border Properties
 The border is a (usually visible) border
 border-style: The type of border
 none, hidden, dotted, dashed, solid, double, groove, ridge, inset, outset
 border-color: The color of the border
 border-width: The width (thickness) of the border
 border: Sets all three at once
 All four borders can also be set separately
 border-xxx-style
 border-xxx-color
 border-xxx-width
 border-xxx
 Where xxx is one of left, right, top, bottom
Box Size
 The total width of a box is
 margin-left + border-left-width + padding-left + width +
padding-right + border-right-width + margin-right
 The total height of a box is
 – margin-top + border-top-width + padding-top + height +
padding-bottom + border-bottom-width + margin-bottom
 Tip: Unless, the height or width is fixed, don't specify it
 Instead, specify the top, left, right, or bottom
Titlebar, Menubar, Content Example
 We use three div elements
 the menubar is fixed-width and its left and top sides are
specified
 the titlebar is fixed-height and its top side is specified
 the content is auto height and width but its left and top sides
match the sizes of the menubar and titlebar, respectively
Titlebar, Menubar, Content Example (2)
 #titlebar {
 position: absolute;
 left: 0;
 top: 0;
 right: 0;
 height: 10ex;
 }
 #menubar {
 position: absolute;
 width: 12em;
 top: 10ex;
 left: 0; bottom: 0;
 }
 #content {
 position: absolute;
 left: 12em;
 top: 10ex;
 right: 0; bottom: 0;
 }
Two Columns with Header Example
 Use three div elements
 The header has a fixed-height, its left, top, and right sides at
distance 0
 column1 has left side at distance 0 and right-side at 50%
 column2 has left side at 50% right-side at distance 0
 The bottom of column1 and column2 are at 0 so that they
line up
Two Columns with Header Example (2)
 #titlebar {
 position: absolute;
 left: 0; right: 0; top: 0;
 height: 10ex;
 }
 #column1 {
 position: absolute;
 left: 0; right: 50%;
 top: 10ex; bottom: 0;
 }
 #column2 {
 position: absolute;
 left: 50%; right: 0;
 top: 10ex; bottom: 0;
 }
Changing the display Attribute
 The display attribute of tags can be modified
 Two common uses:
 display: none can be used to hide information without deleting
it from the HTML
 The display attribute of list items can be used to turn lists into
menus
 Tip: By setting a:hover properties you can get beautiful
horizontal or vertical menu without using images
A Menubar List
 ul.menu {
 width: 6em;
 margin: 0;
 padding: 0;
 border-left: solid 1px black;
 border-right: solid 1px black;
 border-bottom: solid 1px black;
 }
 ul.menu li {
 list-style-type: none;
 background-color: gray;
 border-top: solid 1px black;
 text-align: left;
 }
A Menubar List (2)
 <ul class=”menu”>
 <li><a href=”e 1/”> Eggs and ham</a></li>
 <li><a href=”e 2/”> Sausage and bacon</a></li>
 <li><a href=”e 3/”> Pancakes</a></li>
 </ul>
A Horizontal List
 ul.hmenu li {
 display: inline;
 list-style: none;
 padding-left: .5em;
 padding-right: .5em;
 margin: 0;
 }
 ....
 <ul class=”hmenu”>
 <li><a href=”e1/”> Eggs</a></li>
 <li><a href=”e2/”> Sausage</a></li>
 <li><a href=”e3/”> Pancakes</a></li>
 </ul>
Summary
 HTML elements are (mostly) either inline or block
 DIV is the prototype block element
 SPAN is the prototype inline element
 This can be changed with the display property
 Uses include:
 Using DIV elements to do page layout
 Using lists (UL) as (vertical or horizontal) menus
 Tip: Even recent browsers can have problems with some CSS
properties
LECTURE 5:

CLIENT-SIDE PROGRAMMING
WITH JAVASCRIPT
Contents
 Introduction
 Variables and operators
 Control structures
 Pop-up boxes
 Functions
 Events and event handling
 Document Object Model (DOM)
 Summary
Introduction
Overview of Client-side Scripting
 Up to now we focused on implementing application logic
on the server;
 the browser was just a simple, generalized user interface that
did not play a role in executing the application logic.
 It is beneficial for clients to share in the execution of some
of the application logic
 Central focus of client-side scripting is to manipulate the
content of a web page
 Application logic as such is not concerned with presentation,
but client-side scripting can be used to make web pages more
dynamic
Uses of Client-side Application Logic
 Field and form validation - relying solely on server-side
validation is expensive (server trips)
 Automatic computation of dependent values e.g. in e-
commerce sites
 Making Web Pages More Dynamic
 New input controls
 Rollovers and swaps
 Adding HTML to the page e.g. inserting the current date into
a web page dynamically
Introduction to JavaScript
 Most common scripting technology in browsers available
today.
 Name a misnomer: JavaScript was born as "LiveScript" and its
name was changed for marketing purposes
 It does share some basic syntax with Java, which makes it easy
to learn
 JavaScript is used in millions of Web pages to improve the
design, validate forms, detect browsers, create cookies, and
much more.
What is JavaScript
 JavaScript was designed to add interactivity to HTML pages
 JavaScript is a scripting language (a scripting language is a
lightweight programming language)
 A JavaScript consists of lines of executable computer code
 A JavaScript is usually embedded directly into HTML pages
 JavaScript is an interpreted language (means that scripts
execute without preliminary compilation)
 Everyone can use JavaScript without purchasing a license
What JavaScript Can Do
 JavaScript gives HTML designers a programming tool -
JavaScript is a scripting language with a very simple syntax!
Almost anyone can put small "snippets" of code into their HTML
pages

 JavaScript can put dynamic text into an HTML page - A


JavaScript statement like this: document.write("<h1>" + name +
"</h1>") can write a variable text into an HTML page

 JavaScript can react to events - A JavaScript can be set to


execute when something happens, like when a page has finished
loading or when a user clicks on an HTML element
What JavaScript Can Do
 JavaScript can read and write HTML elements - A
JavaScript can read and change the content of an HTML
element

 JavaScript can be used to validate data - A JavaScript


can be used to validate form data before it is submitted to a
server, this will save the server from extra processing
What JavaScript Can Do
 JavaScript can be used to detect the visitor's
browser - A JavaScript can be used to detect the visitor's
browser, and - depending on the browser - load another page
specifically designed for that browser

 JavaScript can be used to create cookies - A JavaScript
can be used to store and retrieve information on the visitor's
computer
Adding JavaScript to a Page
 The HTML <script> tag is used to insert a JavaScript into an HTML
page.
 <html>
 <body>
 <script type="text/javascript">
 document.write("Hello World!")
 </script>
 </body>
 </html>

 So, the <script type="text/javascript"> and </script> tells where the


JavaScript starts and ends:
 The word document.write is a standard JavaScript command for
writing output to a page.
Semicolon
 With traditional programming languages, like C++ and Java,
each code statement has to end with a semicolon #

 In general, semicolons are optional!


 However, semicolons are required if you want to put more than
one statement on a single line.
Handle Older Browsers
 Browsers that do not support JavaScript will display the
script as page content.
 To prevent them from doing this, we may use the HTML
comment tag:
 <script type="text/javascript">
 <!—
 document.write("Hello World!")
 //-->
 </script>
 The two forward slashes at the end of comment line (//)
prevent the JavaScript compiler from compiling the line.
Where to Put JavaScript
 JavaScripts in the body section will be executed WHILE the
page loads.
 JavaScripts in the head section will be executed when
CALLED.
 Scripts in the head section: Scripts to be executed when
they are called, or when an event is triggered.
 When you place a script in the head section, you will ensure
that the script is loaded before anyone uses it.
Where to Put JavaScript
 Scripts in the body section: Scripts to be executed when
the page loads
 When you place a script in the body section it generates the
content of the page.

 Scripts in both the body and the head section:You


can place an unlimited number of scripts in your document,
so you can have scripts in both the body and the head section.
Where to Put JavaScript
 Using an External JavaScript
 Sometimes you might want to run the same JavaScript on several
pages, without having to write the same script on every page.You
can write a JavaScript in an external file and save the external
JavaScript file with a .js file extension.

 Note: The external script cannot contain the <script> tag!


 To use the external script, point to the .js file in the "src" attribute
of the <script> tag:
 <script src="xxx.js"></script>
 Note: Remember to place the script exactly where you normally
would write the script!
VARIABLES AND OPERATORS
Variables
 A variable is a "container" for information you want to store.
 A variable's value can change during the script.
 You can refer to a variable by name to see its value or to change its
value.

 Rules for variable names:


 Variable names are case sensitive
 They must begin with a letter or the underscore character

 Creating variables
 You can create a variable with the var statement or leave out var but
assign a value.
 The variable name is on the left side of the expression and the value
you want to assign to the variable is on the right.
Variable Scope
 When you declare a variable within a function, the variable
can only be accessed within that function.
 When you exit the function, the variable is destroyed.
 These variables are called local variables.
 You can have local variables with the same name in different
functions, because each is recognized only by the function in
which it is declared.

 If you declare a variable outside a function, all the functions


on your page can access it.
 The lifetime of these variables starts when they are declared,
and ends when the page is closed.
JavaScript Operators-Arithmetic
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (division remainder)
++ Increment
-- Decrement
JavaScript Assignment Operators
OperatorExample Is The Same As
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y x=x%y
JavaScript Comparison Operators
OperatorDescription Example
== is equal to
=== is equal to (checks for both x=5, y="5" , x==y returns
value and type) true
x===y returns false
!= is not equal
> is greater than
< is less than
>= is greater than or equal to
<= is less than or equal to
JavaScript Logical Operators
Operator Description
&& and
|| or
! not
Other JavaScript Operators
 String Operator
 A string is most often text, for example "Hello World!".
 To stick (concatenate) two or more string variables together,
use the + operator.

 Conditional Operator
 JavaScript also contains a conditional operator that assigns a
value to a variable based on some condition.
 Syntax: variablename=(condition)?value1:value2
Control Structures
Branching in JavaScript
 Very often when you write code, you want to perform different
actions for different decisions.
 In JavaScript we have the following conditional statements:
 if statement - use this statement if you want to execute some code
only if a specified condition is true
 if...else statement - use this statement if you want 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 if you want to
select one of many blocks of code to be executed
 switch statement - use this statement if you want to select one of
many blocks of code to be executed
 The syntax is the same as that in C, C++ and Java
Repetition
 Loops in JavaScript are used to execute the same block of
code a specified number of times or while a specified
condition is true.

 JavaScript supports the loops supported by C++, Java and C

 Also for in statement


 for(var property in object) { ... }
break and continue
 There are two special statements that can be used inside
loops: break and continue.

 Break-The break command will break the loop and continue


executing the code that follows after the loop (if any).

 Continue-The continue command will break the current


loop and continue with the next value.
Popup Boxes
 In JavaScript we can create three kinds
of popup boxes:
 Alert box,
 Confirm box, and
 Prompt box.
 Each of these is modal.
Popup Boxes: Alert Box
 An alert box is often used if you want
to make sure information comes
through to the user.

 Syntax:
 alert("sometext")
Popup Boxes: Confirm Box
 A confirm box is often used if you want
the user to verify or accept something.
 If the user clicks "OK", the box returns true.
 If the user clicks "Cancel", the box returns
false.

 Syntax:
 confirm("sometext")
Popup Boxes: Prompt Box
 A prompt box is often used if you want the
user to input a value before entering a page.
 If the user clicks "OK" the box returns the input
value.
 If the user clicks "Cancel" the box returns null.

 Syntax:
 prompt("sometext","defaultvalue")
Functions
 A function is a reusable code-block that will be executed by
an event, or when the function is called.
 To keep the browser from executing a script as soon as the
page is loaded, you can write your script as a function. A
function contains some code that will be executed only by an
event or by a call to that function. Functions are defined at
the beginning of a page, in the <head> section.
 You may call a function from anywhere within the page (or
even from other pages if the function is embedded in an
external .js file).
Functions: example
 <html>
 <head>
 <script type="text/javascript">
 function displaymessage()
 {
 alert("I am an alert box!")
 }
 </script>
 </head>
 <body>
 <form>
 <input type="button" value="Click me!" onclick="displaymessage()" >
 </form>
 </body>
 </html>
Example explained
 If the line: alert ("Hello world!!"), in the example above had
not been written within a function, it would have been
executed as soon as the line was loaded.

 Now, the script is not executed before the user hits the
button.
How to Define a Function
 The syntax for creating a function is:
 function functionname(var1,var2,...,varX){some code}
 The word function must be written in lowercase letters,
otherwise a JavaScript error occurs! –JavaScript is case
sensitive.
 The return statement is used to specify the value that is
returned from the function,
 so, functions that are going to return a value must use the
return statement.
JavaScript Events
 By using JavaScript, we have the ability to create dynamic
web pages.

 Events are actions that can be detected by JavaScript.

 Every element on a web page has certain events which can


trigger JavaScript functions.
 For example, we can use the onClick event of a button element
to indicate that a function will run when a user clicks on the
button.
 We define the events in the HTML tags.
Common Events
 onClick -- User clicks a form field or link
 onChange -- User changes the value of a form field
 onMouseOver -- User moves mouse pointer over a link
 onMouseOut -- User moves mouse out of an image or link
 onSubmit -- User submits a form

 Note: Events are normally used in combination with


functions, and the function will not be executed before the
event occurs!
Table of Events Recognized by
JavaScript
Attribute The event occurs when...
onabort Loading of an image is interrupted
onblur An element loses focus
onchange The content of a field changes
onclick Mouse clicks an object
ondblclick Mouse double-clicks an object
onerror An error occurs when loading a document or an image
onfocus An element gets focus
onkeydown A keyboard key is pressed
onkeypress A keyboard key is pressed or held down
onkeyup A keyboard key is released
onload A page or an image is finished loading
onmousedown A mouse button is pressed
onmousemove The mouse is moved
onmouseout The mouse is moved off an element
onmouseover The mouse is moved over an element
onmouseup A mouse button is released
onreset The reset button is clicked
onresize A window or frame is resized
onselect Text is selected
onsubmit The submit button is clicked
onunload The user exits the page
EVENT HANDLING
Event Handlers
 JavaScript executes functions in response to events that may occur
through user action, or those that arise from other sources
 An Event Handler executes a segment of a code based on certain events
occurring within the application, such as onLoad, onClick.

 JavaScript Event Handlers can be divided into two parts: interactive


Event Handlers and non-interactive Event Handlers
 An interactive Event Handler is the one that depends on the user
interactivity with the form or the document. For example, onMouseOver
is an interactive Event Handler because it depends on the users action with
the mouse.
 A non-interactive Event Handler would be onLoad, because this Event
Handler would automatically execute JavaScript code without the user's
interactivity.
JavaScript’s Event Handlers
 Here are all the Event Handlers available in JavaScript:
 EVENT HANDLER USED WITH
 onAbort image
 onBlur select, text, text area
 onChange select, text, textarea
 onClick button, checkbox, radio, link, reset, submit, area
 onError image
 onFocus select, text, textarea
 onLoad windows, image
 onMouseOut link, area
 onMouseOver link, area
 onSelect text, textarea
 onSubmit form
 onUnload window
onBlur Event Handler
 An onBlur Event Handler executes JavaScript code when
input focus leaves the field of a text, textarea, or a select
option.
 For windows, frames and framesets the Event Handler
executes JavaScript code when the window loses focus.
 In windows you need to specify the Event Handler in the
<BODY> attribute. For example:
 <BODY BGCOLOR='#ffffff'
onBlur="document.bgcolor=‘#000000'">
 Note: On a Windows platform, the onBlur event does not
work with <FRAMESET>.
onBlur Example
 <HTML>
 <HEAD>
<TITLE>Example of onBlur Event Handler</TITLE>
 <SCRIPT>
 function validate(value) {
if (value < 0) alert("Please input a value that is greater or equal to 0");
}
 </SCRIPT>
 </HEAD>
 <BODY>
<H3> Example of onBlur Event Handler</H3>
Try inputting a value less than zero:<BR>
<FORM>
<INPUT TYPE="text" onBlur="validate(this.value)">
</FORM>
</BODY>
</HTML>
onBlur Example
 In this example, 'data' is a text field.
 When a user attempts to leave the field, the onBlur Event
Handler calls the valid() function to confirm that 'data' has a
legal value.
 Note that the keyword this is used to refer to the current
object-which is the current text field labeled data in our
case.
onChange Event Handler
 <HTML>
<HEAD>
<TITLE>Example of onChange Event Handler</TITLE>
 <SCRIPT>
 function valid(input) {
alert("You have changed the value from 10 to " + input);
}
 </SCRIPT>
 </HEAD>
 <BODY>
<H3>Example of onChange Event Handler</H3>
Try changing the value from 10 to something else:<BR>
<FORM>
<INPUT TYPE="text" VALUE="10" onChange="valid(this.value)">
</FORM>
</BODY>
</HTML>
onChange Example
 The onChange Event Handler executes JavaScript code
when input focus exits the field after the user modifies its
text.
 In this example, 'data' is a text field.
 When a user attempts to leave the field after a change of the
original value, the onChange Event Handler calls the valid()
function which alerts the user about value that has been
inputted.
onClick Event Handler
 <HTML>
<HEAD>
<TITLE>Example of onClick Event Handler</TITLE>
 <SCRIPT>
 function valid(form) {
var input = form.data.value;
 alert("Hello " + input + " ! Welcome...");
}
 </SCRIPT>
 </HEAD>
 <BODY>
<H3> Example of onClick Event Handler </H3>
Click on the button after inputting your name into the text box:<BR>
<FORM>
<INPUT TYPE="text" NAME="data">
<INPUT TYPE="button" VALUE="Click Here" onClick="valid(this.form)">
</FORM>
</BODY>
</HTML>
onClick Example
 In an onClick Event Handler, JavaScript function is called
when an object in a button (regular, radio, reset and submit)
is clicked, a link is pushed, a checkbox is checked or an image
map area is selected.
 Note: On Windows platform, the onClick Event Handler may
not work with reset buttons.
 In this example, when the user clicks the button "Click
Here", the onClick Event Handler calls the function valid
(), which obtains the value input in the form field-the visitor’s name
(through form.data.value i.e. the value of the text field
labeled data) and displays a greeting as well as a welcome message
in an alert box. Note-this.form refers to the current form.
onFocus Event Handler
 <HTML>
<HEAD><TITLE>Example of onFocus Event
Handler</TITLE></HEAD>
 <BODY>
<H3>Example of onFocus Event Handler</H3>
Click your mouse in the text box:<BR>
<FORM>
<INPUT TYPE="text" onFocus='alert("You focused
in the textbox!!")'>
</FORM>
</BODY>
</HTML>
onFocus Example
 An onFocus Event Handler executes JavaScript code when input focus
enters the field either by tabbing in or by clicking but not selecting input
from the field.
 For windows, frames and framesets the Event Handler executes JavaScript
code when the window gets focused.
 In windows you need to specify the Event Handler in the <BODY>
attribute. For example:
 <BODY BGCOLOR="#ffffff" onFocus="document.bgcolor='#000000'">
 Note: On a Windows platform, the onFocus Event Handler does not work
with <FRAMESET>.

 In the above example, when you put your mouse on the text box, an
alert() message displays a message.
 Notice that you can also call the alert method without necessarily having to
define a function like in the previous example.
onLoad Event Handler
 <HTML>
<HEAD>
<TITLE>Example of onLoad Event Handler</TITLE>
 <SCRIPT>
 function hello() {
alert("Hello there...\n\nThis is an example of onLoad.");
}
 </SCRIPT>
 </HEAD>
 <BODY onLoad="hello()">
<H3>Example of onLoad Event Handler</H3>
</BODY>
</HTML>
onLoad Example
 An onLoad event occurs when a window or image finishes
loading.
 For windows, this Event Handler is specified in the <BODY>
attribute of the window.
 In an image, the Event Handler will execute handler text when
the image is loaded.
 For example:<IMG SRC="someimage.gif"
NAME="somename" onLoad="alert('You loaded myimage')">
 The example shows how the function hello() is called by
using the onLoad Event Handler. The hello function in turn
calls alert to display a welcome message in an alert box.
onMouseOut Event Handler
 <HTML>
<HEAD><TITLE> Example of onMouseOut Event
Handler </TITLE></HEAD>
 <BODY>
<H3> Example of onMouseOut Event Handler </H3>
Put your mouse over
<A HREF="javascript:void('');"
onMouseOut="window.status='You left the link!'; return
true;">
here</A> and then take the mouse pointer away.
</BODY>
</HTML>
onMouseOut Example
 JavaScript code is called when the mouse leaves a specific link
or an object or area from outside that object or area. For
area object the Event Handler is specified with the
<AREA> tag.
 In the above example, after pointing your mouse and leaving
the link , the text "You left the link!" appears on your
window's status bar indicated by window.status. The
javascript:void(‘’) ensures the link does not go anywhere
even when clicked.
onUnload Event Handler
 <HTML>
<HEAD><TITLE>onUnLoad Example</TITLE>
 <SCRIPT>
 function goodbye() {
alert("Thanks for Visiting!");
}
 </SCRIPT>
 </HEAD>
 <BODY onUnLoad="goodbye();">
<H3>Example of onUnload Event Handler</H3>
Look what happens when you try to leave this page...
</BODY>
</HTML>
onUnload Example
 An onUnload Event Handler calls JavaScript code when a
document is exited.
 In this example, the onUnload Event Handler calls the
goodbye() function as user exits a document.
 NOTE:You can also call JavaScript code via explicit Event
Handler call. For example say you have a function called
myfunction().You could call this function like this:
 document.form.mybotton.onclick = myfunction
 Notice that you don't need to put the () after the function
and also the Event Handler has to be spelled out in
lowercase.
onSubmit
 <HTML>
<HEAD><TITLE> Example of onSubmit Event Handler </TITLE>
<SCRIPT>
function kaSubmit()
{
alert('Thank you ' + myform.data.value +'!')
}
</SCRIPT>
</HEAD>
<BODY>
<H3>Example of onSubmit Event Handler </H3>
Type your name and press the button<BR>
<FORM NAME="myform" onSubmit="kaSubmit()">
<INPUT TYPE="text" NAME="data">
<INPUT TYPE="submit" VALUE="Submit this form">
</FORM>
</BODY>
<HTML>
onSubmit
 An onSubmit Event Handler calls JavaScript code when the
form is submitted.
 In this example, the onSubmit Event Handler calls an
alert() function when the button "Submit this form" is
pressed.
onMouseOver
 <HTML>
 <HEAD><TITLE>Example of onMouseOver Event Handler</TITLE>
 <script>
 function kaMouseOver()
 {
 window.status='Hello! How are you?';//sets the status bar to the text “Hello! How are you?”
 //window is a predefined JavaScript object and status is one of its properties
 }
 </script>
 </HEAD>
 <BODY>
 <H3>Example of onMouseOver Event Handler</H3>
 Put your mouse over
 <A HREF="javascript:void('');" onMouseOver="kaMouseOver(); return true;">
 here</A>and look at the status bar (usually at the bottom of your browser window).
 </BODY>
 </HTML>
onMouseOver
 JavaScript code is called when the mouse is placed over a
specific link or an object or area from outside that object or
area.
 In the above example when you point your mouse to the link,
the text "Hello! How are you?" appears on your window's
status bar. Leaving out return true will make
javascript:void(‘’) to be displayed on the status bar instead
of the text “Hello! How are you?”
ADDITIONAL EXAMPLES
Insert Date
 <html><head><title> ... </title>
 </head>
 <body>
 <h1>Inserting the date into a document</h1>
 The date is
 <script language="javascript">
 document.write(new Date()); //creates a Date object and calls
its //toString() method
 </script> right now.
 </body>
 </html>
Calculate the Sum of Digits
 <html>
<head>
<title>Sum of Digits</title>
<script>
function sumDigits(num) {
var i, sum = 0; // can declare two variables at once
for (i = 1; i <= num; i++) {
sum += i; // add each number to sum (ie, 1 + 2 + ...+ num)
}
// Display result
alert("The sum of the digits from 1 to "+ num + " is:" + sum);
}
</script>
</head>
<body>
Looping - Calculate the sum of the digits.
<form name="form1">
The sum of the digits from 1 to: <INPUT TYPE="text" NAME="digit">
<INPUT TYPE="button" VALUE="Calculate" onClick="sumDigits(form1.digit.value)">
</form>
</body>
</html>
 form1.digit.value obtains the value in field labeled digit and passes the value to the function named sumDigits.
Sum Two Fields
 <html>
 <head>
 <title>Javascript</title>
 <script language="JavaScript">
 function getSum()
 {
 var sum
 sum=parseInt(window.document.form1.t1.value)+parseInt(window.document.form1.t2.value)
 window.document.form1.t3.value=""+sum
 }
 </script>
 </head>
 <body>
 <form name="form1">
 <p>Value1<input type="text" name="t1">
 <p>Value2<input type="text" name="t2">
 <p>Sum<input type="text" name="t3">
 <p><input type="submit" onclick="getSum();return false;" value="Total">
 </form>
 </body>
 </html>
Sum Two Fields
 return false ensures you get to view the results after clicking
on the Total button; prevents form from refreshing
 parseInt converts a string to an integer. Similarly
parseFloat can be used to convert from string to float and
so on. These are predefined methods and no objects are
needed to call them apart from the value to be converted.
Jump to a Page
 <html>
<head>
<title>Select and Jump</title>
</head>
<body>
<FORM>
<!--selectedIndex is the "Index number" that the user "chose" notice that the <SELECT> tag has a
bunch of options -- hence an Array of Options
the Options all have a value & that value is a URL location.href = URL is where we will end up going to--
>
<SELECT onChange="location.href=options[selectedIndex].value">
<OPTION VALUE="http://wwww.eastandard.net">The Standard</OPTION>
<OPTION VALUE="http://wwww.nationmedia.com">Nation</OPTION>
<OPTION VALUE="http://wwww.timesnews.co.ke">Kenya Times</OPTION>
<OPTION VALUE="http://wwww.jkuat.ac.ke">JKUAT</OPTION>
<OPTION VALUE="http://wwww.uonbi.ac.ke">UoN</OPTION>
<OPTION VALUE="http://sysadmin.jkuat.ac.ke">JKUAT E-Mail</OPTION>
</SELECT>
</FORM>
</body>
</html>
DOCUMENT OBJECT MODEL
DOM
 Regardless of the scripting language, the Document Object Model
(DOM) provides a platform-neutral interface to browser and
content of a page.
 Defined by the W3C and most browsers implement it in their latest versions

 The name Document Object Model was chosen, because it provides an


object interface to HTML (and XML) documents (data and behavior)

 Most scripting languages provide predefined objects that map to the


DOM and a programming interface to web documents. For example in
JavaScript, the principal object to use when working with document
content is the document object, a reference to which can be obtained
through the window object that represents a browser window
Client-side Object Hierarchy: DOM
self,...
Level 0 DOM
navigator
forms[]
frames[] elements[]
anchors[] such as the
location
window input objects
links[] and the
history
textarea
images[] object
document
applets[]
screen
embeds[]
Calculations
 Write a program that calculates the area and circumference of a
circle:
Examine DOM Properties
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">
 <html>
 <head>
 <!-- FILE: dom0.html -->
 <title>Examining the properties of an object</title>
 <script language = "javascript" type="text/javascript">
 function objectPropertiesTable(obj)
 {
 document.write(
 "<table border='1'>" +
 "<tr><th>Property Name</th><th>Property Value</th></tr>"
 );
 for (var property in obj)
 {
 document.write("<tr>");
 document.write("<td><code>" + "&nbsp;" + property + "</code></td>");
 document.write("<td><code>" + "&nbsp;" + obj[property] + "</code></td>");
Examine DOM Properties
 </script>
 </head>
 <body>
 Create two links and images:
 <a href="array1.html">link 1</a>
 <a href="array2.html">link 2</a>
 <img src="omare.gif">
 <img src="atetwe.gif">
 <h1>Window Properties Table</h1>
 <script language = "javascript" type="text/javascript">
 objectPropertiesTable(window);
 </script>
 <h1>Document Properties Table</h1>
 <script language = "javascript" type="text/javascript">
 objectPropertiesTable(document);
Examine DOM Properties
 </script>
 <h1>Links Properties Table</h1>
 <script language = "javascript" type="text/javascript">
 objectPropertiesTable(document.links);
 </script>
 <h1>Images properties Table</h1>
 <script language = "javascript" type="text/javascript">
 /* You can't do this in a loop with IE (infinite loop) but you can
with Netscape */
 objectPropertiesTable(document.images[0]);
 objectPropertiesTable(document.images[1]);
 </script>
 </body>
 </html>
Lecture 6:

Server-side Programming with


PHP
Content
PHP Basics:
 Introduction to PHP
• a PHP file, PHP workings, running PHP.
 Basic PHP syntax
• variables, operators, if...else...and switch, while, do while, and for.
 Some useful PHP functions
 How to work with
• HTML forms, cookies, files, time and date.
 How to create a basic checker for user-entered data
PHP Advanced:
 PHP and MySQL
Publishing your website

254
Server-Side Dynamic Web
Programming
• CGI is one of the most common approaches to server-side
programming
 Universal support: (almost) Every server supports CGI programming. A
great deal of ready-to-use CGI code. Most APIs (Application Programming
Interfaces) also allow CGI programming.
 Choice of languages: CGI is extremely general, so that programs may be
written in nearly any language. Perl is by far the most popular, with the
result that many people think that CGI means Perl. But C, C++, Ruby, and
Python are also used for CGI programming.
 Drawbacks: A separate process is run every time the script is requested. A
distinction is made between HTML pages and code.

255
Server-Side Dynamic Web Programming
(2)
• Other server-side alternatives try to avoid the drawbacks
 Server-Side Includes (SSI): Code is embedded in HTML pages, and evaluated on
the server while the pages are being served. Add dynamically generated content
to an existing HTML page, without having to serve the entire page via a CGI
program.
 Active Server Pages (ASP, Microsoft) : The ASP engine is integrated into the web
server so it does not require an additional process. It allows programmers to mix
code within HTML pages instead of writing separate programs. (Drawback(?)
Must be run on a server using Microsoft server software.)
 Java Servlets (Sun): As CGI scripts, they are code that creates documents. These
must be compiled as classes which are dynamically loaded by the web server
when they are run.
 Java Server Pages (JSP): Like ASP, another technology that allows developers to
embed Java in web pages.

256
Introduction to PHP
PHP and MySQL are tricky to teach without access to a server and a
database. We'll do the best we can in the slides that follow.

257
WEB SERVER

Gets Page

<HTML>
<?php PHP code ?>
HTTP Request </HTML>
(url)

Interprets the PHP code


Server response

<HTML>
<B>Hello</B>
CLIENT </HTML>
Hello

Browser creates
the web page

258
Why PHP?
 ..there are no. of server side scripting available like ASP, SSJS,
JSP…..
 PHP involves
 simplicity in scripting (..generally using the database)
 platform independence.
 PHP is
 primarily designed for web applications
 well optimized for the response times needed for web applications
 Is an open source.

259
PHP Language features
 PHP language features such as control structures, operators, variable
types, function declaration, class/object declaration are almost
similar to any compiled or interpreted language such as C or C++.

260
PHP Introduction

PHP is a recursive acronym for “PHP: Hypertext Preprocessor”


-- It is a widely-used open source general-purpose scripting
language that is especially suited for web development and can be
embedded into HTML.

261
PHP Introduction
> PHP is a server-side scripting language
> PHP scripts are executed on the server
> PHP supports many databases (MySQL, Informix, Oracle,
Sybase, Solid, PostgreSQL, Generic ODBC, etc.)
> PHP is open source software
> PHP is free to download and use

262
PHP Introduction

> PHP runs on different platforms (Windows, Linux, Unix, etc.)


> PHP is compatible with almost all servers used today (Apache,
IIS, etc.)
> PHP is FREE to download from the official PHP resource:
www.php.net
> PHP is easy to learn and runs efficiently on the server side

263
PHP Introduction

Instead of lots of commands to output HTML (as seen in C or


Perl), PHP pages contain HTML with embedded code that does
"something" (like in the next slide, it outputs "Hi, I'm a PHP
script!").

The PHP code is enclosed in special start and end processing


instructions <?php and ?> that allow you to jump into and out
of "PHP mode."

264
PHP Introduction

265
PHP Introduction

PHP code is executed on the server, generating HTML which is


then sent to the client. The client would receive the results of
running that script, but would not know what the underlying
code was.

A visual, if you please...

266
PHP Introduction

267
PHP Getting Started

On windows, you can download and install WAMP. With one
installation and you get an Apache webserver, database server and
php.
http://www.wampserver.com

On mac, you can download and install MAMP.


http://www.mamp.info/en/index.html

268
PHP Hello World

Above is the PHP source code.

269
PHP Hello World
It renders as HTML that looks like this:

270
PHP Hello World

This program is extremely simple and you really did not need
to use PHP to create a page like this. All it does is display: Hello
World using the PHP echo() statement.

Think of this as a normal HTML file which happens to have a


set of special tags available to you that do a lot of interesting
things.

271
PHP Comments

In PHP, we use // to make a


single-line comment or /* and */
to make a large comment block.

272
PHP Variables
> Variables are used for storing values, like text strings, numbers
or arrays.
> When a variable is declared, it can be used over and over again
in your script.
> All variables in PHP start with a $ sign symbol.
> The correct way of declaring a variable in PHP:

273
PHP Variables

> In PHP, a variable does not need to be declared before adding a


value to it.
> In the example above, you see that you do 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.
274
PHP Variables
> A variable name must start with a letter or an underscore "_" --
not a number
> A variable name can only contain alpha-numeric characters,
underscores (a-z, A-Z, 0-9, and _ )
> A variable name should not contain spaces. If a variable name is
more than one word, it should be separated with an underscore
($my_string) or with capitalization ($myString)

275
PHP Concatenation
> The concatenation operator (.) is used to put two string values
together.
> To concatenate two string variables together, use the
concatenation operator:

276
PHP Concatenation

The output of the code on the last slide will be:

If we look at the code you see that we used the concatenation
operator two times. This is because we had to insert a third string
(a space character), to separate the two strings.

277
PHP Operators
Operators are used to operate on values. There are four
classifications of operators:

 > Arithmetic
 > Assignment
 > Comparison
 > Logical

278
PHP Operators

279
PHP Operators

280
PHP Operators

281
PHP Operators

282
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...

283
PHP 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
a condition is true and another code if the condition is false
> if...elseif....else statement - use this statement to select one of
several blocks of code to be executed
> switch statement - use this statement to select one of many
blocks of code to be executed

284
PHP Conditional Statements
The following example will output "Have a nice weekend!" if the
current day is Friday:

285
PHP Conditional Statements
Use the if....else statement to execute some code if a condition is
true and another code if a condition is false.

286
PHP Conditional Statements

If more than one line should be


executed if a condition is
true/false, the lines should be
enclosed within curly braces { }

287
PHP Conditional Statements

The following example will


output "Have a nice weekend!" if
the current day is Friday, and
"Have a nice Sunday!" if the
current day is Sunday. Otherwise
it will output "Have a nice day!":

288
PHP Conditional Statements
Use the switch statement to select one of many blocks of code
to be executed.

289
PHP Conditional Statements
For switches, 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.

290
PHP Conditional Statements

291
PHP Arrays

> An array variable is a storage area holding a number or text. The


problem is, a variable will hold only one value.
> An array is a special variable, which can store multiple values in
one single variable.

292
PHP Arrays
If you have a list of items (a list of car names, for example),
storing the cars in single variables could look like this:

293
PHP Arrays
> 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 best solution here is to use an array.
> An array can hold all your variable values under a single name.
And you can access the values by referring to the array name.
> Each element in the array has its own index so that it can be
easily accessed.

294
PHP Arrays
 In PHP, there are three kind of arrays:
 > Numeric array - An array with a numeric index
 > Associative array - An array where each ID key is associated
with a value
 > Multidimensional array - An array containing one or more
arrays

295
PHP Numeric Arrays

> A numeric array stores each array element with a numeric


index.
> There are two methods to create a numeric array.

296
PHP Numeric Arrays
In the following example the index is automatically assigned (the
index starts at 0):

In the following example we assign the index manually:

297
PHP Numeric Arrays
In the following example you access the variable values by referring
to the array name and index:

The code above will output:

298
PHP Associative Arrays
> With an associative array, each ID key is associated with a value.
> When storing data about specific named values, a numerical
array is not always the best way to do it.
> With associative arrays we can use the values as keys and assign
values to them.

299
PHP Associative Arrays
In this example we use an array to assign ages to the different
persons:

This example is the same as the one above, but shows a different
way of creating the array:

300
PHP Associative Arrays

301
PHP Multidimensional Arrays

In a multidimensional array, each element in the main array can


also be an array.

And each element in the sub-array can be an array, and so on.

302
PHP Multidimensional Arrays

303
PHP Multidimensional Arrays

304
PHP Multidimensional Arrays

305
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:

306
PHP Loops
> 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

307
PHP Loops - While
The while loop executes a block of code while a condition is true.
The example below defines a loop that starts with
i=1. The 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:

308
PHP Loops - While

309
PHP Loops – Do ... While

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.

The next example defines a loop that starts with i=1. It will
then increment i with 1, and write some output. Then the
condition is checked, and the loop will continue to run as long as
i is less than, or equal to 5:

310
PHP Loops – Do ... While

311
PHP Loops – Do ... While

312
PHP Loops - For

313
PHP Loops - For
 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 loop)

314
PHP Loops - For

The example below defines a loop that starts with i=1. The 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:

315
PHP Loops - For

316
PHP Loops - Foreach

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.

317
PHP Loops - Foreach
The following example demonstrates a loop that will print the
values of the given array:

318
PHP Loops - Foreach

319
PHP Functions
> We will now explore how to create your own 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.

320
PHP Functions
A function will be executed by a call to the function.

> Give the function a name that reflects what the function does
> The function name can start with a letter or underscore (not
a number)

321
PHP Functions
A simple function that writes a name when it is called:

322
PHP Functions - Parameters
 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.

323
PHP Functions - Parameters

324
PHP Functions - Parameters

325
PHP Functions - Parameters

This example adds different


punctuation.

326
PHP Functions - Parameters

327
PHP Forms - $_GET Function
> The built-in $_GET function is used to collect values from a
form sent 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 (max. 100 characters).

328
PHP Forms - $_GET Function

Notice how the URL carries the information after the file name.

329
PHP Forms - $_GET Function

The "welcome.php" file can now use the $_GET function to


collect form data (the names of the form fields will
automatically be the keys in the $_GET array)

330
PHP Forms - $_GET Function
> When using method="get" in HTML forms, all variable
names and values are displayed in the URL.
> 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.
> The get method is not suitable for large variable values; the
value cannot exceed 100 chars.

331
PHP Forms - $_POST Function
> The built-in $_POST function 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).

332
PHP Forms - $_POST Function

And here is what the code of action.php might look like:

333
PHP Forms - $_POST Function
Apart from htmlspecialchars() and (int), it should be
obvious what this does. htmlspecialchars() makes sure any
characters that are special in html are properly encoded so
people can't inject HTML tags or Javascript into your page.

For the age field, since we know it is a number, we can just


convert it to an integer which will automatically get rid of any
stray characters. The $_POST['name'] and $_POST['age']
variables are automatically set for you by PHP.

334
PHP Forms - $_POST Function
 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.

335
Lecture 7:

PHP with MySQL


& Website Publishing
Content
PHP Basics:
 Introduction to PHP
• a PHP file, PHP workings, running PHP.
 Basic PHP syntax
• variables, operators, if...else...and switch, while, do while, and for.
 Some useful PHP functions
 How to work with
• HTML forms, cookies, files, time and date.
 How to create a basic checker for user-entered data
PHP Advanced:
 PHP and MySQL
Publishing your website

337
Objectives
 Connect to MySQL from PHP
 Learn how to handle MySQL errors
 Execute SQL statements with PHP
 Use PHP to work with MySQL databases and tables
 Use PHP to manipulate database records

338
PHP Overview
 PHP has the ability to access and manipulate any database
that is ODBC compliant
 PHP includes functionality that allows you to work directly
with different types of databases, without going through
ODBC
 PHP supports SQLite, database abstraction layer functions,
and PEAR DB

339
Enabling MySQL Support in PHP
 On UNIX/Linux systems:
 Configure PHP to use the mysqli extension by specifying the
--with-mysqli parameter when you run the
configure command during installation
 On Windows:
 Copy the files libmysql.dll and php_mysqli.dll
to the installation directory
 Edit the php.ini configuration file and enable the
extension=php_mysqli.dll directive

340
Opening and Closing a MySQL
Connection
 Open a connection to a MySQL database server with the
mysqli_connect() function
 The mysqli_connect() function returns a positive
integer if it connects to the database successfully or false if it
does not
 Assign the return value from the mysqli_connect()
function to a variable that you can use to access the database
in your script

341
Opening and Closing a MySQL
Connection (continued)
 The syntax for the mysqli_connect()
function is:
$connection = mysqli_connect("host"[, "user ", "password",
"database"])

 The host argument specifies the host name


where your MySQL database server is installed
 The user and password arguments specify a MySQL account name
and password
 The database argument selects a database
with which to work

342
Opening and Closing a MySQL
Connection (continued)
Table 6-1 MySQL server information functions

343
Opening and Closing a MySQL
Connection (continued)

Figure 6-1 MySQLInfo.php in a Web browser

344
Selecting a Database
 Select a database with the use database statement
when you log on to the MySQL Monitor
 The syntax for the mysqli_select_db() function is:
mysqli_select_db(connection, database)
 The function returns a value of true if it successfully selects a
database or false if it
does not

345
Handling MySQL Errors
 Reasons for not connecting to a database server include:
 The database server is not running
 Insufficient privileges to access the data source
 Invalid username and/or password

346
Handling MySQL Errors (continued)
 Make sure you are using a valid username and password

Figure 6-2 Database connection error message

347
Suppressing Errors with the Error Control
Operator
 Writing code that anticipates and handles potential problems
is often called bulletproofing
 Bulletproofing techniques include:
 Validating submitted form data
 Using the error control operator (@) to suppress error
messages

348
Terminating Script Execution
 The die() and exit() functions terminate script
execution
 The die() version is usually used when attempting to
access a data source
 Both functions accept a single string argument
 Call the die() and exit() functions as separate
statements or by appending either function to an expression
with the Or operator

349
Terminating Script Execution (continued)
$DBConnect = @mysqli_connect("localhost", "root",
"paris");
if (!$DBConnect)
die("<p>The database server is not
available.</p>");
echo "<p>Successfully connected to the database
server.</p>";
$DBSelect = @mysqli_select_db($DBConnect, "flightlog");
if (!$DBSelect)
die("<p>The database is not available.</p>");
echo "<p>Successfully opened the database.</p>";
// additional statements that access the database
mysqli_close($DBConnect);

350
Terminating Script Execution (continued)
$DBConnect = @mysqli_connect("localhost", "dongosselin",
"rosebud")
Or die("<p>The database server is not available.</p>");
echo "<p>Successfully connected to the database server.</p>";
@mysqli_select_db($DBConnect, "flightlog")
Or die("<p>The database is not available.</p>");
echo "<p>Successfully opened the database.</p>";
// additional statements that access the database server
mysqli_close($DBConnect);

351
Reporting MySQL Errors
Table 6-2 MySQL error reporting functions

352
Reporting MySQL Errors
$User = $_GET['username'];
$Password = $_GET['password'];
$DBConnect = @mysqli_connect("localhost", $User, $Password)
Or die("<p>Unable to connect to the database
server.</p>“ . "<p>Error code " . mysqli_connect_errno()
. ": " . mysqli_connect_error()) . "</p>";
echo "<p>Successfully connected to the database server.</p>";
@mysqli_select_db($DBConnect, "flightlog")
Or die("<p>The database is not available.</p>");
echo "<p>Successfully opened the database.</p>";
// additional statements that access the database
mysqli_close($DBConnect);

353
Reporting MySQL Errors (continued)

Figure 6-4 Error number and message generated by


an invalid username and password

354
Reporting MySQL Errors
$User = $_GET['username'];
$Password = $_GET['password'];
$DBConnect = @mysqli_connect("localhost", $User, $Password)
Or die("<p>Unable to connect to the database
server.</p>"
. "<p>Error code " . mysqli_connect_errno()
. ": " . mysqli_connect_error()) . "</p>";
echo "<p>Successfully connected to the database
server.</p>";
@mysqli_select_db($DBConnect, "flightplan")
Or die("<p>Unable to select the database.</p>"
. "<p>Error code " . mysqli_errno($DBConnect)
. ": " . mysqli_error($DBConnect)) . "</p>";
echo "<p>Successfully opened the database.</p>";
// additional statements that access the database
mysqli_close($DBConnect);

355
Reporting MySQL Errors (continued)

Figure 6-5 Error code and message generated when


attempting to select a database that does not exist

356

Executing SQL Statements
Use the mysqli_query() function to send SQL
statements to MySQL
 The syntax for the mysqli_query() function is:
mysqli_query(connection, query)
 The mysqli_query() function returns one of three
values:
1. For SQL statements that do not return results (CREATE
DATABASE and CREATE TABLE statements) it returns a
value of true if the statement executes successfully

357
Executing SQL Statements (continued)
2. For SQL statements that return results (SELECT and SHOW
statements) the mysqli_query() function returns a
result pointer that represents the query results
a) A result pointer is a special type of variable that refers to the
currently selected row in a resultset
3. The mysqli_query() function returns a value of false
for any SQL statements that fail, regardless of whether they
return results

358
Working with Query Results
Table 6-3 Common PHP functions for accessing database results

359
Retrieving Records into an
Indexed Array
 The mysqli_fetch_row() function returns the fields
in the current row of a resultset into an indexed array and
moves the result pointer to the next row
echo "<table width='100%‘ border='1'>";
echo "<tr><th>Make</th><th>Model</th>
<th>Price</th><th>Quantity</th></tr>";
$Row = mysqli_fetch_row($QueryResult);
do {
echo "<tr><td>{$Row[0]}</td>";
echo "<td>{$Row[1]}</td>";
echo "<td align='right'>{$Row[2]}</td>";
echo "<td align='right'>{$Row[3]}</td></tr>";
$Row = mysqli_fetch_row($QueryResult);
} while ($Row);

360
Retrieving Records into an Indexed Array

Figure 6-6 Output of the inventory table in a Web browser

361
Retrieving Records into an Associative Array
 The mysqli_fetch_assoc() function returns the fields
in the current row of a resultset into an associative array and
moves the result pointer to the next row
 The difference between mysqli_fetch_assoc() and
mysqli_fetch_row() is that instead of returning the
fields into an indexed array, the mysqli_fetch_assoc()
function returns the fields into an associate array and uses each
field name as the array key

362
Accessing Query Result Information
 The mysqli_num_rows() function returns the
number of rows in a query result
 The mysqli_num_fields() function returns the
number of fields in a query result
 Both functions accept a database connection variable as an
argument

363
Accessing Query Result Information
$SQLstring = "SELECT * FROM inventory";
$QueryResult = @mysqli_query($DBConnect, $SQLstring)
Or die("<p>Unable to execute the query.</p>"
. "<p>Error code “ . mysqli_errno($DBConnect)
. ": " . mysqli_error($DBConnect)) . "</p>";
echo "<p>Successfully executed the query.</p>";
$NumRows = mysqli_num_rows($QueryResult);
$NumFields = mysqli_num_fields($QueryResult);
if ($NumRows != 0 && $NumFields != 0)
echo "<p>Your query returned “ .
mysqli_num_rows($QueryResult) . “ rows and "
. mysqli_num_fields($QueryResult) . “
fields.</p>";
else
echo "<p>Your query returned no results.</p>";
mysqli_close($DBConnect);

364
Accessing Query Result Information

Figure 6-8 Output of the number of rows and fields


returned from a query

365
Closing Query Results
 When you are finished working with query results retrieved
with the mysqli_query() function, use the
mysqli_free_result() function to close the
resultset
 To close the resultset, pass to the
mysqli_free_result() function the
variable containing the result pointer from the
mysqli_query() function

366
Creating and Deleting Databases
 Use the CREATE DATABASE statement with the
mysqli_query() function to create a new database

$SQLstring = "CREATE DATABASE real_estate";


$QueryResult = @mysqli_query($DBConnect,
$SQLstring)
Or die("<p>Unable to execute the
query.</p>"
. "<p>Error code " .
mysqli_errno($DBConnect)
. ": " . mysqli_error($DBConnect)) .
"</p>";
echo "<p>Successfully executed the query.</p>";
mysqli_close($DBConnect);

367
Creating and Deleting Databases

Figure 6-9 Error code and message that prints when you attempt
to create a database that already exists

368
Creating and Deleting Databases
 Use the mysqli_db_select() function to check whether
a database exists before you create or delete it
 To use a new database, you must select it by executing the
mysqli_select_db() function
 Deleting a database is almost identical to creating one, except use
the DROP DATABASE statement instead of the CREATE
DATABASE statement with the mysqli_query()
function

369
Creating and Deleting Databases
$DBName = "real_estate";
...
if (@!mysqli_select_db($DBConnect, $DBName))
echo "<p>The $DBName database does not exist!</p>";
else {
$SQLstring = "DROP DATABASE $DBName";
$QueryResult = @mysqli_query($DBConnect, $SQLstring)
Or die("<p>Unable to execute the query.</p>"
. "<p>Error code “ . mysqli_errno($DBConnect)
. ": “ . mysqli_error($DBConnect)) . "</p>";
echo "<p>Successfully deleted the database.</p>";
}
mysqli_close($DBConnect);

370
Creating and Deleting Tables
 To create a table, use the CREATE TABLE statement with the
mysqli_query() function
 Execute the mysqli_select_db() function before
executing the CREATE TABLE statement or the new table
might be created in the wrong database
 To prevent code from attempting to create a table that already
exists, use a mysqli_query() function that attempts to
select records from the table

371
Creating and Deleting Tables
$DBName = "real_estate";
...
$SQLstring = "CREATE TABLE commercial (city VARCHAR(25),
state VARCHAR(25), sale_or_lease VARCHAR(25),
type_of_use VARCHAR(40),Price INT, size INT)";
$QueryResult = @mysqli_query($DBConnect, $SQLstring)
Or die("<p>Unable to execute the query.</p>"
. "<p>Error code " . mysqli_errno($DBConnect)
. ": " . mysqli_error($DBConnect)) . "</p>";
echo "<p>Successfully created the table.</p>";
mysqli_close($DBConnect);

372
Creating and Deleting Tables

Figure 6-11 Error code and message that prints when you
attempt to create a table that already exists

373
Adding, Deleting, and Updating Records
 To add records to a table, use the INSERT and VALUES
keywords with the mysqli_query() function
 The values entered in the VALUES list must be in the same
order in which you defined the table fields
 You must specify NULL in any fields for which you do not
have a value

374
Adding, Deleting, and Updating Records
 To add multiple records to a database, use the LOAD DATA
statement and the mysqli_query() function with a
local text file containing the records you want to add
 To update records in a table, use the UPDATE, SET, and
WHERE keywords with the mysqli_query() function

375
Adding, Deleting, and Updating Records
 The UPDATE keyword specifies the name of the table to
update
 The SET keyword specifies the value to assign to the fields in
the records that match the condition in the WHERE keyword
 To delete records in a table, use the DELETE and WHERE
keywords with the mysqli_query() function
 The WHERE keyword determines which records to delete in
the table

376
Using the mysqli_affected_rows() Function
 With queries that return results (SELECT queries), use the
mysqli_num_rows() function to find the number of
records returned from the query
 With queries that modify tables but do not return results
(INSERT, UPDATE, and DELETE queries), use the
mysqli_affected_rows() function to determine
the number of affected rows

377
Using the mysqli_affected_rows() Function

$SQLstring = "UPDATE inventory SET price=368.20


WHERE make='Fender' AND model='DG7'";
$QueryResult = @mysqli_query($DBConnect, $SQLstring)
Or die("<p>Unable to execute the query.</p>"
. "<p>Error code " . mysqli_errno($DBConnect)
. ": " . mysqli_error($DBConnect)) . "</p>";
echo "<p>Successfully updated "
. mysqli_affected_rows($DBConnect) . "
record(s).</p>";

378
Using the mysqli_affected_rows()
Function (continued)

Figure 6-16 Output of mysqli_affected_rows() function


for an UPDATE query

379
Using the mysqli_info() Function
 For queries that add or update records, or alter table’s structure, use
the mysqli_info() function to return information about the
query
 The mysqli_info() function returns the number of operations
for various types of actions, depending on the type of query
 The mysqli_info() function returns information about the last
query that was executed on the database connection

380
Using the mysqli_info() Function
 The mysqli_info() function returns information
about queries that match one of the following formats:
 INSERT INTO...SELECT...
 INSERT INTO...VALUES (...),(...),(...)
 LOAD DATA INFILE ...
 ALTER TABLE ...
 UPDATE
 For any queries that do not match one of these formats, the
mysqli_info() function returns an empty string

381
Using the mysqli_info() Function
$SQLstring = "INSERT INTO inventory
VALUES('Ovation', '1777 LX Legend', 1049.00,
2),
('Ovation', '1861 Standard Balladeer', 699.00,
1),
('Ovation', 'Tangent Series T357', 569.00, 3)";
$QueryResult = @mysqli_query($DBConnect, $SQLstring)
Or die("<p>Unable to execute the query.</p>"
. "<p>Error code “ . mysqli_errno($DBConnect)
. ": " . mysqli_error($DBConnect)) . "</p>";
echo "<p>Successfully added the records.</p>";
echo "<p>" . mysqli_info($DBConnect) . "</p>";

382
Using the mysqli_info() Function

Figure 6-17 Output of mysqli_info() function for an


INSERT query that adds multiple records

383
Using the mysqli_info() Function
 The mysqli_info() function also returns information for
LOAD DATA queries
$SQLstring = "LOAD DATA LOCAL INFILE
'c:/temp/inventory.txt'
INTO TABLE inventory;";
$QueryResult = @mysqli_query($DBConnect, $SQLstring)
Or die("<p>Unable to execute the query.</p>"
. "<p>Error code “ . mysqli_errno($DBConnect)
. ": " . mysqli_error($DBConnect)) . "</p>";
echo "<p>Successfully added the records.</p>";
echo "<p>" . mysqli_info($DBConnect) . "</p>";

384
Using the mysqli_info() Function

Figure 6-18 Output of mysqli_info() function for a


LOAD DATA query

385
Summary
 PHP includes functionality that allows you to work directly with
different types of databases, without going through ODBC
 Writing code that anticipates and handles potential problems is
often called bulletproofing
 The error control operator (@) suppresses error messages
 A result pointer is a special type of variable that refers to the
currently selected row in a resultset

386
Summary (continued)
 Use the mysqli_query() function to send SQL
statements to MySQL
 To identify a field as a primary key in MySQL, include the
PRIMARY KEY keywords when you first define a field
with the CREATE TABLE statement
 The AUTO_INCREMENT keyword is often used with a
primary key to generate a unique ID for each new row in a
table

387
Summary (continued)
 You use the LOAD DATA statement and the
mysqli_query() function with a local text file to add
multiple records to a database
 With queries that return results, such as SELECT queries,
you can use the mysqli_ num_rows() function to
find the number of records returned from the query
 The mysqli_info() function returns the number of
operations for various types of actions, depending on the
type of query

388
Publishing Your Web Site
 Web Hosting:
 The publication of a Web site for public access
 Internet access (cable modem, DSL, satellite, dial-up modem,
ISP)
 Internet Service Provider (ISP):
 Provides access to the Internet along with other types of
services such as e-mail

389
Publishing Your Web Site (continued)
 ISP advantages to hosting a Web site:
 Extremely fast Internet connections using advanced fiber-optic
connections
 Large and powerful Web servers and the expertise and
manpower to maintain and manage them
 A domain name is a unique address used for identifying a
computer, such as a Web server on the Internet

390
Publishing Your Web Site
(continued)
 Domain name registration
 Pick a domain name that is similar to your business name or that
describes your Web site
 You cannot use a domain name that is already in use or a
trademarked name
 Contact a domain name registrar to find out the availability
of a domain name and register it
 Domain names are stored in a master database that is
maintained by the InterNIC

391
Publishing Your Web Site
(continued)
 Domain name registration (continued)
 For a fee, domain names can be registered for a specified period
of time
 Most hosting sites provide registration service for you
 After you register your domain name, notify your ISP of your
domain information

392
Publishing Your Web Site
(continued)
 File Transfer Protocol (FTP)
 Is a TCP/IP protocol used for transferring files across the
Internet
 Transfers files between an FTP client (your computer) and an
FTP server (a server capable of running FTP)
 The vehicle that allows you to get your Web page files to the
Web server

393
Publishing Your Web Site
(continued)
 File Transfer Protocol (continued)
 Your ISP provides a username and password to log on to the
FTP site and upload files to the FTP server
 Examples of FTP clients include Firefox and Internet Explorer
and WinScp
 Use your browser to log on to an FTP server and upload your files

394

You might also like