1. Trang chủ
  2. » Công Nghệ Thông Tin

Beginning PHP6, Apache, MySQL Web Development- P19 pot

30 354 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Beginning PHP6, Apache, MySQL Web Development- P19 pot
Thể loại Textbook chapter
Định dạng
Số trang 30
Dung lượng 499,23 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

The fourth table is named ecomm_order_details and contains a detailed list of the products in each order: order_id INTEGER UNSIGNED The ID of the order this information belongs to.. The

Trang 1

The next table you create is called ecomm_orders and contains the main order information:

order This will auto - increment and is the table ’ s primary key

placed the order This is a foreign key that references ecomm_customers

shipping_address_2 VARCHAR(50) Shipping contact ’ s address line 2

(can be left empty)

Trang 2

The fourth table is named ecomm_order_details and contains a detailed list of the products in each

order:

order_id INTEGER UNSIGNED The ID of the order this information belongs

to This is a foreign key that references

ecomm_orders

order_qty INTEGER UNSIGNED How many of the item the customer wants

foreign key that references ecomm_products

The fifth and final table is named ecomm_temp_cart and is used to temporarily store the shopping

cart ’ s product list while the customer is browsing:

session INTEGER UNSIGNED The customer ’ s session identifier

product_code CHAR(5) The product associated with this order This is a

foreign key that references ecomm_products

You now have a mechanism set up so that you can store all your products, customers, and the

information associated with the orders they place

You may be wondering why the temporary information is stored in the database Certainly the list of

shopping - cart items can be stored as $_SESSION variables or in cookies, but storing the information in

the database lets you keep track of orders that customers never complete — information that would be

lost if it were stored in the user ’ s session or in cookies This is commonly called shopping - cart

abandonment, and it is considered one of the major obstacles e - commerce ventures face Data in this

temporary cart can really help you glean information about your customers, such as:

Percentage of potential sales: You can gauge what percentage of visitors or potential

customers are abandoning their carts If it ’ s exceedingly high, then your checkout procedure

may be too complicated or convoluted for them to finish the process, or perhaps your

shipping costs are not made clear up - front, and people are forced into faking their shopping

carts to determine shipping costs

Analysis of Stock: You can track any trends in the items that are consistently being put in the

cart before abandonment If the same items are found to be abandoned, then perhaps there is

something wrong with your checkout procedure for these items, the shipping costs are

exceedingly high, or the price for the item itself is too high based on your competitors ’ rates

This would require greater analysis of the cost of the flagged items to ensure that you ’ re

being competitive

Trang 3

Periods of use: You can track any trends in when your customers are leaving items in the

cart If you find that a large number of customers are abandoning their carts during your web site or server maintenance, perhaps the workload on the server is causing your site to load slowly, and your customers are losing patience and leaving their carts In this instance, you would want to schedule such maintenance for a time when your site has the fewest shoppers

online As you can see, what people don ’ t buy can be just as informative as what they do buy

By understanding these key concepts and where to glean this information, you can find a large amount of helpful tracking information You should use this table as a reference when trying to enhance sales of your product or services Many professionals use this table to help them better their site, their services, and their products and company overall

The type of person shopping also factors into this equation For example, younger (and generally more na ï ve) shoppers are likely to quickly click through your offerings and either impulsively make a purchase or abandon the process at the last moment, from fear of committing to a purchase they may know little about Then there are older shoppers, who are generally wiser This potential base of customers is more likely to try to verify the legitimacy of your site and comparison - shop, which contributes to a large amount of abandonment

If a potential buyer is trying to find out any hidden costs along the way, he or she is likely to find two other competitors online and move through the entire shopping process, to find the true and final cost, then select the one that is the cheapest and most reputable — and abandon the rest

Try It Out Adding Your Products

Now that you have a set of tables set up in your database, you need to populate them with some information In this exercise, you ’ ll do just that

1 Open your text editor, and type the following program:

< ?phprequire ‘db.inc.php’;

