小編給大家分享一下php如何實現購物車功能,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
1、需求分析
我們需要找到一種將數據庫連接到用戶的瀏覽器的方法。用戶能夠按目錄瀏覽商品。 用戶應該能夠從商品目錄中選取商品以便此后的購買。我們也要能夠記錄他們選中的物品。 當用戶完成購買,要合計他們的訂單,獲取運送商品細節,并處理付款。 創建一個管理界面,以便管理員在上面添加、編輯圖書和目錄。
2、解決方案
2.1 用戶視圖
2.2 管理員視圖
2.3 Book-O-Rama中的文件列表
3、實現數據庫3.1 創建book_sc數據庫的SQL代碼
CREATE DATABASE book_sc; #創建book_sc數據庫 USE book_sc; #使用book_sc數據庫 CREATE TABLE customers #創建用戶表 ( customerid INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, name CHAR(60) NOT NULL, address CHAR(80) NOT NULL, city CHAR(30) NOT NULL, state CHAR(10), zip CHAR(10), country CHAR(20) NOT NULL ); CREATE TABLE orders #創建訂單表 ( orderid INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, customerid INT UNSIGNED NOT NULL, amount FLOAT(6,2), date DATE NOT NULL, order_status CHAR(10), ship_name CHAR(60) NOT NULL, ship_address CHAR(80) NOT NULL, ship_city CHAR(30) NOT NULL, ship_state CHAR(20), ship_zip CHAR(10), ship_country CHAR(20) NOT NULL ); CREATE TABLE books #創建圖書表 ( isbn CHAR(13) NOT NULL PRIMARY KEY, author CHAR(80), title CHAR(100), catid INT UNSIGNED, price FLOAT(4,2) NOT NULL, description VARCHAR(255) ); CREATE TABLE categories #創建目錄表 ( catid INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, catname CHAR(60) NOT NULL ); CREATE TABLE order_items #訂單物品表 ( orderid INT UNSIGNED NOT NULL, isbn CHAR(13) NOT NULL, item_price FLOAT(4,2) NOT NULL, quantity TINYINT UNSIGNED NOT NULL, PRIMARY KEY(orderid,isbn) ); CREATE TABLE admin #管理員表 ( username char(16) NOT NULL PRIMARY KEY, password CHAR(40) NOT NULL ); GRANT SELECT,INSERT,UPDATE,DELETE on book_sc.* to book_sc@localhost IDENTIFIED by 'password';
3.2 數據庫測試數據文檔
USE book_sc; INSERT INTO books VALUES ('0672329166','Luke Welling and Laura Thomson','PHP and MySQL Web Development',1,49.99, 'PHP & MySQL Web Development teaches the reader to develop dynamic, secure e-commerce web sites. You will learn to integrate and implement these technologies by following real-world examples and working sample projects.'); INSERT INTO books VALUES ('067232976X','Julie Meloni','Sams Teach Yourself PHP, MySQL and Apache All-in-One',1,34.99, 'Using a straightforward, step-by-step approach, each lesson in this book builds on the previous ones, enabling you to learn the essentials of PHP scripting, MySQL databases, and the Apache web server from the ground up.'); INSERT INTO books VALUES ('0672319241','Sterling Hughes and Andrei Zmievski','PHP Developer\'s Cookbook',1,39.99, 'Provides a complete, solutions-oriented guide to the challenges most often faced by PHP developers\r\nWritten specifically for experienced Web developers, the book offers real-world solutions to real-world needs\r\n'); INSERT INTO categories VALUES (1,'Internet'); INSERT INTO categories VALUES (2,'Self-help'); INSERT INTO categories VALUES (5,'Fiction'); INSERT INTO categories VALUES (4,'Gardening'); INSERT INTO admin VALUES ('admin', sha1('admin'));
4、實現在線目錄
主頁-目錄
由以下代碼實現:
4.1 index.php
<?php /** * @author switch * @copyright 2015 * 網站首頁,顯示系統中的圖書目錄 */ //require_once語句和require語句完全相同,唯一區別是PHP會檢查該文件是否已經被包含過,如果是則不會再次包含。 require_once('book_sc_fns.php'); session_start(); //開始會話 do_html_header('Welcome to Book-O-Rama'); //頁頭 echo "<p>Please choose a category:</p>"; $cat_array = get_categories(); //從數據庫獲取目錄 display_categories($cat_array); //顯示目錄鏈接 if(isset($_SESSION['admin_user'])) //如果是管理員,顯示管理員操作 display_button("admin.php","admin-menu","Admin Menu"); do_html_footer(); //頁尾 ?>
4.2 book_fns.php文件中的函數get_categories()
function get_categories() //從數據庫中獲取目錄列表 { $conn = db_connect(); //連接數據庫 $query = "select catid,catname from categories"; $result = @$conn ->query($query); if(!$result) //查詢失敗,返回false return false; $num_cats = @$result ->num_rows; if($num_cats == 0) //數據庫中無目錄,返回false return false; $result = db_result_to_array($result); return $result; }
4.3 output_fns.php文件中的函數display_categories()
function display_categories($cat_array) //輸出目錄 { if(!is_array($cat_array)) { echo "<p>No categories currently available</p>"; return; } echo "<ul>"; foreach($cat_array as $row) { $url = "show_cat.php?catid=". $row['catid']; $title = $row['catname']; echo "<li>"; do_html_URL($url,$title); echo "</li>"; } echo "</ul>"; echo "<hr/>"; }
4.4 db_fns.php文件中的函數db_result_to_array()
function db_result_to_array($result) //結果到數組 { $res_array = array(); for($count = 0; $row = $result ->fetch_assoc(); $count++) $res_array[$count] = $row; return $res_array; }
Internet目錄下的所有圖書
由以下代碼實現:
4.5 show_cat.php
<?php /** * @author switch * @copyright 2015 * 顯示特定目錄包含的所有圖書 */ //require_once語句和require語句完全相同,唯一區別是PHP會檢查該文件是否已經被包含過,如果是則不會再次包含。 require_once('book_sc_fns.php'); session_start(); @$catid = $_GET['catid']; $name = get_category_name($catid); do_html_header($name); $book_array = get_books($catid); display_books($book_array); //如果是管理員,顯示管理界面按鈕 if(isset($_SESSION['admin_user'])) { display_button("index.php","continue","Continue Shopping"); display_button("admin.php","admin-menu","Admin Menu"); display_button("edit_category_form.php?catid=". $catid,"edit-category","Edit Category"); } else //否則顯示主界面按鈕 { display_button("index.php","continue-shopping","Continue Shopping"); } do_html_footer(); ?>
4.6 book_fns.php文件中的函數get_category_name()
function get_category_name($catid) //獲取目錄名 { $conn = db_connect(); //連接數據庫 $query = "select catname from categories where catid = '". $catid ."'"; $result = @$conn ->query($query); if(!$result) //查詢失敗,原因為查詢出錯 return false; $num_cats = @$result ->num_rows; if($num_cats == 0) //查詢失敗,原因為無目錄 return false; $row = $result ->fetch_object(); return $row ->catname; }
4.8 book_fns.php文件中的函數get_books()
function get_books($catid) //從數據庫中獲取圖書 { if((!$catid) || ($catid == '')) //如果目錄ID為空 return false; $conn = db_connect(); $query = "select * from books where catid = '". $catid ."'"; $result = @$conn ->query($query); if(!$result) //查詢失敗,原因為查詢出錯 return false; $num_books = @$result ->num_rows; if($num_books == 0) //查詢失敗,原因為無圖書 return false; $result = db_result_to_array($result); return $result; }
4.9 output_fns文件中的函數display_books()
function display_books($book_array) //輸出圖書 { if(!is_array($book_array)) echo "<p>No books currently available in this category</p>"; else //有圖書,建表 { echo "<table width = \"100%\" border=\"0\">"; foreach($book_array as $row) { $url = "show_book.php?isbn=". $row['isbn']; echo "<tr><td>"; // 如果圖片存在 if(@file_exists("images/". $row['isbn'] .".jpg")) { $title = "<img src=\"images/". $row['isbn'] .".jpg\" style=\"border: 1px solid black\"/>"; do_html_URL($url,$title); } else echo " "; echo "</td><td>"; $title = $row['title'] ." by ". $row['author']; do_html_URL($url,$title); echo "</td></tr>"; } echo "</table>"; } echo "<hr/>"; }
PHP and MySQL Web Development的詳細信息
由以下代碼實現:
4.10 show_book.php
<?php /** * @author switch * @copyright 2015 * 顯示特定圖書的詳細信息 */ //require_once語句和require語句完全相同,唯一區別是PHP會檢查該文件是否已經被包含過,如果是則不會再次包含。 require_once('book_sc_fns.php'); session_start(); $isbn = $_GET['isbn']; $book = get_book_details($isbn); do_html_header($book['title']); display_book_details($book); //設置繼續按鈕 $target = "index.php"; if($book['catid']) $target = "show_cat.php?catid = ". $book['catid']; //如果是管理員,顯示編輯鏈接 if(check_admin_user()) { display_button("edit_book_form.php?isbn=". $isbn,"edit-item","Edit Item"); display_button("admin.php","admin-menu","Admin Menu"); display_button($target,"continue","Continue"); } else { display_button("show_cart.php?new=". $isbn,"add-to-cart","Add". $book['title']." To My Shopping Cart"); display_button($target,"continue-shopping","Continue Shopping"); } do_html_footer(); ?>
4.11 book_fns.php文件中的函數get_book_details()
function get_book_details($isbn) //從數據庫中獲取一本圖書的詳細說明 { if((!$isbn) || ($isbn == '')) //如果圖書統一書號為空 return false; $conn = db_connect(); //連接數據庫 $query = "select * from books where isbn = '". $isbn ."'"; $result = @$conn ->query($query); if(!$result) //查詢失敗,原因為查詢出錯 return false; $result = @$result ->fetch_assoc(); return $result; }
4.12 output_fns.php文件中的函數display_book_details()
function display_book_details($book) //輸出圖書詳細說明 { if(is_array($book)) { echo "<table><tr>"; // 如果圖片存在 if(@file_exists("images/". $book['isbn'] .".jpg")) { $size = getimagesize("images/". $book['isbn'] .".jpg"); if(($size[0] > 0) && ($size[1] > 0)) { echo "<td><img src=\"images/". $book['isbn'] .".jpg\" style=\"border: 1px solid black\"/></td>"; } } echo "<td><ul>"; echo "<li><strong>Author:</strong>"; echo $book['author']; echo "</li><li><strong>ISBN:</strong>"; echo $book['isbn']; echo "</li><li><strong>Our Price:</strong>"; echo number_format($book['price'],2); echo "</li><li><strong>Description:</strong>"; echo $book['description']; echo "</li></ul></td></tr></table>"; } else { echo "<p>The details of this book cannot be displayed at this time.</p>"; } echo "<hr/>"; }
5、實現購物車
不使用參數的腳本只顯示購物車的內容
帶有參數new的腳本將添加一個物品到購物車
由以下代碼實現:
5.1 show_cart.php
<?php /** * @author switch * @copyright 2015 * 顯示用戶購物車的內容。也用來向購物車添加圖書 */ //require_once語句和require語句完全相同,唯一區別是PHP會檢查該文件是否已經被包含過,如果是則不會再次包含。 require_once('book_sc_fns.php'); session_start(); @$new = $_GET['new']; if($new) { if(!isset($_SESSION['cart'])) //購物車中無物品 { $_SESSION['cart'] =array(); $_SESSION['items'] = 0; $_SESSION['total_price'] = '0.00'; } if(isset($_SESSION['cart'][$new])) { $_SESSION['cart'][$new]++; } else { $_SESSION['cart'][$new] = 1; } $_SESSION['total_price'] = calculate_price($_SESSION['cart']); $_SESSION['items'] = calculate_items($_SESSION['cart']); } if(isset($_POST['save'])) { foreach($_SESSION['cart'] as $isbn => $qty) { if($_POST[$isbn] == '0') unset($_SESSION['cart'][$isbn]); else $_SESSION['cart'][$isbn] = $_POST[$isbn]; } $_SESSION['total_price'] = calculate_price($_SESSION['cart']); $_SESSION['items'] = calculate_items($_SESSION['cart']); } do_html_header("Your shopping cart"); if((@$_SESSION['cart']) && (array_count_values($_SESSION['cart']))) { display_cart($_SESSION['cart']); } else { echo "<p>There are no items in your cart</p><hr/>"; } $target = "index.php"; //如果只有一種物品添加到購物車,可以繼續購物 if($new) { $details = get_book_details($new); if($details['catid']) { $target = "show_cat.php?catid=". $details['catid']; } } display_button($target,"continue-shopping","Continue Shopping"); //SSL鏈接--需要配置,PS:沒配置,所以不能使用 // $path = $_SERVER['PHP_SELF']; //獲取路徑 // $server = $_SERVER['SERVER_NAME']; //獲取主機名 // $path = str_replace('show_cart.php','',$path); // display_button("https://". $server . $path ."checkout.php","go-to-checkout","Go To Checkout"); //非SSL鏈接 display_button("checkout.php","go-to-checkout","Go To Checkout"); do_html_footer(); ?>
5.2 output_fns.php文件中的函數display_cart()
function display_cart($cart,$change = true,$images = 1) //顯示購物車 { echo "<table border=\"0\" width=\"100%\" cellspacing=\"0\"> <form action=\"show_cart.php\" method=\"post\"> <tr> <th colspan=\"". (1 + $images) ."\" bgcolor=\" #cccccc\">Item</th> <th bgcolor=\"#cccccc\">Price</th> <th bgcolor=\"#cccccc\">Quantity</th> <th bgcolor=\"#cccccc\">Total</th> </tr>"; //輸出購物車中每一項 foreach($cart as $isbn => $qty) { $book = get_book_details($isbn); echo "<tr>"; if($images == true) { echo "<td align=\"left\">"; if(file_exists("images/". $isbn .".jpg")) { $size = getimagesize("images/". $isbn .".jpg"); if(($size[0] > 0) && ($size[1] > 1)) //圖片長寬 { echo "<img src=\"images/". $isbn .".jpg\" style=\"border: 1px solid black\" width=\"". ($size[0] / 3) ."\" height=\"". ($size[1] / 3) ."\"/>"; } } else echo " "; echo "</td>"; } echo "<td align=\"left\"> <a href=\"show_book.php?isbn=". $isbn ."\">". $book['title'] ."</a> by". $book['author'] ."</td> <td align=\"center\">\$". number_format($book['price'],2) ."</td><td align=\"center\">"; //如果允許更改數量 if ($change == true) { echo "<input type=\"text\" name=\"".$isbn."\" value=\"".$qty."\" size=\"3\">"; } else { echo $qty; } echo "</td><td align=\"center\">\$".number_format($book['price']*$qty,2)."</td></tr>\n"; } //總數 echo "<tr> <th colspan=\"". (2 + $images) ."\" bgcolor = \"#cccccc\"> </th> <th align = \"center\" bgcolor=\"#cccccc\">". $_SESSION['items'] ."</th> <th align = \"center\" bgcolor=\"#cccccc\">\$". number_format($_SESSION['total_price'],2) ."</th></tr>"; //保存按鈕 if($change == true) { echo "<tr> <td colspan = \"". (2 + $images) ."\"> </td> <td align = \"center \"> <input type=\"hidden\" name=\"save\"value=\"true\" /> <input type = \"image\" src = \"images/save-changes.gif\" border = \" 0 \" alt = \" Save Changes \" /> </td> <td> </td> </tr>"; } echo "</form></table>"; }
5.3 book_fns.php文件中的函數calculate_price()
function calculate_price($cart) //計算購物車中物品總價 { $price = 0.0; if(is_array($cart)) { $conn = db_connect(); foreach($cart as $isbn => $qty) { $query = "select price from books where isbn ='". $isbn ."'"; $result = $conn ->query($query); if($result) { $item = $result ->fetch_object(); $item_price = $item ->price; $price += $item_price * $qty; } } } return $price; }
5.4 book_fns.php文件中的函數calculate_items()
function calculate_items($cart) //計算購物車中的物品總數 { $items = 0; if(is_array($cart)) { foreach($cart as $isbn => $qty) $items += $qty; } return $items; }
獲取顧客的詳細信息
由以下代碼實現:
5.5 checkout.php
<?php /** * @author switch * @copyright 2015 * 向用戶顯示所有的訂單細節。獲取商品運送細節 */ //require_once語句和require語句完全相同,唯一區別是PHP會檢查該文件是否已經被包含過,如果是則不會再次包含。 require_once('book_sc_fns.php'); session_start(); do_html_header("Checkout"); if((@$_SESSION['cart']) && (array_count_values($_SESSION['cart']))) { display_cart($_SESSION['cart'],false,0); display_checkout_form(); } else { echo "<p>Thers are no items in your cart</p>"; } display_button("show_cart.php","continue-shopping","Continue Shopping"); do_html_footer(); ?>
5.6 output_fns.php文件中的display_checkout_form()
function display_checkout_form() //輸出付款臺界面 { ?> <br /> <table border="0" width="100%" cellspacng="0"> <form action="purchase.php" method="post"> <tr> <!--客戶信息--> <th colspan="2" bgcolor="#cccccc">Your Details</th> </tr> <tr> <td>Name</td> <td><input type="text" name="name" value="" maxlength="40" size="40"/></td> </tr> <tr> <td>Address</td> <td><input type="text" name="address" value="" maxlength="40" size="40"/></td> </tr> <tr> <td>City/Suburb</td> <td><input type="text" name="city" value="" maxlength="20" size="40"/></td> </tr> <tr> <td>State/Province</td> <td><input type="text" name="state" value="" maxlength="20" size="40"/></td> </tr> <tr> <td>Postal Code or Zip Code</td> <td><input type="text" name="zip" value="" maxlength="10" size="40"/></td> </tr> <tr> <td>Country</td> <td><input type="text" name="country" value="" maxlength="10" size="40"/></td> </tr> <tr> <!--運單信息--> <th colspan="2" bgcolor="#cccccc">Shipping Address(leave blank if as above)</th> </tr> <tr> <td>Name</td> <td><input type="text" name="ship_name" maxlength=""/></td> </tr> <tr> <td>Address</td> <td><input type="text" name="ship_address" value="" maxlength="40" size="40"/></td> </tr> <tr> <td>City/Suburb</td> <td><input type="text" name="ship_city" value="" maxlength="20" size="40"/></td> </tr> <tr> <td>State/Province</td> <td><input type="text" name="ship_state" value="" maxlength="20" size="40"/></td> </tr> <tr> <td>Postal Code or Zip Code</td> <td><input type="text" name="ship_zip" value="" maxlength="10" size="40"/></td> </tr> <tr> <td>Country</td> <td><input type="text" name="ship_country" value="" maxlength="20" size="40"/></td> </tr> <tr> <td colspan="2" align="center"> <p> <strong>Please press Purchase to confirm your purchase, or Continue Shopping to add or remove items.</strong> </p> <?php display_form_button("purchase","Purchase There Items"); ?> </td> </tr> </form> </table> <hr /> <?php }
已填寫好信息的訂單
獲取客戶信用卡信息
由以下代碼實現:
5.7 purchase.php
<?php /** * @author switch * @copyright 2015 * 從用戶獲取付款細節 */ //require_once語句和require語句完全相同,唯一區別是PHP會檢查該文件是否已經被包含過,如果是則不會再次包含。 require_once('book_sc_fns.php'); session_start(); do_html_header("Checkout"); //創建變量 $name = $_POST['name']; $address = $_POST['address']; $city = $_POST['city']; $zip = $_POST['zip']; $country = $_POST['country']; //如果訂單細節填滿 if(($_SESSION['cart']) && ($name) && ($address) && ($city) && ($zip) && ($country)) { if(insert_order($_POST) != false) { display_cart($_SESSION['cart'],false,0); display_shipping(calculate_shipping_cost()); display_card_form($name); display_button("show_cart.php","continue-shopping","Continue Shopping"); } else { echo "<p>Could not store data, please try again.</p><hr/>"; display_button('checkout.php','back','Back'); } } else { echo "<p>You did not fill in all the fields, please try again.</p><hr/>"; display_button('checkout.php','back','Back'); } do_html_footer(); ?>
5.8 order_fns.php文件中的函數insert_order()
function insert_order($order_details) //提取訂單細節作為變量 { extract($order_details); //設置郵寄地址為當前地址 if((!$ship_name) && (!$ship_address) && (!$ship_city) && (!$ship_state) && (!$ship_zip) &&(!$ship_country)) { $ship_name = $name; $ship_address = $address; $ship_city = $city; $ship_state = $state; $ship_zip = $zip; $ship_country = $country; } //連接數據庫 $conn = db_connect(); //事務開始,必須關閉自動提交 $conn ->autocommit(false); $query = "select customrid from customers where name ='". $name ."' and address = '". $address ."' and city = '". $city ."' and state = '". $state ."' and zip = '". $zip ."' and country = '". $country ."'"; $result = $conn ->query($query); if(@$result ->num_rows > 0) { $customer = $result ->fetch_object(); $customerid = $customer ->customerid; } else { $query = "insert into customers values ('','". $name ."','". $address ."','". $city ."','". $state ."','". $zip ."','". $country ."')"; $result = $conn ->query($query); if(!$result) return false; } $customerid = $conn ->insert_id; //返回上次查詢中自增量的ID $date = date("Y-m-d"); $query ="insert into orders values ('','". $customerid ."','". $_SESSION['total_price'] ."','". $date ."','PARTIAL','". $ship_name ."','". $ship_address ."','". $ship_city ."','". $ship_state ."','". $ship_zip ."','". $ship_country ."')"; $result = $conn ->query($query); if(!$result) return false; $query = "select orderid from orders where customerid ='". $customerid ."' and amount > (". $_SESSION['total_price'] ."-.001) and amount < (". $_SESSION['total_price'] ."+.001) and date ='". $date ."' and order_status = 'PARTIAL' and ship_name ='". $ship_name ."' and ship_address ='". $ship_address ."' and ship_city ='". $ship_city ."' and ship_state ='". $ship_state ."' and ship_zip ='". $ship_zip ."' and ship_country ='". $ship_country ."'"; $result = $conn ->query($query); if($result ->num_rows > 0) { $order = $result ->fetch_object(); $orderid = $order ->orderid; } else return false; foreach($_SESSION['cart'] as $isbn => $quantity) { $detail = get_book_details($isbn); $query = "delete from order_items where orderid = '". $orderid ."' and isbn = '". $isbn ."'"; $result = $conn ->query($query); $query = "insert into order_items values ('". $orderid ."','". $isbn ."',". $detail['price'] .",$quantity)"; $result = $conn ->query($query); if(!$result) return false; } //事務關閉,開啟自動提交 $conn ->commit(); $conn ->autocommit(true); return $orderid; }
5.9 output_fns.php文件中的函數display_shipping()
function display_shipping($shipping) //輸出包含運費的總價 { ?> <table border="0" width="100%" cellspacing="0"> <tr> <td align="left">Shipping</td> <td align="right"> <?php echo number_format($shipping, 2); ?></td> </tr> <tr> <th bgcolor="#cccccc" align="left">TOTAL INCLUDING SHIPPING</th> <th bgcolor="#cccccc" align="right">$ <?php echo number_format($shipping+$_SESSION['total_price'], 2); ?></th> </tr> </table> <br /> <?php }
5.10 output_fns.php文件中的函數display_card_form()
function display_card_form($name) //輸出信用卡信息 { ?> <table border="0" width="100%" cellspacing="0"> <form action="process.php" method="post"> <tr> <th colspan="2" bgcolor="#cccccc">Credit Card Details</th> </tr> <tr> <td>Type</td> <td> <select name="card_type"> <option value="VISA">VISA</option> <option value="MasterCard">MasterCard</option> <option value="American Express">American Express</option> </select> </td> </tr> <tr> <td>Number</td> <td><input type="text" name="card_number" value="" maxlength="16" size="40"/></td> </tr> <tr> <td>AMEX code (if required)</td> <td><input type="text" name="amex_code" value="" maxlength="4" size="4"/></td> </tr> <tr> <td>Expiry Date</td> <td>Month <select name="card_month"> <option value="01">01</option> <option value="02">02</option> <option value="03">03</option> <option value="04">04</option> <option value="05">05</option> <option value="06">06</option> <option value="07">07</option> <option value="08">08</option> <option value="09">09</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> </select> Year <select name="card_year"> <?php for($y = date("Y"); $y < date("Y") + 10; $y++) echo "<option value =\"". $y ."\">" . $y ."</option>"; ?> </select> </td> </tr> <tr> <td>Name on Card</td> <td><input type="text" name="card_name" value="<?php echo $name; ?>" maxlength="40" size="40"/></td> </tr> <tr> <td colspan="2" align="center"> <p> <strong>Please press Purchase to confirm yout purchase, or Continue Shopping to add or remove items</strong> </p> <?php display_form_button('purchase','Purchase These Items'); ?> </td> </tr> </table> <?php }
5.11 db_fns.php文件中的函數db_connect()
function db_connect() //連接數據庫 { $result = new mysqli('localhost','book_sc','password','book_sc'); if(!$result) //連接失敗 return false; $result ->autocommit(true); return $result; }
6、實現付款
已填寫好信息的信用卡詳細信息
購物成功
由以下代碼實現:
6.1 process.php
<?php /** * @author switch * @copyright 2015 * 處理付款細節,將訂單添加到數據庫 */ //require_once語句和require語句完全相同,唯一區別是PHP會檢查該文件是否已經被包含過,如果是則不會再次包含。 require_once('book_sc_fns.php'); session_start(); do_html_header('Checkout'); //創建變量 $card_type = $_POST['card_type']; $card_number = $_POST['card_number']; $card_month = $_POST['card_month']; $card_year = $_POST['card_year']; $card_name = $_POST['card_name']; if(($_SESSION['cart']) && ($card_type) && ($card_number) && ($card_month) && ($card_year) &&($card_name)) { //顯示沒有圖片,不允許更改數量的購物車 display_cart($_SESSION['cart'],false,0); display_shipping(calculate_shipping_cost()); if(process_card($_POST)) { //清空購物車 session_destroy(); //這里可以寫一些關于信用卡接口調用的函數,調用銀行寫好的接口 echo "<p>Thank you for shopping with us. Your order has been placed.</p>"; display_button("index.php","continue-shopping","Continue Shopping"); } else { echo "<p>Could not process your card. Please contact the card issuer or try again.</p>"; display_button("purchase.php","back","Back"); } } else { echo "<p>You did not fill in all the fields,please try again.</p><hr/>"; display_button("purchase.php","back","Back"); } do_html_footer(); ?>
7、實現一個管理界面
登錄界面
由以下代碼實現:
7.1 admin.php
<?php /** * @author switch * @copyright 2015 * 主管理菜單 */ //require_once語句和require語句完全相同,唯一區別是PHP會檢查該文件是否已經被包含過,如果是則不會再次包含。 require_once('book_sc_fns.php'); session_start(); if((@$_POST['username']) && (@$_POST['passwd'])) //嘗試登陸 { $username = $_POST['username']; $passwd = $_POST['passwd']; if(login($username,$passwd)) { $_SESSION['admin_user'] = $username; } else { do_html_header("Problem:"); echo "<p>You could not be logged in.<br /> You must be logged in to view this page.</p>"; do_html_URL('login.php','Login'); do_html_footer(); exit; } } do_html_header("Administration"); if(check_admin_user()) { display_admin_menu(); } else { echo "<p>You are not authorized to enter the administration area.</p>"; do_html_URL('login.php','Login'); } do_html_footer(); ?>
7.2 user_auth_fns.php文件中的函數login()
function login($username,$password) //登錄 { $conn = db_connect(); //連接數據庫 if(!$conn) return 0; //檢查用戶名唯一性 $query = "select * from admin where username='". $username ."' and password = sha1('". $password ."')"; $result = $conn ->query($query); if(!$result) return 0; if($result ->num_rows > 0) return 1; else return 0; }
7.3 user_auth_fns.php文件中的函數check_admin_user()
function check_admin_user() //檢查是否是管理員 { if(isset($_SESSION['admin_user'])) return true; else return false; }
管理主界面
由以下代碼實現:
7.4 output_fns.php文件中的函數display_admin_menu()
function display_admin_menu() //輸出管理員菜單 { ?> <br /> <a href="index.php">Go to main site</a><br /> <a href="insert_category_form.php">Add a new category</a><br /> <a href="insert_book_form.php">Add a new book</a><br /> <a href="change_password_form.php">Change admin password</a><br /> <?php } function display_button($target,$image,$alt) //顯示按鈕 { echo "<div align= \" center \"><a href=\"". $target ."\"> <img src=\"images/". $image .".gif\" alt=\"". $alt ."\" border = \" 0 \" height = \" 50 \" width = \" 135 \" /></a></div>"; }
目錄添加
目錄添加成功
目錄頁中可以看出多了Novel目錄
由以下代碼實現:
7.5 insert_category_form.php
<?php /** * @author switch * @copyright 2015 * 允許管理員向數據庫中添加一個目錄的表格 */ //require_once語句和require語句完全相同,唯一區別是PHP會檢查該文件是否已經被包含過,如果是則不會再次包含 require_once('book_sc_fns.php'); session_start(); do_html_header(); if(check_admin_user()) { display_category_form(); do_html_URL("admin.php","Back to administrtion menu"); } else { echo "<p>You are not authorized to enter the administation area.</p>"; } do_html_footer(); ?>
7.6 insert_category.php
<?php /** * @author switch * @copyright 2015 * 向數據庫中插入新目錄 */ //require_once語句和require語句完全相同,唯一區別是PHP會檢查該文件是否已經被包含過,如果是則不會再次包含 require_once('book_sc_fns.php'); session_start(); do_html_header("Adding a category"); if(check_admin_user()) { if(filled_out($_POST)) { $catname =$_POST['catname']; if(insert_category($catname)) { echo "<p>Category \"". $catname ."\" was added to the database.</p>"; } else { echo "<p>Category \"". $catname ."\" could not be added to the database.</p>"; } } else { echo "<p>You have not filled out the form. Please try again.</p>"; } do_html_URL("admin.php","Back to administration menu"); } else { echo "<p>You are not authorised to view this page.</p>"; } do_html_footer(); ?>
管理員目錄界面
目錄編輯界面-可更新,刪除
目錄更新成功
目錄主界面可以看到該目錄更改成功
由以下代碼實現:
7.7 edit_category_form.php
<?php /** * @author switch * @copyright 2015 * 管理員編輯目錄的表單 */ //require_once語句和require語句完全相同,唯一區別是PHP會檢查該文件是否已經被包含過,如果是則不會再次包含。 require_once('book_sc_fns.php'); session_start(); do_html_header("Edit category"); if(check_admin_user()) { if($catname = get_category_name($_GET['catid'])) { $catid = $_GET['catid']; $cat = compact('catname','catid'); display_category_form($cat); } else { echo "<p>Could not retrieve category details.</p>"; } do_html_URL("admin.php","Back to administration menu"); } else { echo "<p>You are not authorized to enter the administration area.</p>"; } do_html_footer(); ?>
7.8 edit_category.php
<?php /** * @author switch * @copyright 2015 * 更新數據庫中的目錄 */ //require_once語句和require語句完全相同,唯一區別是PHP會檢查該文件是否已經被包含過,如果是則不會再次包含。 require_once('book_sc_fns.php'); session_start(); do_html_header("Updating category"); if(check_admin_user()) { if(filled_out($_POST)) { if(update_category($_POST['catid'],$_POST['catname'])) { echo "<p>Category was updated.</p>"; } else { echo "<p>Category could not be updated.</p>"; } } else { echo "<p>you have not filled out the form. Please try again.</p>"; } do_html_URL("admin.php","Back to administration menu"); } else { echo "<p>You are not authorised to view this page.</p>"; } do_html_footer(); ?>
7.9 admin_fns.php
<?php /** * @author switch * @copyright 2015 * 管理腳本使用的函數集合 */ function display_category_form($category = '') //顯示目錄表單 { //如果傳入存在目錄,進入編輯模式 $edit = is_array($category); ?> <form method="post" action="<?php echo $edit ? 'edit_category.php' :'insert_category.php'; ?>"> <table border="0"> <tr> <td>Category Name:</td> <td><input type="text" name="catname" size="40" maxlength="40" value="<?php echo $edit ? $category['catname'] : ''; ?>"/></td> </tr> <tr> <td <?php if(!$edit){echo "colspan=2";} ?> align="center"> <?php if($edit) { echo "<input type=\"hidden\" name=\"catid\" value=\"". $category['catid'] ."\" />"; } ?> <input type="submit" value="<?php echo $edit ? 'Update' : 'Add'; ?> Category"/></form> </td> <?php if($edit) //允許刪除存在目錄 { echo "<td> <form method=\"post\" action=\"delete_category.php\"> <input type=\"hidden\" name=\"catid\" value=\"". $category['catid'] ."\" /> <input type=\"submit\" value=\"Delete category\" /> </form></td>"; } ?> </tr> </table> <?php } function display_book_form($book = '') //顯示圖書表單 { //如果傳入圖書存在,進入編輯模式 $edit = is_array($book); ?> <form method="post" action="<?php echo $edit ? 'edit_book.php' : 'insert_book.php'; ?>"> <table border="0"> <tr> <td>ISBN:</td> <td><input type="text" name="isbn" value="<?php echo $edit ? $book['isbn'] : ''; ?>" /></td> </tr> <tr> <td>Book Title:</td> <td><input type="text" name="title" value="<?php echo $edit ? $book['title'] : ''; ?>" /></td> </tr> <tr> <td>Book Author:</td> <td><input type="text" name="author" value="<?php echo $edit ? $book['author'] : ''; ?>"/></td> </tr> <tr> <td>Category:</td> <td> <select name="catid"> <?php $cat_array = get_categories(); foreach($cat_array as $thiscat) { echo "<option value=\"". $thiscat['catid'] ."\""; if(($edit) && ($thiscat['catid'] == $book['catid'])) { echo " selected"; } echo ">". $thiscat['catname'] ."</option>"; } ?> </select> </td> </tr> <tr> <td>Price:</td> <td><input type="text" name="price" value="<?php echo $edit ? $book['price'] : ''; ?>" /></td> </tr> <tr> <td>Description:</td> <td><textarea rows="3" cols="50" name="description"><?php echo $edit ? $book['description'] : ''; ?></textarea></td> </tr> <tr> <td <?php if (!$edit) { echo "colspan=2"; }?> align="center"> <?php if ($edit) echo "<input type=\"hidden\" name=\"oldisbn\" value=\"".$book['isbn']."\" />";?> <input type="submit" value="<?php echo $edit ? 'Update' : 'Add'; ?> Book" /></form></td> <?php if ($edit) { echo "<td> <form method=\"post\" action=\"delete_book.php\"> <input type=\"hidden\" name=\"isbn\" value=\"".$book['isbn']."\" /> <input type=\"submit\" value=\"Delete book\"/> </form></td>"; } ?> </td> </tr> </table> </form> <?php } function display_password_form() //顯示更改密碼表單 { ?> <br /> <form action="change_password.php" method="post"> <table width="250" cellpadding="2" cellspacing="0" bgcolor="#cccccc"> <tr> <td>Old password:</td> <td><input type="password" name="old_passwd" size="16" maxlength="16"/></td> </tr> <tr> <td>New password:</td> <td><input type="password" name="new_passwd" size="16" maxlength="16"/></td> </tr> <tr> <td>Repeat new password:</td> <td><input type="password" name="new_passwd2" size="16" maxlength="16"/></td> </tr> <tr> <td colspan="2" align="center"><input type="submit" value="Change password"/></td> </tr> </table> </form> <br /> <?php } function insert_category($catname) //目錄插入 { $conn = db_connect(); //數據庫連接 $query = "select * from categories where catname='". $catname ."'"; $result = $conn ->query($query); if((!$result) || ($result ->num_rows != 0)) return false; $query = "insert into categories values ('','". $catname ."')"; $result = $conn ->query($query); if(!$result) return false; else return true; } function insert_book($isbn,$title,$author,$catid,$price,$description) //圖書插入 { $conn = db_connect(); //連接數據庫 $query = "select * from books where isbn='". $isbn ."'"; $result = $conn ->query($query); if((!$result) || ($result ->num_rows != 0)) return false; $query = "insert into books values ('". $isbn ."','". $author ."','". $title ."', '". $catid ."','". $price ."','". $description ."')"; $result = $conn ->query($query); if(!$result) return false; else return true; } function update_category($catid,$catname) //更改目錄名稱 { $conn = db_connect(); //連接數據庫 $query = "update categories set catname='". $catname ."' where catid='". $catid ."'"; $result = @$conn ->query($query); if(!$result) return false; else return true; } function update_book($oldisbn,$isbn,$title,$author,$catid,$price,$description) { $conn = db_connect(); //連接數據庫 $query = "update books set isbn='". $isbn ."', title='". $title ."', author='". $author ."', catid='". $catid ."', price ='". $price ."', description='". $description ."' where isbn='". $oldisbn ."'"; $result = @$conn ->query($query); if(!$result) return false; else return true; } function delete_category($catid) //刪除目錄 { $conn = db_connect(); //連接數據庫 $query = "select * from books where catid='". $catid ."'"; $result = @$conn ->query($query); if((!$result) || (@$result ->num_rows > 0)) //如果該目錄有圖書,無法刪除該目錄 return false; $query = "delete from categories where catid='". $catid ."'"; $result = @$conn ->query($query); if(!$result) return false; else return true; } function delete_book($isbn) //刪除圖書 { $conn = db_connect(); //連接數據庫 $query = "delete from books where isbn='". $isbn ."'"; $result = @$conn ->query($query); if(!$result) return false; else return true; } ?>
7.10 目錄刪除操作,圖書添加,更新,刪除操作基本與上述操作差不多,這里就不在演示,可以下載代碼查看
8、擴展
本項目創建了一個相當簡單的PHP購物車系統。我們還可以對它進行許多改進和提高:
在真正的在線商店,可能必須建立一些訂單記錄和實施系統——在這個系統中,用戶無法看到已經預定了的訂單。
顧客希望在不必與我們聯系的前提下就能檢查到他們的訂單處理情況。用戶應當可以通過一種身份驗證方式使之能夠查看自己以前的訂單,并且也可以將操作與個人情況緊密地結合起來。也更方便我們收集一些用戶習慣信息。
圖書的圖片可以通過FTP之類的服務傳輸到該網站的圖像目錄并給它們取一個合適的名字??梢园盐募陷d到圖片插入頁,以使該操作方便一些。
可以添加用戶登錄、個性化設置以及書目推薦、在線評論、會員制度、庫存級別檢查等??梢蕴砑拥墓δ苁欠浅6嗟?。
以上是“php如何實現購物車功能”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。