Introduction To Web Application Fundamentals
Introduction To Web Application Fundamentals
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"
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.
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
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
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.
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.
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.
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
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)
<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
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
263
PHP Introduction
264
PHP Introduction
265
PHP Introduction
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
268
PHP Hello World
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.
271
PHP Comments
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
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
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
287
PHP Conditional Statements
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.
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
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
296
PHP Numeric Arrays
In the following example the index is automatically assigned (the
index starts at 0):
297
PHP Numeric Arrays
In the following example you access the variable values by referring
to the array name and index:
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
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 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
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
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
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.
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:
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"])
342
Opening and Closing a MySQL
Connection (continued)
Table 6-1 MySQL server information functions
343
Opening and Closing a MySQL
Connection (continued)
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
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)
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)
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
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
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
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
378
Using the mysqli_affected_rows()
Function (continued)
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
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
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