(“00001”, “CBA Logo T-shirt”, “This T-shirt will show off your CBA connection Our t-shirts are ‘ ‘all made of high quality and 100% preshrunk cotton.”,

17.95), (“00002”, “CBA Bumper Sticker”, “Let the world know you are a proud supporter of the CBA web site ‘ ‘with this colorful bumper sticker.”,

Trang 4

5.95),

(“00003”,

“CBA Coffee Mug”,

“With the CBA logo looking back at you over your morning cup of ‘

‘coffee, you are sure to have a great start to your day Our mugs ‘

‘are microwave and dishwasher safe.”,

8.95),

(“00004”,

“Superhero Body Suit”,

“We have a complete selection of colors and sizes for you to choose ‘

‘from This body suit is sleek, stylish, and won\’t hinder either ‘

‘your crime-fighting skills or evil scheming abilities We also ‘

‘offer your choice in monogrammed letter applique.”,

99.95),

(“00005”,

“Small Grappling Hook”,

“This specialized hook will get you out of the tightest places ‘

‘Specially designed for portability and stealth, please be aware ‘

‘that this hook does come with a weight limit.”,

139.95),

(“00006”,

“Large Grappling Hook”,

“For all your heavy-duty building-to-building swinging needs, this ‘

‘large version of our grappling hook will safely transport you ‘

‘throughout the city Please be advised however that at 50 pounds ‘

‘this is hardly the hook to use if you are a lightweight.”,

3 Open the file in your browser You should see confirmation that the products were

successfully loaded into the table

How It Works

You inserted each of your products into the ecomm_products table Notice that, although you

assigned sequential numbers as your products ’ product code, they are string values, and you are not

using the auto - increment feature This is because you may wish to assign product numbers based on

category, distributor/manufacturer, or another numbering scheme in the real world These product

codes may include letters and numbers

If you had no errors and your query didn ’ t cause the script to die, you should have seen the success

message displayed, and your products should now be in the database

Trang 5

Try It Out Creating the Store Home Page

In this exercise, you ’ ll create the home page that all users will see when they start to shop at your site

The home page is responsible for listing all the available products you have for sale Unfortunately, we can ’ t give you the image files through this book, but you can download them from the book ’ s

companion web site, or you can create your own

1 Open your text editor, and save the following as ecomm_shop.php

/head >

body >

< h1 > Comic Book Appreciation Store < /h1 >

< > < a href=”ecomm_view_cart.php” > View Cart < /a > < /p >

below, and click on the link for more information: < /p >

< table style=”width:75%;” >

< ?phprequire ‘db.inc.php’;

$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or die (‘Unable to connect Check your connection parameters.’);

mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db));

$query = ‘SELECT product_code, name, price FROM

ecomm_products ORDER BY

echo ‘ < td > < a href=”ecomm_view_product.php?product_code=’ $product_code ‘” > ’ $name ‘ < /a > < /td >

Trang 6

echo ‘ < td style=”text-align: right;” > < a href=”ecomm_view_product.php?’

‘product_code=’ $product_code ‘” > ’ $price ‘ < /a > < /td >

After querying the database to retrieve a list of products, you present the results in a table Each row

displays a thumbnail image, the name of the product, and its price Each element is also a link for the

customer to click, to view the product ’ s details You haven ’ t written ecomm_view_product.php yet,

so these links are a dead end for now, but you will code that script in the next section

Trang 7

$result = mysql_query($query, $db)or die(mysql_error($db));

echo ‘ < td > < a href=”ecomm_view_product.php?product_code=’ $product_code ‘” > ’ $name ‘ < /a > < /td >

echo ‘ < td style=”text-align: right;” > < a href=”ecomm_view_product.php?’ ‘product_code=’ $product_code ‘” > ’ $price ‘ < /a > < /td >

echo ‘ < /tr >

}

We are storing the product ’ s images in an images folder for this project, though you can store them elsewhere, if you would like The filename for the image is the same as the item ’ s product code, and thumbnail versions include the suffix _t

