You are on page 1of 386

INTRODUCTION TO PHP

Dynamic Web Sites

Dynamic Web Sites are flexible, accurately describes as applications than merely sites:

Respond to different parameters (for example, the time of day or the version of the visitors Web browser Have a memory allowing user registration & login Involve HTML forms, so that people can perform searches, provide feedback, etc Often have interfaces where administrators can manage the sites content Easier to maintain, upgrade and build open

What is PHP?

PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.) PHP is an open source software (OSS) PHP is free to download and use

Php.net

Figure 1: The home page for PHP

What is a PHP File?

PHP files may contain text, HTML tags and scripts PHP files are returned to the browser as plain HTML PHP files have a file extension of ".php", ".php3", or ".phtml"

Why PHP?

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

Where to Start?

Install an Apache server on a Windows or Linux machine Install PHP on a Windows or Linux machine Install MySQL on a Windows or Linux machine Or download FoxServ/EasyPHP

PHP Installation
Download PHP http://www.php.net/downloads.php

Download MySQL Database http://www.mysql.com/downloads/index.html

Download Apache Server http://httpd.apache.org/download.cgi

What can PHP do?

Server-side scripting. You need to run the web server, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server. Command line scripting. You can make a PHP script to run it without any server or browser.
Writing desktop applications. Ability to write cross-platform applications this way. PHP-GTK is an extension to PHP, not available in the main distribution.

Basic syntax

To place PHP code within HTML document, use


<?php ?>

Save the file as .php Run the file in web browser


http://localhost/filename.php

Sending data to web browser

Language constructs in PHP to display message


echo() print ()

For example, <?php echo This was done using PHP; ?> Will display: This was done using PHP

PHP, HTML & White Space

There are 3 areas where you can affect spacing :


in your PHP scripts In HTML source In the rendered Web page

PHP is generally white space insensitive, meaning that you can space out your code to make your scripts more legible.

To create white space

To alter the spacing of the finished Web page, use the HTML tags <br /> (line break) and <p></p> (paragraph).
To alter the spacing of the HTML source created with PHP:

Use echo() or print() over the course of several lines Use the newline character (\n) within the double quotation marks.

Writing comments in PHP

PHP supports three comment types:


# This is a comment // This is also a comment /* This is a longer comment that spans two lines */

Variables

PHP syntactical rules for creating variables:

A variables name (identifier) must start with a dollar sign ($), for example $name Can contain combination of strings, numbers & underscore ($my_report1) First character after dollar sign ($) must be either a letter or an underscore (it cannot be a number)

Variables

Variable names in PHP are casesensitive. Variables can be assigned using the equal sign (=)

Variables: Strings

A string is a quoted chunk of letters, numbers, spaces, punctuations, etc. E.g.


Ali In my mind 1000 9 july 1978

Strings are case sensetive so $Welcome_Text is not the same as $welcome_text When assigning numbers to strings you do not need to include the quotes so: $user_id = 987 would be allowed.

Outputting Variables

To display a variable on the screen uses exactly the same code as to display text but in a slightly different form. The following code would display your welcome text:
<? $welcome_text = "Hello and welcome to my website."; print($welcome_text); ?>

As you can see, the only major difference is that you do not need the quotation marks if you are printing a variable. String variables are created and their values sent to the Web browser in this script

Concatenating strings
$city = Ipoh; $state = Perak $address = $city . $state ; Will display: IpohPerak To improve: $address = $city . , . $state ;

Add a comma and a space

Using numbers

Valid number-type variables can be like: 8, 3.14, 109080808, -4.524 To format the number into thousands and round it to two decimal places:
$total = number_format ($total, 2);

Understanding Functions

Function: subroutine/individual statements grouped into a logical unit that performs specific task. To execute a function, must invoke or call it from somewhere in your script. The statement that calls a function is referred to as a function call and consists of the function name followed by any data of the function needs.

Understanding Functions (cont)

Arguments / Actual parameters: The data (which you place in parentheses following the function name). Passing arguments: Sending data to a called function. Many functions generate, or return, some sort of a value that you can use in your script. E.g. round() function that rounds a decimal value to the nearest whole number.

round() function

You pass a number as an argument to the round()function, which calculates and returns the nearest whole number. The following statements calls the round()function and passes to it a value of 3.556. The round()function calculates and returns a value of 4, which is then displayed with an echo statement.

<?php echo round(3.556); ?>

round() function

Many functions can accept multiple arguments, which you separate with commas. The following statements calls the round() function and then passes to it a first argument of 3.556 and a second argument of 2. The round() function calculates and returns a value of 3.56 (rounded to two decimal places)

<?php echo round(3.556, 2); ?>

Constants

Constants are a specific data type in PHP, that unlike variables, retain their initial value throughout the course of a script. You cant change the value of a constant once it has been set. Constants can be assigned any single value a number or a string of characters.

Defining Constants

A constant contains information that does not change during the course of program execution. Common practice to use all uppercase letters for constant names. Use define( ) function to create constant.

define(CONSTANT_NAME, value); define(DEFAULT_LANGUAGE, Malay); define(VOTING_AGE, 18);

Defining Constants (cont)

By default, constant names are case sensitive, but you can make constant names case insensitive by passing a Boolean value of TRUE as third argument to the define function.

define(DEFAULT_LANGUAGE, Malay, TRUE);

Defining Constants (cont)

You can pass a constant name to the echo statement on the same manner as you pass a variable name, but without the dollar sign.

echo <p>The legal voting age is , VOTING_AGE, .</p>;

Data Types
Data Type Integer numbers Floating point numbers Boolean String NULL Description The set of all positive and negative numbers and zero, with no decimal places Positive or negative numbers with decimal places or numbers written using exponential notation A logical value of true or false Text such as Hello World An empty value, also referred ti as a NULL value

Numeric data types

Loosely Typed Programming Languages

Programming languages that do not require you to declare the data types of variables are called loosely typed programming languages. Loose typing is also known as dynamic typing because the data types for a variable can change after it has been declared. In PHP, you are not required to declare the type of variables, in fact you are not allowed to do so.

Data Types (cont)

$ChangingVar String $ChangingVar Number $ChangingVar point $ChangingVar $ChangingVar

= Hello World; //
= 8; // Integer = 5.367; // Floating = TRUE; // Boolean = NULL; // NULL

Single vs Double Quotation Marks

Using double quotation marks: echo "You are purchasing <b>$quantity</b> widget(s) at a cost of <b>\$$price</b> each. With tax, the total comes to <b>\$$total</b>.\n";
Using single quotation marks echo 'You are purchasing <b>$quantity</b> widget(s) at a cost of <b>\$$price</b> each. With tax, the total comes to <b>\$$total</b>.\n';

The script to demonstrate the difference between using single and double quotation marks

Single vs Double Quotation Marks

cont

PROGRAMMING WITH PHP

Overview

Creating an HTML Form Handling an HTML Form Managing Magic Quotes Conditionals & Operators Validating Form Data Arrays

Creating an HTML Form

Managing HTML forms with PHP is a 2 step process:

Create the HTML form

An HTML form is created using the form tags and various input types.
<form action=script.php method=post> </form>

Create the corresponding script that will receive and process the form data

Form

PHP Forms and User Input

PHP Form Handling

The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts.

Form example:

<html> <body><form action="welcome.php" method="post"> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" /> </form></body> </html>

PHP Forms and User Input

cont

The "welcome.php" file looks like this:

<html> <body>Welcome <?php echo $_POST["name"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old.</body> </html> A sample output of the above script may be:
Welcome John. You are 28 years old.

Example of PHP script to handle form

$_REQUEST

$_REQUEST is a special variable type in PHP. It stores all of the data sent to PHP page through either the GET or POST methods, as well as data accessible in cookies.

PHP $_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.

Example of GET method

When the user clicks the "Submit" button, the URL sent to the server could look something like this:

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

When to use method=GET"?

When using method="get" in HTML forms, all variable names and values are displayed in the URL. Note: This method should not be used when sending passwords or other sensitive information! However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases. Note: The get method is not suitable for large variable values; the value cannot exceed 100 characters.

PHP $_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).

Example of $_POST Function

When the user clicks the "Submit" button, the URL will look like this:

The "welcome.php" file can now use the $_POST function to collect form data (the names of the form fields will automatically be the keys in the $_POST array):

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

$_REQUEST

If the PHP scripts show blank spaces where the variables should have printed out, it means that the variable have no values. Likely causes:

Misspelled or mis-capitalized the variable names $_REQUEST is not available because youre using an outdated version of PHP

Managing Magic Quotes

When Magic Quotes is enables, it will automatically escape single and double quotation marks in the values of variables. In PHP, there are 2 types of Magic Quotes

magic_quotes_gpc: Applies to form, URL & cookie data (gpc stands for get, post, cookie) magic_quotes_runtime: Applies to data

Managing Magic Quotes

cont

If Magic Quotes is enabled on your server, you can do undo its effect using the stripslashes() function &var = stripslashes($var)
This function will remove any backslashes found in $var.

Managing Magic Quotes

Managing Magic Quotes

The apostrophe entered in the form was escaped automatically by PHP, generating unseemly results

To adjust Magic Quotes

Open handle_form.php Change the first & third variable assignment lines to
$name=stripslashes($_REQUEST[nam e]); $comments=stripslashes($_REQUEST[ comments]);

Conditionals & Operators