Try It Out Viewing the Products

A site with dead - end links is never a good thing, especially in this case, when the user is looking for more information about the product You are now going to create the page that displays the details of each product

1 Enter this code in your text editor, then save this file as ecomm_view_product.php

< ?phpsession_start();

require ‘db.inc.php’;

ecomm_products WHERE

product_code = “’ mysql_real_escape_string($product_code, $db) ‘”’;

$result = mysql_query($query, $db)or die(mysql_error($db));

if (mysql_num_rows($result) != 1) {

Trang 8

< h1 > Comic Book Appreciation Store < /h1 >

< > < a href=”ecomm_view_cart.php” > View Cart < /a > < /p >

< h2 > < ?php echo $name; ? > < /h2 >

< table >

< tr >

< td rowspan=”4” > < img src=”images/ < ?php echo $product_code; ? > jpg”

alt=” < ?php echo $name; ? > ”/ > < /td >

value=” < ?php echo $product_code; ? > ”/ >

< label for=”qty” > Quantity: < /label >

Trang 9

extract($row);

} else { $qty = 0;

}mysql_free_result($result);

} else { echo ‘ < input type=”submit” name=”submit” value=”Add to Cart”/ >

}

? < /div >

Trang 10

How It Works

First, you call the session_start() function because you will be accessing the session information

for the customer Then, you use the product_id value passed in the query string to retrieve the

product information from the ecomm_products table If an erroneous product_id has been provided

and there is no matching product in the database, then you redirect the customer back to the

You display the product ’ s information in the form of a table with pretty much the standard mix of

PHP and HTML you ’ ve grown accustomed to using throughout this book Things get interesting

again when it comes time to display the quantity field, for the customer to add the product to his or

her shopping cart

First you query the ecomm_temp_cart table, using the customer ’ s session ID The session ID is

retrieved by calling PHP ’ s session_id() function Your goal is to find out if the customer has

already placed this item in the shopping cart, and if so, in what quantity

Trang 11

Armed with this information, you can now display the quantity field in an appropriate manner.

value=”’ $qty ‘”/ >

if ($qty > 0) { echo ‘ < input type=”submit” name=”submit” value=”Change Qty”/ >

} else { echo ‘ < input type=”submit” name=”submit” value=”Add to Cart”/ >

}

The form element that the quantity field and action button are part of posts its information to

ecomm_update_cart.php It sends the product code, the desired quantity, the action to be performed

on the cart, and a redirect location where the customer should be sent next

Try It Out Adding, Changing, and Deleting Items in the Cart

In this exercise, you ’ ll write the script that updates the contents of the cart It is responsible for handling the addition of items, updating/removing items, and clearing out the entire contents of the shopping cart

1 Type in this code, and save it as ecomm_update_cart.php :

< ?phprequire ‘db.inc.php’;

$session = session_id();

$qty = (isset($_POST[‘qty’]) & & ctype_digit($_POST[‘qty’])) ? $_POST[‘qty’] : 0;

$product_code = (isset($_POST[‘product_code’])) ? $_POST[‘product_code’] : ‘’;

$action = (isset($_POST[‘submit’])) ? $_POST[‘submit’] : ‘’;

$redirect = (isset($_POST[‘redirect’])) ? $_POST[‘redirect’] : ‘ecomm_shop.php’;