PHPs three primary terms for creating conditionals are if, else and elseif (which can also be written as two words else if)
IF conditions
if (condition) { //DO something! }

If else
if (condition) { //DO something! } else } //DO something else }

if elseif
if (condition) { //DO something! } elseif (condition2) { //DO something else } else { //DO something different }

cont

A condition can be true in PHP for any number of reasons. These are common true conditions:

$var, if $var has a value other than 0, an empty string, or NULL isset($var), if $var has any value other than NULL, including 0 or an empty string TRUE, true, True, etc

isset($var)

This function checks if a variable is set, meaning that it has a value other than NULL. Example:

if (isset($_REQUEST['gender'])) { $gender = $_REQUEST['gender']; } else { $gender = NULL; }

Form Validation

Form Validation

The first aim of form validation is ensuring that something was entered or selected in form elements. The second goal is to ensure that submitted data is of the right type (numeric, string, etc) or a specific acceptable value (like &gender being equal to either F or M.

Form Validation

cont

Validating form data requires the use of conditionals and any number of functions, operators & expressions. One common function to be used is isset(), which tests if a variable has a value (including 0, FALSE, or an empty string, but not NULL). One problem with isset()function is that an empty string tests as TRUE, meaning that its not effective way to validate text inputs and text boxes from an HTML form.

Form Validation

cont

To check that a user typed something into textual elements like name, email, and comments you can use the empty() function.
It checks if a variable has an empty value: an empty string, 0, null or FALSE Script to validate form

Arrays

Array can hold multiple, separate pieces of information, unlike strings and numbers (which are scalar variables, meaning they can store only a single value at a time). PHP supports two kinds of arrays:

indexed associative.

Array: Indexed

Indexed arrays use numbers as the keys. Example:

Array Example1: $artists KEY VALUE

0
1 2 3

Rihanna
Madonna Sting Daughtry

Maroon5

Array: Associative

Associative arrays use strings as the keys.

Array Example1: $states KEY KL PP PRK KEL VALUE Kuala Lumpur Pulau Pinang Perak KELANTAN

To retrieve value from an array

To retrieve a specific value from an array, you refer to the array name first, followed by the key, in square brackets:
Note that array keys are used like other values in PHP: number (e.g., 2) are never quoted, whereas strings (KL) must be.

echo $artists[2];//Sting echo $states [KL]; //Kuala Lumpur

Printing array

Wrap around your array name and key in curly braces when your array uses strings for its keys: echo PP is the abbreviation for {$states[PP]}.; Numerically, indexed arrays dont have this problem, though: echo The artist with an index of 4 is $artists[4].;

To use arrays

Open handle_form.php Change the assignment of the $name and $comments variables to

$name = striplashes($_POST[name]) $comments= striplashes($_POST[comments]); In the previous version of this script, the values of $name and $comments were assigned by referring to the $_REQUEST array which will work. But since these variables come from a form that uses the post method, $_POST would be more exact, and therefore more secure

cont
Alter the echo() statement echo <p>Thank you, <b>$name</b>, for the following comments:<br /> <tt>$comments</tt></p> <p>We will reply to you at <i> {$_POST[email]}</i>/</p>\n ;

Creating arrays

Two primary ways to define your own arrays.

Add an element at a time to build one Use array() function to build an entire array in one step

Build array one by one

Example:
$array[] = Tobias; $array[] = Maeby; $array[wife] = Lindsay;

Its important to note that if you specify a key and a value already exists indexed with that same key, the new value will overwrite the existing one. For example,
$array[son] = Buster; $array[son] = Michael;

Use array() function to build an entire array in one step


$states=array(KL => Kuala Lumpur, PP => Pulau Pinang);

This function can be used whether or not you explicitly set the key
$artists=array (Incubus, Coldplay, Nelly);

If you set the first numeric key value, the added values will be keyed incrementally thereafter:

$days=array(1=>Sunday, Monday,Tuesday); echo $day[3];//Tuesday If you want to create an array of sequential numbers, use the range() function: $ten = range (1,10); Calendar: To create & access arrays

Multidimensional arrays

Multidimensional array is array consisting of other arrays. Example:


$states=array (MD => Maryland, IL => Illinois, ); $province=array(QC=>Quebec, AB=>Alberta,.);

Then, these two arrays could be combined into one multidimensional array like:
$abbr=array (UD=>$states, Canada=>province);

Now, $abbr is a multidimensional array

Multidimensional arrays

cont
To access the $states array, refer to $abbr[US] To access Maryland, use $abbr[US][MD] Simply use the name of the multidimensional array, followed by the key of the first array in square brackets, followed by the key of the second inner array in square brackets. To print, surround the whole construct in curly braces: echo The US state whose abbreviation is MD is {$abbr[US][MD].; To use multidimensional arrays About.html About.txt To handle the form: handle_about.php

Arrays and strings

PHP has two functions for converting between strings and arrays
$array=explode (separator, $string); $string=implode (glue, $array);

When turning an array into a string, you set the glue the characters or code that will be inserted between the array values in the generated string.\ Conversely, when turning into an array, you specify the separator, which is the code that delineates between the different elements in the generated array

Arrays and strings

cont
$string1 = Mon Tue Wed Thur Fri; $days_array = explode( - , $string1);

The $days_array variable is now a five-element array, with Mon indexed at 0, Tue indexed at 1, etc. $string2=implode(, , $days_array); The $string2 variable is now a comma-separated list of days: Mon, Tue, Wed, Thur, Fri

Sorting arrays

sort() Sort an array by value, discarding the original keys. Its important to note that the arrays keys will be reset after the sorting process, so if the key-value relationship is important, you should NOT use this function. asort() sort an array by value while maintaining the keys ksort() sort an array by key rsort(), arsort(), krsort() sort in reverse order

The while loop


while (condition) {
// Do something }

As long as the condition part of the loop is true, the loop will be executed. Once it becomes false, the loop stopped. If the condition is never true, the loop will never be executed. The while loop will most frequently be used when retrieving results from a database

The while loop

condition

Do this if TRUE

Exit loop once condition is FALSE

A flowchart representation of how PHP handles a while loop

The for loop

The for loop syntax


for (initial expression; condition; closing expression) { // Do something }

The for loop


initial expression

condition

after expression

Do this if TRUE Exit loop once condition is FALSE

The for loop

Upon first executing the loop, the initial expression is run. Then, the condition is checked and, if true, the contents of the loop are executed. After execution, the closing expression is run and the condition is checked again. This process continues until the condition is false.
for ($i = 1; $i <=10; $i++) { echo $i; }

The for loop


for ($i = 1; $i <=10; $i++) { echo $i; }

The first time this loop is run, the $i variable is set to the value of 1. Then, the condition is checked (is 1 less than or equal to 10?) Since this is true, 1 is printed out (echo $i) Then, $i is incremented to 2 ($i++), the condition is checked, and so forth. The result of this script will be the numbers 1 through 10 printed out Example of loops: calendar.php

CREATING DYNAMIC WEB SITES

88

Overview
1.
2.

3.
4.

5.
6. 7.

Including Multiple Files Handling HTML Forms with PHP Redux Making Sticky Form Creating & Calling Your Own Functions Variable Scope Date & Time Functions Sending Email
89

Including multiple files

PHP has four functions for using external file:

include() include_once() require() require_once

90

Difference between include() and require()

The functions are exactly the same when working properly but behave differently when they fail. If an include() function doesnt work (it cannot include the file for some reason), a warning will be printed on the Web browser, but the script will continue to run.
91

Difference between include() and require()

If require() fails, error is printed and the script is halted. These two functions are used to create functions, headers, footers, or elements that can be reused on multiple pages. This can save the developer a considerable amount of time by creating a standard header or menu file. When the header needs to be updated, you can only update this one include file, or when you add a new page to your site, you can simply change the menu file (instead of updating the links on all web pages).
92

The include() Function

The include() function takes all the text in a specified file and copies it into the file that uses the include function. Example 1: Assume that you have a standard header file, called "header.php". To include the header file in a page, use the include() function, like this:
<html> <body><?php include("header.php"); ?><h1>Welcome to my home page</h1><p>Some text</p></body> </html>
93

*_once() function

Both functions have a *_once() version, which guarantees that the file in question is included only once regardless of how many times a script may (presumeably inadvertently) attempt to include it. require_once(filename.php) ; include_once(filename.php)
94

Site structure

When you begin using multiple files, the overall site structure becomes more important. When laying out your site, there are 3 considerations:

Ease of maintenance Security Ease of user navigation


95

Site structure

Ease of maintenance

Using external files for holding standard procedures (i.e. PHP code), CSS, JavaScript and HTML design greatly improve the ease of maintaining site because commonly edited code is placed in one central location.
96

Site structure

Security

Use .inc or .html file for extension documents where security is not issue (such as HTML templates) Use .php for files containing sensitive data (such as database access information) You can also use both .inc and .html or .php so that a file is clearly indicated as an include of a certain type: functions.inc.php or header.inc.html
97

Site structure

Ease of user navigation

Structure your sites so that they are easy for users to navigate, both by clicking links and by manually typing a URL. Try avoid creating too many nested folders or using hard-to-copy directory names and filenames containing upper and lowercase letters and all manner of punctuation
98

Handling HTML Forms with PHP Redux

The previous examples showed that there are two separate scripts for handling HTML forms: one that displayed the form and another that received it. To have the entire process in one script, use a conditional if (/* form has been submitted */) { //Handle it } else { //Display it }
99

Handling HTML Forms with PHP Redux

cont

To determine if the form has been submitted, check that a $_POST variable. For example, check the $_POST[submitted]
if (isset($_POST[submitted])) { //Handle it } else { // Display it }
100

Handling HTML Forms with PHP Redux

cont

If you want a page to handle a form and then display it again (e.g. to add a record to a database and then give an option to add another), use
if (isset($_POST[submitted])) { //Handle it } // Display the form

Example (calculator.php)
101

Steps to handle HTML forms


Step 1: Create a new PHP document (Script 3.5) <?php # calculator.php $page_title = 'Widget Cost Calculator'; include ('./includes/header.html');
102

Step 2: Write the conditional for handling the form if (isset($_POST['submitte d'])) {

103

Step 3: Validate the form


if (is_numeric($_POST['quantity ']) && is_numeric($_POST['price'])) && is_numeric($_POST['tax'])) {
The validation checks that three submitted variables are all numeric
104

Step 4: Perform the calculations


$taxrate = $_POST[tax] / 100; $total = ($_POST['quantity'] * $_POST['price']) * ($taxrate + 1); $total = number_format ($total, 2);
1st line: changes the tax value to from percentage to decimal (5% .05) 2nd line: quantity * price * by tax rate (.05) plus 1 (1.05)
105

Step 5: Print the results


echo '<p>The total cost of purchasing ' . $_POST['quantity'] . ' widget(s) at $' . number_format ($_POST['price'], 2) . ' each is $' . $total . '.</p>';
106

Step 6: Complete the conditionals and close the PHP tag


} else { echo '<h1 id="mainhead">Error!</h1> <p class="error">Please enter a valid quantity and price.</p><p><br /></p>'; } Step 7: Display the HTML Form Step 8: Include the footer file <?php include ('./includes/footer.html'); ?>
107

Making Sticky Form

A sticky form is simply a standard HTML form that remembers how you filled it out. This is particularly nice feature for end users especially if your are requiring them to resubmit a form (for instance, after filling it out incorrectly on the first place) To make sticking form, open calculator.php
108

To make sticky form


Step 1: Open calculator.php Step 2: Change the quantity input to read: <p>Quantity: <input type="text" name="quantity" size="5" maxlength="10" value="<?php if (isset($_POST['quantity'])) echo $_POST['quantity']; ?>" /></p> Add the value attribute the input, then print the value of the submitted quantity variable ($_POST[quantity] Step 3: Repeat process for price & tax

109

Creating & Calling Your Own Functions

To create your own functions Creating a function that takes arguments Setting default argument values Returning values from a function

110

Creating & Calling Your Own Functions

To create your own functions

PHP has a the capability for you to define and use your own functions. The syntax:
function function_name () { // Function code }

The name of your function can be any combination of letters, numbers & underscores, but it must begin with either a letter or the underscore.
111

To create your own functions (2)

The main restriction is that you cannot use an existing function (print, echo, isset, etc). Function names are case-insensitive (unlike variable names), so you could call that function use function_name() or FUNCTION_NAME() or Function_Name(), etc.
Exercise: To create your own function (dateform.php)
112

Creating & Calling Your Own Functions

Creating a function that takes arguments

Just like PHPs built-in functions, those you write can take arguments (also called parameters). A function can take any number of arguments that you choose, but the order in which you put them is critical. To allow for arguments, add variables to your functions definition:
function print_hello() ($first, $last) { // Function code 113 }

Creating & Calling Your Own Functions

cont

You can call the function as you would any other function in PHP, sending literal values or variables to it:
print_hello (Jimmy, Stewart); $surname = Stewart; $print_hello (Jimmy, surname);

As with any function in PHP, failure to send the right number of arguments results in an error. Exercise: Rewrite the calculator process as a function
114

function calculate_total
function calculate_total ($qty, $cost, $tax) { $taxrate = $tax / 100; $total = ($qty * $cost) * ($taxrate + 1); echo '<p>The total cost of purchasing ' . $qty . ' widget(s) at $' . number_format ($cost, 2) . ' each, including a tax rate of ' . $tax . '%, is $' . number_format ($total, 2) . '.</p>'; }
115 Notice that the variables being defined are not $_POST[quantity], $_POST[price], $_POST[tax]

Creating & Calling Your Own Functions

Setting default argument values

Another variant on defining your own functions is to preset an arguments value. To do so, assign the argument a value in the functions definition:
function greet ($name, $greeting = Hello) { echo $greeting, $name!; }

The end result of setting a default argument value is that that particular argument becomes optional when calling the function. If a values is passed to it, the passed value is used; otherwise the default value is used
116

Creating & Calling Your Own Functions

cont..

You can set default values for as many of the arguments as you want, as long as those arguments come last in the function definition. In other words, the required arguments should always be first. Example:
greet ($surname, $message); greet (Roberts); greet (Grant, Good Evening);

However, greet() will not work, and theres no way to pass $greeting a value without passing one to $name as well. Exercise: To set default argument values
117

To set default argument values


function calculate_total ($qty, $cost, $tax = 5) { The calculate_total() function now assumes a set tax rate unless one is specified when the function is called. Change the form validation to read: if (is_numeric($_POST['quantity']) && is_numeric($_POST['price'])) {
118

To set default argument values (2)


Change the function call line to: if (is_numeric($_POST['tax'])) { calculate_total ($_POST['quantity'], $_POST['price'], $_POST['tax']); } else { calculate_total ($_POST['quantity'], $_POST['price']); } If the tax value has also been submitted (and is numeric), then the function will be called as before. Otherwise, the function is called providing the two arguments, meaning that the default value will be used for the tax rate.

119

Creating & Calling Your Own Functions

Returning values from a function

To have your function return a value, use the return statement


function find_sign ($month, $day) { // Function code return $sign; }

120

Creating & Calling Your Own Functions

cont

The function can return a value (number/string) or a variable whose value has been created by the function. When calling this function, assign the returned value to a variable $my_sign = find_sign (July, 9); Or use it as a parameter to find another function: print find_sign (July, 9); Exercise: To have a function return a value
121

Variable Scope

Every variable in PHP has a scope to it, which is to say a realm in which the variable (and therefore its value) can be accessed. For starters, variables have the scope of the page in which they reside, So, if you define $var, the rest of the page can access $var, but other pages generally cannot (unless you use special variables).
122

Variable Scope (2)

Since included files act as if they were part of the original (including) script, variables defined before the include() line are available to the included file. Further, variables defined within the included file are available to the parent (including) script after the include() line.
123

Variable Scope

cont

Functions have their own scope, which means that variables used within a function are not available outside of it; and variables defined outside of a function are not available within it. For this reason, a variable inside of a function can have the same name as one outside of it and still be an entirely different variable with a different value. This is a confusing concept for most beginners.
124

Variable Scope

global() Statement

To alter the variable scope within a function, use the global() statement
function function_name() { global $var; } $var = 20; function_name(); // Function call

In this example, $var inside the function is now the same as $var outside of it. This means that the function $var already has a value of 20, and if the value changes inside of the function, the external $var s value will also change
125

Variable Scope

Superglobals

Another option for circumventing variable scope is to make use of the superglobals: $_GET, $_POST, $_REQUEST, etc.
These variables are automatically accessible within your functions. Exercise: To use global variables
126

Date & Time Functions

date() function returns a string of text for a certain date and time according to a format specified date (format, [timestamp]); The timestamp is an optional argument representing the number of seconds . It allows you to get information, like the day of the week, for a particular date. If timestamp is not specified, PHP will just use the current time on the server.
127

Date & Time Functions

cont

There are myriad formatting parameters available and these can be used in conjunction with literal text. For example:
echo date (F j, Y); // January 26, 2005 echo date (H:i); 23:14 echo date(Today is D); // Today is Mon
128

Date & Time Functions

Date Function Formatting


CHARACTER
Y

MEANING
Year as 4 digits

EXAMPLE
2005

y
N m F M j d L (lowercase L)

Year as 2 digits
Month as 1 or 2 digits Month as 2 digits Month Month as 3 letters Day of the months as 1 or 2 digits Day of the months as 2 digits Day of the week
129

05
2 02 February Feb 8 08 Monday

(cont) Date Function Formatting


CHARACTER
D

Date & Time Functions

MEANING
Day of the week as 3 letters

EXAMPLE
Mon

g
G h H i S a A

Hour, 12-hour format as 1 or 2 digits


Hour, 24-hour format as 1 or 2 digits Hour, 12-hour format as 2 digits Hour, 24-hour format as 2 digits Minutes Seconds Am or pm AM or PM
130

6
18 06 18 45 18 am PM

Date & Time Functions

getdate() Function

getdate() Function to return an array of values for date and time. Example:
$dates = getdate(); echo $dates [month]; // January

This function also takes an optional timestamp argument. If that argument is not used, getdate() returns information of the current date and time. Exercise: dateform.php
131

Date & Time Functions

The getdate()Array
KEY year mon month mday weekday hours minutes seconds VALUE
Year Month 2005 12

EXAMPLE

Month name Day of the month Day of the week Hours Minutes Seconds
132

December 25 Tuesday 11 56 47

Sending Email

Use mail() function to send email in mail ($to, $subject, $body); $to = email address or a series of addresses, separated by commas $subject = emails subject line $body = contents of the email. Use the newline character (\n) within the double quotation marks when creating your body to make the text go over multiple lines

133

Sending Email

cont

The mail() function takes a fourth, optional parameter for additional headers. This is where you can set the From, Reply-To, Cc, Bcc and etc. For example: mail (sarirah97@yahoo.com, Hello, $body, From: fcet3rd@yahoogroups.com);
134

Sending Email

cont

To use multiple headers of different types in email, separate each with \r\n

$headers = From: fcet3rd@yahoogroups.com \r\n; $headers .= Cc: unatuna97@yahoo.com\r\n; mail (sarirah97@yahoo.com, Hello, $body, $headers);
135

PHP mail() dependencies

PHPs mail function doesnt actually send the email itself. Instead, it tells the mail server running on the computer to do so. This means, that your computer must have a WORKING MAIL SERVER in order for this function to work.
136

PHP mail() dependencies (2)

If you have a computer running a UNIX variant or through a professional host, this should not be a problem. But if you are running PHP on your own computer, youll probably need to make adjustments.

137

PHP mail() dependencies (3)

If you are running on Windows and have ISP that provides with SMTP server, this information can be set in the php.ini file. Unfortunately, this will only work if your ISP doesnt require authentication to use the SMTP server. Otherwise, you need to install an SMTP server on your computer. Google for free windows smtp server.
138

PHP mail() dependencies (4)

If you are running on Mac OS X, youll need to enable the built-in SMTP server (either sendmail or postfix, depending upon the specific version of Mac OS X you are running). You can find instructions online for doing so google: enable sendmail Mac OS X
139

140

COOKIES AND SESSIONS

Cookies

A cookie is a small file that is stored on the client computer when visiting a website. Cookies got a bad rap a few years ago and as a result there is a good deal of people out there with their cookies disabled. Cookies are harmless. Some sites will use them to track visitor usage and

Features of a cookie

Stored on the client computer and are thus decentralized. Can be set to a long lifespan and/or set to expire after a period of time from seconds to years. They work well with large sites that may use several web servers. Wont do you any good if the client has set their browser to disable cookies.

Features of a cookie (cont)

Limitations on size and number: a browser can keep only the last 20 cookies sent from a particular domain, and the values that a cookie can hold are limited to 4 KB in size. Can be edited beyond your control since they reside on the client system. Information set in the cookie is not available until the page is reloaded.

How to Create a Cookie?


The setcookie() function is used to set a cookie. Note: The setcookie() function must appear BEFORE the <html> tag. setcookie(name, value, expire, path, domain);

setcookie() function: Example 1


In the example below, we will create a cookie named "user" and assign the value "Alex Porter" to it. We also specify that the cookie should expire <?php after one hour: setcookie("user", "Alex Porter",

time()+3600); ?> <html>

setcookie() function: Example 2


You can also set the expiration time of the cookie in another way. It may be easier than using seconds. In the example below the expiration time is set to a month (60 sec * 60 min * 24 hours * <?php days). 30 $expire=time()+60*60*24*30; setcookie("user", "Alex Porter", $expire); ?>

How to Retrieve a Cookie Value?

<?php // Print a cookie echo $_COOKIE["user"];

The PHP $_COOKIE variable is used to retrieve a cookie value. In the example below, we retrieve the value of the cookie named "user" and display it on a page:

// A way to view all cookies print_r($_COOKIE); ?>

How to Retrieve a Cookie Value? (cont)


In the following example we use the isset() function to find out if a cookie has been set: <html> <body> <?php if (isset($_COOKIE["user"])) echo "Welcome " . $_COOKIE["user"] . "!<br />"; else echo "Welcome guest!<br />"; ?> </body> </html>

How to Delete a Cookie?


When deleting a cookie you should assure that the expiration date is in the past. Delete example: <?php // set the expiration date to one hour ago setcookie("user", "", time()3600);

What if a Browser Does NOT Support Cookies?

If your application deals with browsers that do not support cookies, you will have to use other methods to pass information from one page to another in your application. One method is to pass the data through forms.

What if a Browser Does NOT Support Cookies? (cont)

PHP Sessions

PHP session

A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.

Features of sessions

Server-size cookie can store very large amounts of data while regular cookies are limited in size. Since the client-side cookie generated by a session only contains the id reference (a random string of 32 hexadecimal digits, such as fca17f071bbg9bf7f85ca281653499a4 called a session id) you save on bandwidth. Much more secure than regular cookies since the data is stored on the server and cannot be edited by the user.

Features of sessions (cont)

Only last until the user closes their browser. Wont work if client has cookies disabled in their browser unless some extra measures are taken. Can be easily customized to store the information created in the session to a database. Information is available in your code as soon as it is set.

Advantages of PHP Sessions

Your server-side cookie can contain very large amounts of data with no hassle client-side cookies are limited in size Your client-side cookie contains nothing other than a small reference code - as this cookie is passed each time someone visits a page on your site, you are saving a lot of bandwidth by not transferring large client-side cookies around Session data is much more secure - only you are able to manipulate it, as opposed to client-side cookies which are editable

Cookies vs Session?

Cookies generally should be used for nonsensitive throw-away information like the following:

Displaying the users name next time they visit the site. Simple user display preferences. Anything small and disposable that needs to be stored for a period of time (for info like, email address, contact info etc. a database should be used)

Sessions are used for more sensitive info like controlling user access or loading info from a database that expires when the session ends or the browser window is closed.

Starting a PHP Session


Before you can store user information in your PHP session, you must first start up the session. The session_start() function must appear BEFORE the <html> tag:

<?php session_start(); ?> <html> <body> </body> </html>

The code above will register the user's session with the server, allow you to start saving user information, and assign a UID for that user's session.

Storing a Session Variable

Storing a Session Variable

In the next example, we create a simple page-views counter. The isset() function checks if the "views" variable has already been set. If "views" has been set, we can increment our counter. If "views" doesn't exist, we create a "views" variable, and set it to 1:

Storing a Session Variable (cont)

Destroying a Session
If you wish to delete some session data, you can use the unset() or the session_destroy() function. The unset() function is used to free the specified session variable: <?php unset($_SESSION['views']); ?>

Destroying a Session (cont)


You can also completely destroy the session by calling the session_destroy() function: <?php session_destroy(); ?> Note: session_destroy() will reset your session and you will lose all your stored session data.

Choosing the appropriate option

You should not use sessions in very large projects which are likely to be deployed on multiple load-balancing servers. The reason behind this may not be apparent at first, but if you recall, session data is actually stored in a file on a server's computer. If a user visits your site, and your load-balancer redirects them to one server for a request, that server has their session data. Next time they read a page, your load-balancer may well shift them to another server, leaving their original session data on the original server. The second server might also save some session data of its own.

Choosing the appropriate option

The end result? They lose their information part-way through their visit, and what data you do have is fragmented across your servers. There are ways around this problem, never fear:

Use a networked file system (NFS on Unix or the equivalent). Pretty much all operating systems allow you to connect to other computers and read/write their data. If you have a shared session data source, you would be able to bypass the above problem Write your own session implementation that stores data in a medium you can handle and share between all computers. This is tricky, and error-prone. Use a database to store your sessions.

LAB: Cookies & Sessions

Testing for Cookies

Different versions of browsers on different platforms define their cookie handling policies in different places. In IE, Windows XP:

choose Tools > Internet Options Click Privacy tab Click Advanced button under Settings Click Override automatic cookie handling Choose Prompt for both First- and

Testing for Cookies (cont)

In Firefox on Windows

Choose Tools > Options Click Privacy Expand the Cookies section Select ask me every time in the Keep Cookies dropdown menu

If you are using Firefox on Mac OS X, the steps are the same, but start by choosing Firefox > Preferences

setcookie() function

To see the effect of the setcookie() function, set your Web browser to ask before storing cookie.

setcookie() function

To send a cookie
Create new PHP document <?php # login.php 2. Validate the form // Check if the form has been submitted. if (isset($_POST['submitted'])) {
1.

require_once ('/mysql_connect.php'); // Connect to the db. $errors = array(); // Initialize error array.

To send a cookie (cont)


$query = "SELECT user_id, first_name FROM users WHERE email='$e' AND password='$p'"; $result = @mysql_query ($query); $row = mysql_fetch_array ($result, MYSQL_NUM);

Retrieve user_id and first_name for this user from database.

To send a cookie (cont)


if ($row) { // A record was pulled from the database. // Set the cookies & redirect. setcookie ('user_id', $row[0]); setcookie ('first_name', $row[1]);

If user entered the correct information, log the user in. The $row variable will have a value only if the preceding query returned at least one record

To send a cookie (cont)


$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']); // Check for a trailing slash. if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) { $url = substr ($url, 0, -1); // Chop off the slash. } // Add the page. $url .= '/loggedin.php'; header("Location: $url"); exit(); // Quit the script.

Redirect the user to another page

To send a cookie (cont)


} else { // No record matched the query. $errors[] = 'The email address and password entered do not match those on file.'; // Public message. $errors[] = mysql_error() . '<br /><br />Query: ' . $query; // Debugging message. } } // End of if (empty($errors)) IF. mysql_close(); // Close the database connection. } else { // Form has not been submitted. $errors = NULL; } // End of the main Submit conditional.

Complete the $row conditional and the $errors conditional, and the close the database connection

To send a cookie (cont)


// Begin the page now. $page_title = 'Login'; include ('./includes/header.html');
if (!empty($errors)) { // Print any error messages. echo '<h1 id="mainhead">Error!</h1> <p class="error">The following error(s) occurred:<br />'; foreach ($errors as $msg) { // Print each error. echo " - $msg<br />\n"; } echo '</p><p>Please try again.</p>'; }

Create the form


// Create the form. ?> <h2>Login</h2> <form action="login.php" method="post"> <p>Email Address: <input type="text" name="email" size="20" maxlength="40" /> </p> <p>Password: <input type="password" name="password" size="20" maxlength="20" /></p> <p><input type="submit" name="submit" value="Login" /></p> <input type="hidden" name="submitted" value="TRUE" /> </form> <?php include ('./includes/footer.html'); ?>

loggedin.php
?php # Script 9.2 Check the loggedin.php presence of a cookie // If no cookie is present, redirect the user. if (!isset($_COOKIE['user_id']) ) { // Start defining the URL. $url = 'http://' .

loggedin.php
// Check for a trailing slash. if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) { $url = substr ($url, 0, -1); // Chop off the slash. } $url .= '/index.php'; // Add the page. header("Location: $url"); exit(); // Quit the script.
}

// Set the page title and include the HTML header. $page_title = 'Logged In!'; include ('./includes/header.html'); // Print a customized message. echo "<h1>Logged In!</h1> <p>You are now logged in, {$_COOKIE['first_name']}!</p> <p><br /><br /></p>";
include ('./includes/footer.html'); ?>

Setting cookie parameters


setcookie (name, value, expiration, path, domain, secure);

The expiration argument is used to set a definitive length of time for a cookie to exist, specified in seconds. If it is not set, the cookie will continue to be functional until the user closes his or her browser.

Setting cookie parameters (cont)


Expiration time is determined by adding a particular number of minutes or hours to the current moment, retrieved using the time() function. The following line will set the expiration time of the cookie to be 1 hour (60 seconds times 60 minutes) from the current moment; setcookie (name, value,

Setting cookie parameters (cont)


The path and domain arguments are used to limit cookie to a specific folder within a Web site (the path) or to a specific host. For example, you could restrict a cookie to exist only while a user is within the admin folder of a domain (and the admin folders subfolders): setcookie (name, value,

Setting cookie parameters (cont)


Finally, the secure value dictates that a cookie should only be sent over a secure HTTPS connection. A 1 indicates that a secure connection must be used, and a 0 says that a standard connection is fine. setcookie (name, value, time()+3600, /admin/, , 1);

Setting cookie parameters (cont)

As with all functions that take arguments, you must pass the setcookie() values in order. To skip any parameter, use NULL or an empty string. The expiration and secure values are both integers and are therefore not quote.

To set a cookies expiration date

Change the two setcookie() lines to include an expiration date thats 60 minutes away

Deleting cookies
Create a new PHP document <?php # logout.php

Check for the existence of a user_id cookie if it is present, delete both cookies. // If no cookie is present, redirect the user. if (!isset($_COOKIE['user_id'])

Deleting cookies (cont)


// Start defining the URL. $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']); // Check for a trailing slash. if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) { $url = substr ($url, 0, -1); // Chop off the slash. } $url .= '/index.php'; // Add the page. header("Location: $url"); exit(); // Quit the script.
} else { // Delete the cookies. setcookie ('first_name', '', time()-300, '/', '', 0); setcookie ('user_id', '', time()-300, '/', '', 0); }

Deleting cookies (cont)


// Set the page title and include the HTML header. $page_title = 'Logged Out!'; include ('./includes/header.html');

Deleting cookies (cont)


// Print a customized message. echo "<h1>Logged Out!</h1> <p>You are now logged out, {$_COOKIE['first_name']}!</p > <p><br /><br /></p>";
include ('./includes/footer.html');

To create a logout link


Open header.html Change the links

Summary

Define cookies and session Create a Cookie: setcookie() Retrieve a Cookie Value: PHP $_COOKIE How to Delete a Cookie? Starting a PHP Session: The session_start() function must appear BEFORE the <html> tag: Destroying a Session: use the unset() or the session_destroy() function
Pros and Cons of Cookies and Sessions

Social Networks, Auctions, and Portals

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Copyright 2009 Pearson Education,

Slide 11-206

Inc.

Slide 11-206

Social Network Fever Spreads to the Professions


Class Discussion

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

How has the growth of social networking enabled the creation of more specific niche sites? What are some examples of social network sites with a financial or business focus? Describe some common features and activities on these social networking sites.
Slide 11-207

Social Networks and Online Communities

Internet began as community building technology for scientists, researchers The Well Early communities limited to bulletin boards, newsgroups 2002: Mobile Internet devices, blogs, sharing of rich media began new era of social networking Social networking one of most common
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 11-208

What Is an Online Social Network?

Area online where people who share common ties can interact with one

Involve:

A group of people Shared social interaction Common ties among members People who share an area for some period of time

e.g. MySpace, Friendster, Flickr, Facebook Portals and social networks moving closer together as portals add social networking features and community Copyright 2009 Pearson Slide 11-209 Education, Inc. Publishing as Prentice Hall sites add portal-like services

The Growth of Social Networks and Online Communities

Top 10 social networks account for over 90% social networking activity

MySpace: 50% of all social networking activity Users: Over 50% over 35, wealthy, with college degrees MySpace: 60 million/month Yahoo: 133 million/month

Unique visitors

Advertising revenue

Top 4 portals generate $12 billion annually Social networking sites: $1.4 billion

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 11-210

Types of Social Networks And Their Business Models

Early networking sites relied on subscriptions; today social networks rely primarily on advertising
General communities:

Offer opportunities to interact with general audience organized into general topics Advertising supported by selling ad space on pages and videos

Practice networks:

Offer focused discussion groups, help and knowledge related to area of shared practice or non-profit; Slide 11-211 advertising or user rely on

Copyright 2009 Pearson May be profit

Education, Inc. Publishing as Prentice Hall

donations

Types of Social Networks And Their Business Models (contd)

Interest-based social networks:

Offer focused discussion groups based on shared interest in some specific subject Usually advertising supported

Affinity communities:

Offer focused discussion and interaction with other people who share same affinity (self or group identification) Advertising and revenues from sales of products

Sponsored communities:

Created by government, non-profit or for-profit organizations for purpose of pursuing organizational goals
Slide 11-212

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Social Network sites for financial & business

LinkedIn display business profile and accomplishment StockTickr stock performance Duedee users rated against their virtual portfolio TradeKing to view trading styles Motley Fool online stock investment services
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 11-213

Social network for professional

DailyStrength for healthcare LawLink for law practitioners Sermo physicians INMobile wireless industry executives AdGabber advertising professionals
Slide 11-214

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Social Network Features and Technologies

Profiles Friends network Network discovery Favorites E-mail Storage Instant messaging

Message boards Online polling Chat Discussion groups Experts online Membership management tools

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 11-215

Insight on Technology

Social Operating Systems: Facebook vs. Google


Class Discussion

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

What does Mark Zuckerberg, Facebooks CEO, mean by social operating system? Why have Facebook applications become so popular? Do they have any limitations? How has Google responded? Which core functions can their programs
Slide 11-216

Online Auctions

Online auction sites among the most popular consumer-to-consumer sites on the Internet eBay: Market leader Several hundred different auction sites in U.S. alone

Established portals and online retail sites increasingly are adding auctions to their sites
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 11-217

Defining and Measuring the Growth of Auctions and Dynamic Pricing

Dynamic pricing

Airline tickets, coupons, college scholarships

Prices based on demand characteristics of customer and supply situation of seller Bundling
Trigger pricing Utilization pricing
Slide 11-218

Many types of dynamic pricing

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Personalization pricing

Defining and Measuring the Growth of Auctions and Dynamic Pricing


(contd)

Auctions

Type of dynamic pricing C2C auctions


Auction house an intermediary $25 billion gross revenue 2008

B2C auctions

Business owns assets; often used for excess goods $19 billion gross revenue 2008

Copyright 2009 CanPearson asused be Education, Inc. Publishing Prentice Hall

to allocate, bundle resources


Slide 11-219

Insight on Society

Dynamic Pricing: Is This Price Right?


Class Discussion

What is dynamic pricing? What are the various types of dynamic pricing?

Why would consumers be opposed to dynamic pricing? Is dynamic pricing anti-consumer?


Should customers be told that todays prices will change without notice? Or that some consumers pay less for this product, sometimes?
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 11-220

Revenues
Figure 11.3, Page 724

SOURCES: eMarketer, 2005; Jupiter Research, 2001; authors estimates. Copyright 2009 Pearson Slide 11-221
Education, Inc. Publishing as Prentice Hall

Benefits of Auctions

General

Liquidity Price discovery Price transparency Market efficiency Lower transaction costs Consumer aggregation Network effects
warehouse costs
Slide 11-222

For market-makers
No inventory, Copyright 2009 Pearson
Education, Inc. Publishing as Prentice Hall

Risks and Costs of Auctions for Consumers and Businesses


Delayed consumption costs Monitoring costs Possible solutions include:

Fixed pricing Watch lists Proxy bidding

Equipment costs Trust risks

Possible solutionrating systems (not always successful)

Fulfillment costs
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 11-223

Internet Auction Basics

Internet auctions different from traditional auctions


Last much longer (usually a week) Variable number of bidders who come and go from auction arena

Market power and bias in dynamically priced markets

Neutral: Number of buyers and sellers is few or equal


Seller bias: Few sellers and many buyers

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Buyer bias: Many sellers and few buyers

Slide 11-224

Internet Auction Basics (contd)

Price Allocation Rules

Uniform pricing rule: Multiple winners who all pay the same price
Discriminatory pricing rule: Winners pay different amount depending on what they bid

Public vs. private information

Prices bid may be kept secret

Bid rigging
Slide 11-225

Education, Inc. Publishing as Open markets


Copyright 2009 Pearson Prentice Hall

Bias in Dynamically Priced Markets


Figure 11.4, Page 729

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 11-226

Types of Auctions

English auctions:

Easiest to understand and most common


Single item up for sale to single seller Highest bidder wins

Traditional Dutch auction:


Uses a clock that displays starting price Clock ticks down price until buyer stops it
Slide 11-227

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Types of Auctions (contd)

Dutch Internet auction:

Public ascending price, multiple units


Final price is lowest successful bid, which sets price for all higher bidders

Name Your Own Price Auctions


Pioneered by Priceline Users specify what they are willing to pay for goods or services and multiple providers bid for their business not descend and are fixed
Slide 11-228

Prices do Education, Inc. Publishing as


Copyright 2009 Pearson Prentice Hall

Types of Auctions (contd)

Group Buying Auctions (Demand Aggregators)

Facilitate group buying of products at dynamically adjusted discount prices based on high volume purchases Based on two principles

Sellers are more likely to offer discounts to buyers purchasing in volume Buyers increase their purchases as prices fall

Professional Service AuctionsElance.com

Auction Aggregatorsuse Web crawlers to search thousands of Web auction sites and accumulate information on products, bids, auction duration, etc.

Unlicensed aggregators opposed by eBay


Slide 11-229

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

When to Use Auctions (And For What) In Business

Factors to consider

Type of product Product life cycle Channel management

Type of auction
Initial pricing Bid increments Auction length Number of items Price allocation rule Closed vs. open bidding
Slide 11-230

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Seller and Consumer Behavior at Auctions

Profit to seller: A function of arrival rate, auction length, and number of units at auction
Auction prices not necessarily the lowest

Reasons include herd behavior (tendency to gravitate toward, and bid for, auction listing with one or more existing bids) Winners regret Sellers lament Losers lament

Unintended results of participating in auctions:


Consumer trust an important motivating factor in auctions


Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 11-231

When Auction Markets Fail: Fraud and Abuse in Auctions

Markets fail to produce socially desirable outcomes in four situations: information asymmetry, monopoly power, public goods, and externalities.
Auction markets prone to fraud

Most common: Failure to deliver, failure to pay


Slide 11-232

2008 IC3 statistics:

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

35.7% of Internet fraud complaints

The Growth and Evolution of Portals


Portals: most frequently visited sites on the Web Gateways to the 40 - 50 billion Web pages

Most of top portals today began as search engines


Today provide navigation of the Web, commerce, and content (own and others) Enterprise portals an important function within organizations
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 11-233

Top 5 Portal/Search Engine Sites in the United States


Figure 11.6, Page 743

SOURCE: Compete.com, 2008; authors estimates Education, Inc. Publishing as


Prentice Hall

Copyright 2009 Pearson

Slide 11-234

Insight on Business

Battle of the Portals


Class Discussion

How many different kinds of portals are there? How do portals make money? What are the strengths of the top four portals: Yahoo, Google, MSN and AOL? Why did Google link up with AOL when AOL was losing audience share?
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 11-235

Types of Portals: General Purpose and Vertical Market

General purpose portals:

Attempt to attract very large general audience and then retain it on-site by providing in-depth vertical content channels E.g. Yahoo!, MSN

Vertical market portals:

Attempt to attract highly focused, loyal audiences with specific interest

Community (affinity group); e.g. iVillage.com Copyright 2009 Pearson Slide 11-236 Education, Inc. Publishing as Focused content; e.g. ESPN.com Prentice Hall

Two General Types of Portals: General Purpose and Vertical Market Portals
Figure 11.7, Page 747

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 11-237

Portal Business Models

ISP services (AOL, MSN)

Provide Web access, e-mail for monthly fee

General advertising revenue

Charge for impressions delivered

Tenancy deals

Fixed charge for number of impressions, exclusive partnerships, sole providers

Commissions on sales

Sales at site by independent providers

Subscription fees

Charging for premium content


Slide 11-238

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

E-commerce in Action: Yahoo! Inc.


Vision: Global Internet communications, commerce and media company Business model: Earns money from advertising, premium content sales, commissions and corporate services Financial analysis: Revenues continue to grow; operating margins positive but falling Strategic analysis

Growth through acquisition Competition: Google, Microsoft, Time Warner/AOL Outsources technology

Future prospects dim


Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 11-239

SUMMARY
Social Networks General communities Practice networks Interest-based social networks Affinity communities Sponsored communities Online Auctions Dynamic pricing: Prices based on demand characteristics of customer and supply situation of seller Types of dynamic pricing 1. Bundling 2. Trigger pricing 3. Utilization pricing 4. Personalization pricing Types of Auctions English auctions Traditional Dutch auction Dutch Internet auction Name Your Own Price Auctions Group Buying Auctions (Demand Aggregators) Professional Service Auctions Auction Aggregator

Types of Portals General purpose portals Vertical market portals Community (affinity group) Focused content Portal Business Models ISP services General advertising revenue Tenancy deals Commissions on sales Subscription fees
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 11-240

Chapter 1
Overview of Electronic Commerce

Learning Objectives
1.

2.

3.

4.

5.

Chapter 1

Define electronic commerce (EC) and describe its various categories. Describe and discuss the content and framework of EC. Describe the major types of EC transactions. Describe the digital revolution as a driver of EC. Describe the business environment as a driver of EC.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

242

Learning Objectives
6.
7.

8. 9.

10.

Describe some EC business models. Describe the benefits of EC to organizations, consumers, and society. Describe the limitations of EC. Describe the contribution of EC to organizations responding to environmental pressures. Describe online social and business networks.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 243

Chapter 1

Electronic Commerce: Definitions and Concepts

electronic commerce (EC) The process of buying, selling, transferring, or exchanging products, services, or information via computer networks.

Chapter 1

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

244

Electronic Commerce: Definitions and Concepts

e-business A broader definition of EC that includes not just the buying and selling of goods and services, but also servicing customers, collaborating with business partners, and conducting electronic transactions within an organization.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 245

Chapter 1

Electronic Commerce: Definitions and Concepts

PURE VERSUS PARTIAL EC

EC Organizations

Chapter 1

brick-and-mortar (old economy) organizations Old-economy organizations (corporations) that perform their primary business off-line, selling physical products by means of physical agents. virtual (pure-play) organizations Organizations that conduct their business Copyright activities solely2009 Pearson Education, Inc. online. Publishing as Prentice Hall

246

Electronic Commerce: Definitions and Concepts

click-and-mortar (click-and-brick) organizations Organizations that conduct some ecommerce activities, usually as an additional marketing channel.

Chapter 1

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

247

Electronic Commerce: Definitions and Concepts

1.1

Chapter 1

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

248

Electronic Commerce: Definitions and Concepts

INTERNET VERSUS NON-INTERNET EC

intranet An internal corporate or government network that uses Internet tools, such as Web browsers, and Internet protocols. extranet A network that uses the Internet to link multiple intranets.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 249

Chapter 1

Electronic Commerce: Definitions and Concepts

electronic market (e-marketplace) An online marketplace where buyers and sellers meet to exchange goods, services, money, or information.

Chapter 1

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

250

Electronic Commerce: Definitions and Concepts

Interorganizational information systems (IOSs) Communications systems that allow routine transaction processing and information flow between two or more organizations. intraorganizational information systems Communication systems that enable e-commerce activities to go on within individual organizations.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 251

Chapter 1

The EC Framework, Classification, and Content

Chapter 1

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

252

The EC Framework, Classification, and Content

CLASSIFICATION OF EC BY THE NATURE OF THE TRANSACTIONS OR INTERACTIONS

business-to-business (B2B) E-commerce model in which all of the participants are businesses or other organizations. business-to-consumer (B2C) E-commerce model in which businesses sell to individual shoppers.

Chapter 1

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

253

The EC Framework, Classification, and Content

e-tailing Online retailing, usually B2C. business-to-business-to-consumer (B2B2C) E-commerce model in which a business provides some product or service to a client business that maintains its own customers.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 254

Chapter 1

The EC Framework, Classification, and Content

consumer-to-business (C2B) E-commerce model in which individuals use the Internet to sell products or services to organizations or individuals who seek sellers to bid on products or services they need. mobile commerce (m-commerce) E-commerce transactions and activities conducted in a wireless environment.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 255

Chapter 1

The EC Framework, Classification, and Content

Chapter 1

location-based commerce (lcommerce) M-commerce transactions targeted to individuals in specific locations, at specific times. intrabusiness EC E-commerce category that includes all internal organizational activities that involve the exchange of goods, services, or information among various units and individuals in an organization.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

256

The EC Framework, Classification, and Content

Chapter 1

business-to-employees (B2E) E-commerce model in which an organization delivers services, information, or products to its individual employees. collaborative commerce (c-commerce) E-commerce model in which individuals or groups communicate or collaborate online. consumer-to-consumer (C2C) E-commerce model in which consumers
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

257

The EC Framework, Classification, and Content

Chapter 1

peer-to-peer Technology that enables networked peer computers to share data and processing with each other directly; can be used in C2C, B2B, and B2C e-commerce. e-learning The online delivery of information for purposes of training or education. e-government E-commerce model in which a government entity buys or provides goods, services, or information from 2009to businesses or individual or Pearson Education, Inc. Copyright Publishing as Prentice Hall citizens.

258

The EC Framework, Classification, and Content

exchange A public electronic market with many buyers and sellers. exchange-to-exchange (E2E) E-commerce model in which electronic exchanges formally connect to one another for the purpose of exchanging information.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 259

Chapter 1

The EC Framework, Classification, and Content

THE INTERDISCIPLINARY NATURE OF EC

The Google Revolution EC Failures EC Successes

Chapter 1

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

260

The EC Framework, Classification, and Content

Web 2.0 The second-generation of Internetbased services that let people generate content, collaborate, and share information online in perceived new wayssuch as social networking sites, wikis, communication tools, and folksonomies.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 261

Chapter 1

The EC Framework, Classification, and Content

Chapter 1

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

262

The Digital Revolution Drives E-Commerce

digital economy An economy that is based on digital technologies, including digital communication networks, computers, software, and other related information technologies; also called the Internet economy, the new economy, or the Web economy.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 263

Chapter 1

The Digital Revolution Drives E-Commerce

The digital revolution accelerates EC mainly by providing competitive advantage to organizations. The digital revolution enables many innovations

Chapter 1

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

264

The Business Environment Drives E-Commerce

THE BUSINESS ENVIRONMENT


The Business Environment Impact Model Business Pressures and Opportunities Organizational Response Strategies

Chapter 1

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

265

The Business Environment Drives E-Commerce

Chapter 1

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

266

EC BUSINESS MODELS

business model A method of doing business by which a company can generate revenue to sustain itself.

Chapter 1

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

267

EC BUSINESS MODELS

TYPICAL EC BUSINESS MODELS


Online direct marketing Electronic tendering systems for procurement

tendering (bidding) system Model in which a buyer requests would-be sellers to submit bids; the lowest cost or highest value bidder wins.

name-your-own-price model Model in which a buyer sets the price he or she is willing to pay and invites sellers to supply the good or service at that price.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 268

Chapter 1

EC BUSINESS MODELS

Find the best price

also known as a search engine model

Chapter 1

affiliate marketing An arrangement whereby a marketing partner (a business, an organization, or even an individual) refers consumers to the selling companys Web site. viral marketing Word-of-mouth marketing in which customers promote a product or service to friends or others. Copyright 2009 Pearson Education, Inc. 269
Publishing as Prentice Hall

EC BUSINESS MODELS

group purchasing Quantity (aggregated) purchasing that enables groups of purchasers to obtain a discount price on the products purchased.

Chapter 1

SMEs Small-to-medium enterprises. e-co-ops Another name for online group purchasing organizations. 2009 Pearson Education, Inc. Copyright
Publishing as Prentice Hall

270

EC BUSINESS MODELS

Online auctions Product customization and service personalization

customization Creation of a product or service according to the buyers specifications. personalization The creation of a service or information according to specific customer specifications.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 271

Chapter 1

EC BUSINESS MODELS

Chapter 1

Electronic marketplaces and exchanges Information brokers (infomediaries) Bartering Value-chain integrators Value-chain service providers Supply chain improvers Social networks, communities, and blogging Negotiation
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

272

EC BUSINESS MODELS

virtual world A user-defined world in which people can interact, play, and do business. The most publicized virtual world is Second Life.

Chapter 1

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

273

Benefits and Limitations of EC

THE BENEFITS OF EC

Benefits to Organizations Benefits to Consumers Benefits to Society Facilitating Problem Solving

Chapter 1

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

274

Benefits and Limitations of EC

THE LIMITATIONS AND BARRIERS OF EC


Technological Limitations Nontechnological Limitations social networks Web sites that connect people with specified interests by providing free services such as photo presentation, e-mail, blogging, and so on. Business-Oriented Networks Revenue Models2009 Pearson Education, and Business of Social Inc. Copyright 275 Publishing as Prentice Hall Networks

SOCIAL AND BUSINESS NETWORKS


Chapter 1

The Digital Enterprise

digital enterprise A new business model that uses IT in a fundamental way to accomplish one or more of three basic objectives: reach and engage customers more effectively, boost employee productivity, and improve operating efficiency. It uses converged communication and computing technology in a way that improves business processes.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 276

Chapter 1

The Digital Enterprise

corporate portal A major gateway through which employees, business partners, and the public can enter a corporate Web site.

Chapter 1

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

277

Managerial Issues
1.
2. 3.

4.

5.

6.

Is it real? Why is B2B e-commerce so attractive? There are so many EC failureshow can one avoid them? How can we exploit social/business networking? What should be my companys strategy toward EC? What are the top challenges of EC?
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 278

Chapter 1

Summary
1.

2. 3. 4. 5.

Definition of EC and description of its various categories. The content and framework of EC. The major types of EC transactions. The role of the digital revolution. The role of the business environment as an EC driver.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 279

Chapter 1

Summary
6.
7.

8. 9.

The major EC business models. Benefits of EC to organizations, consumers, and society. Barriers to EC. Social and business online networks.

Chapter 1

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

280

All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. Printed in the United States of America.

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall


Chapter 1 Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 281

E-commerce Business Models and Concepts

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Copyright 2009 Pearson Education,

Slide 2-282

Inc.

Slide 2-282

E-commerce Business Models Definitions

Business model

Set of planned activities designed to result in a profit in a marketplace

Business plan

Describes a firms business model

E-commerce business model

Uses/leverages unique qualities of Internet and Web


Slide 2-284

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 2-284

Key Ingredients of a Business Model


Table 2.1, Page 67

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 2-285

Slide 2-285

Value Proposition

Defines how a companys product or service fulfills the needs of customers Questions to ask:

Why will customers choose to do business with your firm instead of another? What will your firm provide that others do not or cannot?

Examples of successful value propositions:


Personalization/customization Reduction of product search, price discovery Copyright 2009 Pearson Slide 2-286 costs Education, Inc. Publishing as

Prentice Hall

Slide 2-286

Revenue Model

Describes how the firm will earn revenue, generate profits, and produce a superior return on invested capital

Major types:

Advertising revenue model Subscription revenue model

Transaction fee revenue model


Sales revenue model modelSlide 2-287
Slide 2-287

Copyright 2009 Pearson Affiliate revenue

Education, Inc. Publishing as Prentice Hall

Revenue Model
Revenue Model Examples Revenue source

Advertising
Subscription

Yahoo
WSJ.com Consumerreports.org

Fees from advertisers in exchange for advertisements


Fees from subscribers in exchange for content/services

Transaction fee
Sales

eBay E*Trade

Fees (commissions) for enabling or executing a transaction

Amazon, LLBean, Gap Sales of goods, information or services

Affiliate

MyPoints
Slide 2-288

Fees for business referrals

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Market Opportunity

Refers to a companys intended marketspace and overall potential financial opportunities available to the firm in that marketspace

Marketspace

Area of actual or potential commercial value in which company intends to operate

Realistic market opportunity

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Defined by revenueSlide 2-291 potential in each of market niches in which company hopes to

Slide 2-291

Competitive Environment

Refers to the other companies selling similar products and operating in the same marketspace. Also refers to the presence of substitute products and potential new entrants, as well as power of customers and suppliers

Influenced by:

Number of active competitors Each competitors market share Competitors profitability Competitors pricing

Includes both direct competitors and indirect competitors


Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 2-292

Slide 2-292

Competitive Advantage

Achieved when a firm can produce a superior product and/or bring product to market at a lower price than most, or all, of competitors

First mover advantage Unfair competitive advantage

Perfect market: No competitive advantages or asymmetries Leverage: When a company uses its competitive advantage to achieve more advantage in surrounding markets
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 2-293

Slide 2-293

Market Strategy

Plan that details how a company intends to enter a new market and attract customers

Best business concepts will fail if not properly marketed to potential customers

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 2-294

Slide 2-294

Organizational Development

Plan that describes how the company will organize the work that needs to be accomplished

Work is typically divided into functional departments


Hiring moves from generalists to specialists as company grows

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 2-295

Slide 2-295

Management Team

Employees of the company responsible for making the business model work Strong management team gives instant credibility to outside investors Strong management team may not be able to salvage a weak business model, but should be able to change the model and redefine the business as it becomes necessary
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 2-296

Slide 2-296

Categorizing E-commerce Business Models: Some Difficulties

No one correct way We categorize business models according to e-commerce sector (B2C, B2B, C2C) Type of e-commerce technology used can also affect classification of a business model

i.e., m-commerce
Slide 2-297

Some companies use multiple business


Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 2-297

Categories of B2C
1.
2. 3. 4. 5.

6.
7.

Portal E-tailer Content provider Transaction broker Market creator Service provider Community provider
Slide 2-298

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

B2C Business Models: Portal

Offers powerful search tools plus an integrated package of content and services

Typically utilizes a combined subscription/advertising revenues/transaction fee model Today, seen as destination site rather than gateway
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

May be general (horizontal) or

Slide 2-299

Slide 2-299

B2C Business Models: E-tailer


Online version of traditional retailer Types include:

Virtual merchants Bricks-and-clicks Catalog merchants Manufacturer-direct

Low barriers to entry


Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 2-300

Slide 2-300

B2C Business Models: Content Provider

Distribute digital content: information and entertainment, over the Web


Typical revenue models:

Subscription Pay for download Advertising

Variations:

Slide 2-301

Syndication Copyright 2009 Pearson aggregators Web Education, Inc. Publishing as


Prentice Hall

Slide 2-301

B2C Business Models: Transaction Broker

Processes online transactions for consumers


Primary value propositionsaving time and money Typical revenue modeltransaction fee Largest industries using this model:
Financial services Copyright 2009 Pearson Travel services Education, Inc. Publishing as

Prentice Hall Slide 2-302

Slide 2-302

B2C Business Models: Market Creator

Uses Internet technology to create markets that bring buyers and sellers together

Examples:

Priceline eBay

Typically uses a transaction fee revenue model


Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 2-303

Slide 2-303

B2C Business Models: Service Provider

Offers services online

e.g. Google: Google Maps, Google Docs, etc.

Value proposition

Valuable, convenient, time-saving, low-cost alternatives to traditional service providers

Revenue models

Subscription fees One-time payment


Slide 2-304

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 2-304

B2C Business Models: Community Provider

Creates online environment (social network) where people with similar interests can transact and communicate. Typical revenue model: Hybrid

Including advertising fees, subscription fees, sales revenues, transaction fees, affiliate fees

Examples:
MySpace Facebook Copyright 2009 Pearson Education, Inc. Publishing iVillage as Prentice Hall

Slide 2-305

Slide 2-305

Categories of B2B
1.
2. 3. 4. 5.

E-distributor E-procurement Exchanges Industry consortia Private industrial network

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 2-307

B2B Business Models: Edistributor

Supplies products and services directly to individual businesses Owned by one company seeking to serve many customers Example: Grainger.com

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 2-308

Slide 2-308

B2B Business Models: Eprocurement

Creates and sells access to digital electronic markets

Includes B2B service providers, application service providers (ASPs) Transaction fees, usage fees, annual licensing fees Software that helps firms organize procurement process
Slide 2-309

Revenue models:

Ariba

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 2-309

B2B Business Models: Exchanges

Electronic digital marketplace where suppliers and commercial purchasers can conduct transactions Usually owned by independent firms whose business is making a market Revenue model: Transaction fees Usually serve a single vertical industry Number of exchanges has fallen dramatically
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 2-310

Slide 2-310

B2B Business Models: Industry Consortia

Industry-owned vertical marketplaces that serve specific industries (e.g. automobile, chemical, floral, logging)

Supply smaller number of companies with product and services relevant to industry Sponsored by powerful industry players Strengthen traditional purchasing behavior

Exostar: Online trading exchange for aerospace and defense industry


Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 2-312

Slide 2-312

B2B Business Models: Private Industrial Networks

Digital networks designed to coordinate the flow of communications among firms engaged in business together Single firm network: Most common form

Wal-Mart

Industry-wide networks: Often evolve out of industry associations


Agentrics Copyright 2009 Pearson
Education, Inc. Publishing as Prentice Hall
Slide 2-313

Slide 2-313

Business Models in Emerging E-commerce Areas

Consumer-to-Consumer (C2C)

eBay, Half.com

Peer-to-Peer (P2P)

Kazaa, Cloudmark

M-commerce:

E-commerce models using wireless technologies PayPal Mobile Checkout, AOL MovieFone Technology platform continues to evolve
Slide 2-314

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 2-314

E-commerce Enablers: The Gold Rush Model

Internet infrastructure companies have profited the most, providing:


Hardware, software, networking, security


E-commerce software systems, payment systems, Databases

Hosting services, etc.

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 2-315

Slide 2-315

How the Internet and the Web Change Business: Strategy, Structure, and Process

E-commerce changes nature of players in an industry and their relative bargaining power by changing:

Basis of competition among rivals Barriers to entry Threat of new substitute products Strength of suppliers Bargaining power of buyers
Slide 2-317

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 2-317

Industry Value Chains

Set of activities performed in an industry by suppliers, manufacturers, transporters, distributors, and retailers that transform raw inputs into final products and services Internet reduces cost of information and other transactional costs for manufacturers, distributors, customers Leads to greater operational efficiencies, lowering prices, adding value for
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 2-318

Slide 2-318

E-commerce and Industry Value Chains


Figure 2.5, Page 102

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 2-319

Slide 2-319

Firm Value Chains

Set of activities that a firm engages in to create final products from raw inputs Internet effect:

Increases operational efficiency Enables product differentiation

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 2-320

Slide 2-320

E-commerce and Firm Value Chains


Figure 2.6, Page 103

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 2-321

Slide 2-321

Firm Value Webs

Networked business ecosystem that uses Internet technology to coordinate the value chains of business partners within an industry, or within a group of firms Coordinates a firms suppliers with its own production needs using an Internet-based supply chain management system
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 2-322

Slide 2-322

Internet-Enabled Value Web


Figure 2.7, Page 104

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 2-323

Slide 2-323

Business Strategy

Set of plans for achieving superior long-term returns on the capital invested in a business firm (i.e., a plan for making a profit in a competitive environment) Four generic strategies

Differentiation Cost Focus


Slide 2-324

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 2-324

Business Strategy: Cost

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

This strategy emphasizes efficiency by producing high volumes of standardized products. The product is often a basic no-frills product that is produced at a relatively low cost and made available to a very large customer base. Maintaining this strategy requires a continuous search for cost reductions
Slide 2-325

Business Strategy: Differentiation

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Differentiation is aimed at the broad market that involves the creation of a product or services that is perceived throughout its industry as unique. Charge a premium for its product design, brand image, technology, features, dealers, network, or customers service. Brand loyalty lowers customers'
Slide 2-326

Business Strategy: Focus

In this strategy the firm concentrates on a select few target markets. It is also called a segmentation strategy or niche strategy. The firm typically looks to gain a competitive advantage through product innovation and/or brand marketing rather than efficiency.
Slide 2-327

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Summary
Business model: Set of planned activities designed to result in a profit in a marketplace Business plan: Describes firms business model Elements of Business model 1. Value proposition 2. Revenue model ads, subscription fee, transaction fee, affiliates, sales 3. Market opportunity 4. Competitive environment 5. Competitive advantage 6. Market strategy 7. Organizational development 8. Management team E-Commerce Models 1. B2C Portal: Horizontal / vertical E-tailer: Virtual merchant / Brick and click / Catalog merchant / Manufacturer-direct 2. B2B e-distributor, e-procurement, Exhanges, Industry consortia, private industrial network 3. Others C2C, P2P,M-Commerce Impact: Basis of competition among rivals Barriers to entry Threat of new substitute products Strength of suppliers Bargaining power of buyers Business strategy:: Differentiation Cost Slide 2-328 Focus

Value chains Industry value chains Firm value chains Leads to greater operational efficiencies, lowering prices, adding value for customers
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Online Retail and Services

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Copyright 2009 Pearson Education,

Slide 9-329

Inc.

Major Trends in Online Retail, 2008-2009


1. 2. 3. 4. 5. 6.

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Social shopping Online retail increasingly profitable Buying online becomes normal, mainstream experience Selection of goods increases, including luxury and customized goods Average annual amount of purchases increases Specialty retail sites show most rapid growth
Slide 9-330

Major Trends in Online Retail, 2008-2009 (contd)


8. 9. 10. 11. 12.

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Increased use of interactive multimedia marketing Retail intermediaries strengthen in many areas Retailers increasingly efficient at integrating multiple channels Personalized goods, especially in apparel, become financially successful Online shopping becomes more multiseasonal
Slide 9-331

The Retail Industry

Retail industry divided into nine segments, each of which offers different opportunities for online retail

Informational opportunities

Direct purchasing opportunities

Consumer durables largest segment, then general merchandise Mail order/telephone order (MOTO) sector most similar to online retail sector
Sophisticated Copyright 2009 Pearson
Education, Inc. Publishing as Prentice Hall

order entry, delivery, inventory control systems


Slide 9-333

E-commerce Retail: The Vision


Greatly reduced search and transaction costs would result in customers using Web to find lowest prices Market entry costs would be much lower than those for physical storefronts, and online merchants would be more efficient than offline competitors Traditional offline physical store merchants would be forced out of business Some industries would become disintermediated as manufacturers built direct relationship with consumer Few of these assumptions were correctstructure of retail marketplace has not been revolutionized Internet has created new venues for multichannel firms and supported a few pure-play merchants
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 9-335

The Online Retail Sector Today

Online retailing segment, although smallest segment of retail industry, is growing at exceptionally fast rate Online retail revenues: $146 billion in 2008 Primary beneficiaries of growing consumer support: Established offline retailers with an online presence as well as first mover dot-com companies Top online retailers: Amazon, Staples,
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 9-336

Multi-Channel Integration

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Ability of offline traditional firms to integrate Web operations with physical store operations Provides integrated shopping experience Leverages value of physical store Examples: Wal-Mart, Target , JCPenney Types of integration
Slide 9-338

Analyzing the Viability of Online Firms

Economic viability: Ability of firms to survive as profitable business firms during a specified period (i.e. 1-3 years) Two business analysis approaches:

Strategic analysis

Focuses on both industry as a whole and firm

Financial analysis

How firm is performing Statement of operations: How much money (or loss) the firm is achieving based on current sales Copyright 2009 Pearson Slide 9-339 and costs. Education, Inc. Publishing as
Prentice Hall

Strategic Analysis Factors


Barriers to entry Power of suppliers Power of customers Existence of substitute products Industry value chain Nature of intra-industry competition Firm value chain Core competencies Synergies Technology Social and legal challenges
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 9-340

Financial Analysis Factors

Factors in assessing Statements of Operations


Revenues: Growing and at what rate? Cost of sales: Compared to revenues Gross margin: Gross profit divided by net sales Operating expenses Operating margin: Indication of companys ability to turn sales into pre-tax profit after operating expenses are deducted
Slide 9-341

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Financial Analysis Factors (contd)

Factors in assessing a Balance Sheet:


Current assets Current liabilities Ratio of current assets to liabilities (working capital)

Long-term debt

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 9-342

E-tailing Business Models

Four main types of online retail business models: Virtual merchant

Single channel Web firms that generate almost all revenues from online sales e.g. Amazon

Bricks-and-clicks

Companies with physical stores as primary retail channel, but also online offerings
Slide 9-343

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

e.g. Wal-Mart, J.C. Penney, Sears

E-tailing Business Models (contd)

Catalog merchant

Established companies that have national offline catalog operation as largest retail channel, but also have online capabilities e.g. Lands End, L.L. Bean, Victorias Secret

Manufacturer-direct

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Single or multi-channel manufacturers who sell directly online to consumers without intervention of retailers
Slide 9-344

E-commerce in Action: Amazon.com


Vision: Earths biggest selection, most customer-centric Business Model: Amazon Retail and Amazon Services (merchant and developer services) Financial Analysis: Greatly improved, but not yet consistently profitable; still heavy long-term debt Strategic Analysis/Business strategy: Maximize revenue, cut costs Strategic Analysis/Competition: Online and offline general merchandisers Strategic Analysis/Technology: Largest, most sophisticated collection of online retailing technologies available Strategic Analysis/Social, Legal: Antitrust, sales tax, patent lawsuits; ToysRUs lawsuit Future Prospects: Long-term profitability still uncertain
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 9-345

Common Themes in Online Retailing

Online retail fastest growing channel, has fastest growing consumer base, growing penetration rate across many categories of goods Many online retail firms have begun to raise prices Disintermediation has not occurred, and most manufacturers use Web primarily as an informational resource Most significant online growth has been that of offline general merchandiser giants who are focusing on extending brand to online channel Second area of rapid growth: specialty merchants
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 9-346

Insight on Technology

Using the Web to Shop Till You Drop


Class Discussion

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

What do shopping bots and comparison sites offer consumers? Why are shopping bots more successful with hard goods than soft goods? How can shopping bots compare luxury goods? How will adding content to comparison sites help consumers?
Slide 9-347

The Service Sector: Offline and Online

Service sector: Largest and most rapidly expanding part of economies of advanced industrial nations In the United States, services employs about 76% of labor force; accounts for $7.7 trillion of GDP in 2008

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 9-348

What are Services?

Service occupations:

Concerned with performing tasks in and around households, business firms, and institutions
Provide services to consumers, businesses, governments, and other organizations

Service industries:

Major service industry groups:


Finance, insurance, real estate Travel Professional services Business services Health services Copyright 2009 Pearson Slide 9-349 Educational services Education, Inc. Publishing as

Prentice Hall

Categorizing Service Industries

Within service industry groups, can be further categorized into:


Transaction brokers Hands-on service provider Knowledge- and information-intense, which makes them uniquely suited to ecommerce applications Amount of personalization and customization required differs depending on type of service
Slide 9-350

Services industry features:

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Online Financial Services

Online financial services sector example of e-commerce success story, but success is somewhat different from what had been predicted Brokerage industry transformed Effects less powerful in banking, insurance, real estate Multi-channel established financial services firms are showing fastest growth
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 9-351

Financial Service Industry Trends

Four generic kinds of financial services:

Storage of and access to funds


Protection of assets Means to grow assets Movement of funds Industry consolidation

Two important global trends

Financial Reform Act of 1998 amended GlassSteagall Act and allows banks, brokerages, and insurance firms to merge
Slide 9-352

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Movement toward integrated financial

Industry Consolidation and Integrated Financial Services


Figure 9.3, Page 592

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 9-353

Online Financial Consumer Behavior

Consumers attracted to online financial sites because of desire to save time and access information rather than save money Most online consumers use financial services firms for mundane financial management Greatest deterrents are fears about security and confidentiality
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 9-354

Multi-channel vs. Pure Online Financial Service Firms

Online consumers prefer multi-channel firms with physical presence Multi-channel firms

Lower customer acquisition, conversion, and retention costs Rely on Web sites, advertising to acquire customers Users utilize services more intensively Users shop more, are more price-driven and
Slide 9-357

Pure online firms

Copyright 2009 Pearson

Education, Inc. Publishing as Prentice Hall

Financial Portals and Account Aggregators

Financial portals

Provide comparison shopping services, independent financial advice and financial planning No financial services, revenues from advertising

e.g. Yahoo! Finance, Quicken.com, MSN Money


Pulls together all of a customers financial data at a personalized Web site Yodlee: Leading provider of account aggregation technology; used by Merrill Lynch, Chase, etc. Raises issues about privacy and control of personal data, security, etc.
Slide 9-358

Account aggregation

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Online Real Estate Services

Early vision: The historically local, complex, and agentdriven real estate industry would be transformed into a disintermediated marketplace where buyers and sellers would transact directly However, major impact is influencing of purchases offline

Impossible to complete property transaction online Main services are online property listings, loan calculators, research and reference material

Despite revolution in available information, there has not been a revolution in the industry value chain
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 9-359

Online Travel Services

One of most successful B2C e-commerce segments; attracts largest audience and slice of B2C revenues Internet becoming most common channel used to research travel and book reservations 2007: First year online bookings greater than offline

2008: Online travel bookings $105 billion; expected to grow to $162 billion by 2012
Popular because they offer more convenience (onestop content, commerce, community, customer service) than traditional travel agents For suppliers, offers a singular, focused customer pool that can be efficiently reached
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 9-361

Online Travel Services (contd)

Travel an ideal service/product for Internet


Information-intensive product Electronic producttravel arrangements can be accomplished for the most part online Does not require inventory

Does not require physical offices with multiple employees


Suppliers are always looking for customers to fill excess capacity
Slide 9-362

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

The Online Travel Market

Four major sectors:

Airline tickets:

Source of greatest revenues Tickets as a commodity

Hotel reservations Car rentals Cruises/tours

Two major segments:


Leisure/unmanaged business travel Managed business travel expected to be a major growth area as corporations seek better control of corporate travel expenses

Corporate online-booking solutions (COBS)


Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 9-364

Online Travel Industry Dynamics


Competition among online providers is intense

Price competition difficult


Industry has gone through period of consolidation as stronger, offline established firms purchased weaker and relatively inexpensive online firms Meta-search engines search Web for best prices, collect fees for providing consumer lowest price sites Suppliers (national airlines, hotel chains, etc.) are attempting to eliminate intermediariesglobal distribution systems and travel agenciesusing Web as means
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 9-365

The Travel Services Value Chain


Figure 9.7, Page 612

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 9-366

E-commerce in Action: Expedia.com

One of top players in online travel services, generating revenues of $2.7 billion in 2007 Vision: Create global travel marketplace Business model: Agency model and merchant model

Financial analysis: Assets catching up to liabilities


Strategic Analysis/Business strategy:

Acquire complementary and competing travel companies, broaden scope of offerings, and expand into foreign markets, especially Asia

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Slide 9-367

E-commerce in Action: Expedia.com

Strategic Analysis/Competition

Other online commercial travel Web sites (e.g. Travelocity) Direct suppliers of travel services Suppliers of inventory

Strategic Analysis/Technology

Developed a multi-layered platform capable of handling large transaction volumes, powerful search tools to assist consumers

Strategic Analysis/Social and Legal

Former parent company Taxation, international challenges, legislation on PII


Slide 9-368

Future Prospects
Challenges: Education, Inc. Publishing as
Prentice Hall Copyright 2009 Pearson

Economic conditions, cost control, competition

Online Career Services

Next to travel services, one of Internets most successful online services. Dominated by CareerBuilder, Monster, and Yahoo HotJobs Online recruiting provides more efficient and costeffective method of linking employers and potential employees, while reducing total time-to-hire Enables job hunters to more easily build, update, and distribute resumes while gathering information about prospective employers and conducting job searches Ideally suited for Web due to information-intense nature of process
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 9-369

Why are Job Sites So Popular?

Saves time and money for both job hunters and employers For employers:

Expand geographic reach of search, lower cost, and result in faster hiring decisions Make resumes more widely available, and provides a variety of related job-hunting services
Slide 9-370

For job seekers:

One of most important functions: Ability to establish market prices and terms
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

Recruitment Market Segments

Three major segments

General job recruitment:

Largest segment and primary focus

Executive search:

Highest revenue potential

Specialized job placement services:

Often run by professional societies


Slide 9-371

Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall

SHOPPING CART

Overview

What is a shopping cart? How does a shopping cart work?

What is a shopping cart?

A shopping cart is a software application that typically runs on the computer where your Web site is located (the Web server), and allows your customers to do things such as searching for a product in your store catalog, adding a selected product to a basket, and placing an order for it. The shopping cart "integrates" with the rest of your Web site. In other words, there are typically links on your Web pages that customers can click on, and which allow them to perform some of the functions described above.

What is a shopping cart?

Shopping carts are written in a variety of different programming languages. Some of them provide full access to the "source code", thus allowing experienced programmers to make modifications to the system features, some others don't. Some shopping carts run on Windows Web servers, some on Unix, others on both. In most cases, you can place the shopping cart on your Web server simply by transferring its files there using any FTP software.

How does a shopping cart work?

Typically, all shopping carts share the following structure. A shopping cart normally includes:

a database that stores information such as product details, customer data, order information, etc. a storefront that displays this information to store visitors (e.g. product detail pages, search pages, checkout pages, etc.) an administration area that allows you, the store administrator, to manage your store. For example, this is where you add products, set up shipping & payment options, process orders, etc.

How does a shopping cart work?

Because most of the information is contained in a database, the shopping cart creates pages in "real time" when a customer visits an ecommerce store and requests a specific page. The shopping cart pages don't exist until a customer requests one. The page is dynamically generated by the Web server by retrieving data from the database. So a store that has 4,000 products, does not actually store 4,000 product pages on the Web server. The pages are created on the fly when a customer visits the store and, for example, looks for a specific product.

Example of shopping cart: ProductCart

ProductCart uses a technology called Active Server Pages to created the store pages from a database. Other shopping carts may use different technology, such as PHP, CGI, Ruby on Rails, or Cold Fusion. The process remains the same. Information is retrieved from a database, and displayed to the customer within the graphical interface that the store administrator has created for the store. Different shopping carts offer store administrators different levels of flexibility in setting up how these pages will look.

Storefront vs. Administration

Most shopping carts include two components:

the storefront, which is what your customers will see (the catalog, the search pages, the checkout pages, etc.), the administration area, which is what you will use to manage the store.

Although you find both components in virtually all ecommerce applications available on the market, the features that each of them offers vary substantially.

Storefront

A good storefront should include at least the following features:

A store catalog that is easy to browse and that presents product information is a way that is both useful and graphically pleasing. A search feature that allows customers to quickly locate a specific product. The more filters are available on the search page, the better (e.g. price, part number, description, etc.) A customer service area where existing customers can change their account information, view previous orders, etc. There should also be a way for customers to retrieve a lost password. Special pages where customers can easily find products that are on sale, featured products, products that belong to the same brand, etc.

Administration area

A good administration area should include at least the following features:

A way to easily set general store settings such as the way products should be displayed (e.g. how many products will be shown on each catalog page), the currency and date format to be used, etc. A module to create and manage product categories, and order the way in which they are displayed on the storefront. A module to create and manage products, and assign them to categories. To improve productivity, there should be tools that allow you to change settings across multiple products at once (e.g. change the price for all products in the "tennis shoes" category).

Administration area (cont)

A way to assign options to products (e.g. color and size), with the ability to set price changes that are dependent on the selected option (e.g. if you select an XXL size shirt, then you pay an extra $5). To improve productivity, there should be tools that allow you to assign the same options to multiple products at once. Flexible ways to set multiple shipping (e.g. UPS Ground is free for order over $100), and payment options (e.g. real time credit card processing, COD, and NET 30, but the last one only for wholesale customers). A module to manage orders effectively (pending, processed, shipped, returned, etc.).

Merging the shopping cart with your Web site

How will your customers get to the product catalog? How can you make your home page link to the "Monthly Specials" page, created dynamically by the shopping cart? And how can you make the pages that the shopping cart creates look the same as your "About us" or "Contact us" page? The look and feel of your online store, and the way it merges with the rest of your Web site, are crucial elements of a successful ecommerce store.

Merging the shopping cart with your Web site (cont)

Typically, you will be able to create HTML links that take a user for any HTML page that you may create for your Web site (e.g. the "about us" page), to a page generated dynamically by the shopping cart, which retrieves information in real time from the database that contains your store catalog and store settings. For example, the "About Us" page could contain a link to a page created by the shopping cart that shows products that are on sale in that particular month (assuming that the shopping cart does have the ability to do so).

Merging the shopping cart with your Web site (cont)

How easy it is to place such links into your HTML pages varies however from application to application. Make sure to select a shopping cart that allows to do so quickly and easily. As for the graphical interface used by the shopping cart to display the store page, some shopping carts limit you to using pre-formatted templates. Stay away from that kind of ecommerce software. Choose a shopping cart that does not use templates, but rather allows you to use your own Web site design as the graphical interface for the store pages.

Saved Shopping Lists


Create a Shopping List
In the Shopping Basket, a user may store their frequently used items in a Shopping List. A user may have as many lists as they like. 1) 2) 3) 4) Take items to the Shopping Basket Click on Save as a Shopping List Name the List To access Saved Shopping List; Click on My Accounts and Click on Shopping Lists.

Adding Items to a Saved Shopping List


Add Items to a Saved Shopping List Find the catalog page of the item(s) you wish to add using one or more of the following methods. 1. Order Entry - Enter VWR cat #, unit of measure, and quantity, and Add to Basket. 2. Click on VWR cat # (from Shopping Basket). 3. Search - Perform search and click on blue, underlined description. 4. Select Shopping List. 5. Click Add to Shopping List.

Placing Your Order


Once you have added all items for purchase to your basket, select the Shopping Basket button found in the upper right hand corner of the screen. Review the items in Your Shopping Cart screen; click Update Basket if you have made any changes and then proceed with your purchase. Click Checkout. The VWR items will automatically be transferred into the Arizona BuyWays requisition. To return to Arizona BuyWays without adding an item to the requisition, click the Cancel Punchout button.

Checking Out

Once the shopper has filled his cart, he hits the "Checkout" button and is sent to this page. All of his "Shopping Cart" details (except for the product descriptions) are displayed here. There is also a form into which he enters his delivery details.

Building a simple PHP shopping cart

Setting up the database

Lets take as our example a bookseller. They are not the beststocked bookseller in the world, having as they do only three titles in stock, but it is enough for our example. Lets create the database and add some stock:

CREATE TABLE books


CREATE TABLE books ( id int(6) unsigned NOT NULL auto_increment, title varchar(100) NOT NULL default '', author varchar(100) NOT NULL default '', price decimal(3,2) NOT NULL default '0.00', PRIMARY KEY (id) ) TYPE=MyISAM;

INSERT INTO books VALUES


INSERT INTO books VALUES (1, 'Where God Went Wrong', 'Oolon Colluphid', '24.99'); INSERT INTO books VALUES (2, 'Some More of God\'s Greatest Mistakes', 'Oolon Colluphid', '17.99'); INSERT INTO books VALUES (3, 'Who Is This God Person Anyway?', 'Oolon Colluphid', '14.99');

Identify our requirements

The cart we are going to build should be pretty familiar to most internet users. It will provide a means of displaying a message on every page of the site (along the lines of You have 5 items in your shopping cart), which when clicked will take the customer to a list of the items in the cart; each item may be removed or have its quantity updated. As all of our stock details are stored in the database, the only piece of information that we need to store about each customer is the id of each product they have added to their cart. To do this, we are going to use PHPs built-in session handling capabilities.

Using sessions in PHP


PHPs session handling is very easy to understand. To switch it on, simply add session_start(); at the top of your code; you can then store values (or arrays) in session variables: $_SESSION['name'] = 'Matthew'; $_SESSION['age'] = 31; These $_SESSION variables will now be available to any PHP scripts on other pages (as long as youve included the session_start(); call first).

A short note on cookies

The default behaviour of PHP sessions is to store the session ID (a long string of numbers and letters that identifies you to the server) as a cookie on your computer; however, even if you have cookies disabled this functionality will still work PHP will instead append the session ID to each link on the site (in the form mypage.php?PHPSESSID=) so that it can continue to accurately track visitors from page to page.

Creating the cart

We will store the contents of the shopping cart as a comma-separated list of product ids in a session named (unsurprisingly) cart for example, a cart containing 1,1,3,1,2 has four items; three of product #1, and one each of products #2 and #3. Firstly, lets create the code to display the You have X items message on every page:

Function writeShoppingCart()
function writeShoppingCart() { $cart = $_SESSION['cart']; if (!$cart) { return '<p>You have no items in your shopping cart</p>'; } else { // Parse the cart session variable $items = explode(',',$cart); $s = (count($items) > 1) ? 's':''; return '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart</a></p>'; } }

Function writeShoppingCart()
This function first gets the value of the cart session variable into a local variable, mainly to save on typing. If the cart is empty, we return an appropriate message; if not, we use the explode() function to create an array of all the products in the cart, and then count() them and display the result (the $s variable is there to make plurals display correctly). Now we can display the correct message anywhere on the site: echo writeShoppingCart();

The shopping cart page itself (cart.php) can be arrived at in a couple of ways. The user may have clicked on the link created by the writeShoppingCart() function above; or, they may have clicked an Add to cart link on a product page. If it was the latter, we need to intercept that click and update our cart contents before displaying the new list of products simple enough, as all we need to do is append the id of the clicked product to the cart session variable. Our product links are going to look like this: <a href="cart.php?action=add&id=1">Add to cart</a> Dont worry about the action=add bit, well get to that later. The id can now be extracted from $_GET[id] and added to our cart:

$cart = $_SESSION['cart']; if ($cart) { $cart .= ','.$_GET['id']; } else { $cart = $_GET['id']; } $_SESSION['cart'] = $cart;

Multiple items, one product

As in our example above, it is entirely possible that a customer might have more than one of a certain product in their cart. As we dont want to list duplicate items when we display the contents, we need to figure out a way to combine any of the same product into one entry (with a corresponding quantity attached).

$cart = $_SESSION['cart']; if ($cart) { $items = explode(',',$cart); $contents = array(); foreach ($items as $item) { $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1; }

This time, after exploding the list of product ids, we have iterated through them to create a new array named $contents, which consists of key=>value pairs where the key is the product id and the value is the quantity of that product in the shopping cart. So to take our example above, a cart containing 1,1,3,1,2 would become an array where 1=>3, 2=>1, 3=>1.

Now that we have an accurate count of unique products, lets query the product database for each one and output its details into a table:

$total = 0; 2. $output[] = '<table>'; 3. foreach ($contents as $id=>$qty) { 4. $sql = 'SELECT * FROM books WHERE id = '.$id; 5. $result = $db->query($sql); 6. $row = $result->fetch();
1.

1.
2. 3.

4.

5.

extract($row); $output[] = '<tr>'; $output[] = '<td><a href="cart.php?action=delete&id= '.$id.'" class="r">Remove</a></td>'; $output[] = '<td>'.$title.' by '.$author.'</td>'; $output[] = '<td>&pound;'.$price.'</td>';

1.

2.

3.
4. 5. 6.

7.

$output[] = '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>'; $output[] = '<td>&pound;'.($price * $qty).'</td>'; $total += $price * $qty; $output[] = '</tr>'; } $output[] = '</table>'; $output[] = '<p>Grand total: &pound;'.$total.'</p>';

Pretty simple stuff we iterate through the new $contents array and query the database for each product id. Then we output the relevant details for each product; title, author and price, and at the bottom we show the grand total for the order. For each item, weve also included a link to remove the item from the cart, a textbox containing the current quantity of that item, and a total price (obviously this will only differ from the base price if the quantity is not 1). The reason Im using $output[] = ... is that I am buffering the output into an array to print to the screen later.

Deleting a product

As shown above, the link to delete a product from the cart follows the same format as the add a product link:
href="cart.php?action=delete&id=1 ">Remove</a> Lets expand on the code from earlier by adding a switch() statement to handle the different things that might happen to our cart: Download this code

<a

Updating a product

Lastly, we are going to allow customers to update the contents of their shopping cart by manually changing the value in the quantity box for each product. To make this work, well wrap the shopping cart table in a <form> so that the update cart button will submit the form: Download this code

Note that, even though the form uses the POST method, its action includes a GET variable, action=update. Again, we can expand our previous code to process any quantity updates: Download this code

This looks quite complicated, but its fairly straightforward; we interrogate the contents of the $_POST array (which holds all our quantity values) and extract the relevant id and value pairs. For each product, we then delete all the existing instances of it, and re-insert the new quantity. There are a number of ways this could have been done for example, by counting the existing number of each product present in the cart and figuring out whether we needed to add or remove items but this seemed the easiest way to process the quantity updates.

Final function

And thats about it! A functional and easy shopping cart script heres the final function to display the contents of the cart:

Summary

Definition of shopping cart Structure of shopping cart: database, storefront, administration area Storefront contains: search catalog, search feature, customer service area, special pages Administration area features: products display, create & manage products categories, assign options to products, set shipping, manage orders