switch ($action) {case ‘Add to Cart’:

if (!empty($product_code) & & $qty > 0) { $query = ‘INSERT INTO ecomm_temp_cart (session, product_code, qty) VALUES

(“’ $session ‘”, “’ mysql_real_escape_string($product_code, $db) ‘”, ‘ $qty ‘)’;

Trang 12

case ‘Empty Cart’:

$query = ‘DELETE FROM ecomm_temp_cart

2 Go back to the product description page of the Superhero Body Suit Enter a number in the

quantity field, and add the product to your cart You will be redirected to the same page, but

this time the field will reflect the quantity of suits you ’ ve just added to your cart

3 Change the quantity to zero, and click the button that is now labeled “ Change Qty, ” to remove

the suits from your shopping cart

How It Works

All of the code to manage your shopping cart is contained in one file, ecomm_update_cart.php The

correct course of action is determined by the value of action as posted from the previous form First,

you retrieve the user ’ s session ID, and then you filter the incoming values:

Trang 13

$session = session_id();

$qty = (isset($_POST[‘qty’]) & & ctype_digit($_POST[‘qty’])) ? $_POST[‘qty’] : 0;

$product_code = (isset($_POST[‘product_code’])) ? $_POST[‘product_code’] : ‘’;

$action = (isset($_POST[‘submit’])) ? $_POST[‘submit’] : ‘’;

$redirect = (isset($_POST[‘redirect’])) ? $_POST[‘redirect’] : ‘ecomm_shop.php’;

The first case of the switch statement handles adding products to the ecomm_temp_cart table for the user Afterwards, it redirects the user to the page specified in $redirect (which should be

case ‘Add to Cart’:

if (!empty($product_code) & & $qty > 0) { $query = ‘INSERT INTO ecomm_temp_cart (session, product_code, qty) VALUES

(“’ $session ‘”, “’ mysql_real_escape_string($product_code, $db) ‘”, ‘ $qty ‘)’;

mysql_query($query, $db) or die(mysql_error($db));

} header(‘Location: ‘ $redirect);

exit();

break;

The next case is responsible for changing the quantity of an item in the cart If the value of $qty is greater than 0, then you send an UPDATE query to MySQL If the value of $qty is 0, then the product ’ s record in ecomm_temp_cart should be removed, so you issue a DELETE query

case ‘Change Qty’:

if (!empty($product_code)) {

if ($qty > 0) { $query = ‘UPDATE ecomm_temp_cart SET

qty = ‘ $qty ‘ WHERE

session = “’ $session ‘” AND product_code = “’

mysql_real_escape_string($product_code, $db) ‘”’;

} else { $query = ‘DELETE FROM ecomm_temp_cart WHERE

session = “’ $session ‘” AND product_code = “’

mysql_real_escape_string($product_code, $db) ‘”’;

} mysql_query($query, $db) or die(mysql_error($db));

} header(‘Location: ‘ $redirect);

exit();

break;

Trang 14

The final case in the switch statement handles the event in which the customer is emptying his or her

shopping cart entirely You do this by sending a DELETE query to delete all records in the ecomm_

temp_cart that have the user ’ s session ID

case ‘Empty Cart’:

$query = ‘DELETE FROM ecomm_temp_cart

Try It Out Viewing the Shopping Cart

In this exercise, you ’ ll create the page to view the contents of the shopping cart

1 Same drill as usual enter this code, and save it as ecomm_view_cart.php :

$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or

die (‘Unable to connect Check your connection parameters.’);

Trang 15

FROM ecomm_temp_cart t JOIN ecomm_products p ON t.product_code = p.product_code

WHERE session = “’ $session ‘”

ORDER BY t.product_code ASC’;

$result = mysql_query($query, $db) or die (mysql_error($db));

$rows = mysql_num_rows($result);

if ($rows == 1) { echo ‘ < > You currently have 1 product in your cart < /p >

} else { echo ‘ < > You currently have ‘ $rows ‘ products in your cart < /p >

}

if ($rows > 0) {

? < table style=”width: 75%;” >

< tr >

< th style=”width: 100px;” > < /th > < th > Item Name < /th > < th > Quantity < /th >

< th > Price Each < /th > < th > Extended Price < /th >

< /tr >

< ?php $total = 0;

code= < ?php echo $product_code; ? > > < img src=”images/ < ?php echo $product_code;

< td >

< form method=”post” action=”ecomm_update_cart.php” >

< div >

value=” < ?php echo $qty; ? > ”/ >

value=” < ?php echo $product_code; ? > ”/ >

Ngày đăng: 03/07/2014, 07:20