Nội dung chính
1. Tạo giỏ hàng PHP (Shopping Cart PHP)
Tạo giỏ hàng PHP – Shopping Cart PHP
Hôm nay mình sẽ hướng dẫn các bạn tạo giỏ hàng PHP (shopping cart php) đơn giản nhất. Để trước khi bắt đầu mình sẽ show demo cho các bạn xem luôn nhé!. Dưới đây là kết quả sau khi chúng ta hoàn thành bài học tạo giỏ hàng PHP (shopping cart php):
Cảm thấy hứng khởi rồi phải không ^^. Bây giờ chúng ta bắt tay vào tạo giỏ hàng PHP (shopping cart php) nha!
Chuẩn bị file
Để tạo giỏ hàng PHP (shopping cart php) chúng ta sẽ có 5 file như sau:
- style.css
- config.php
- index.php
- cart_update.php
- view_cart.php
Vì đây chỉ là demo tạo giỏ hàng PHP (shopping cart php) nên các bạn bỏ 5 file trong cùng 1 thư mục nha (cùng cấp). Và demo này sẽ chạy trên localhost nhé!
Bước 1: Tạo cơ sở dữ liệu
Các bạn mở phpmyadmin và chạy câu lệnh sau để tạo database và dữ liệu để chúng ta thực hành:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
CREATE DATABASE IF NOT EXISTS `demo` USE `demo`; CREATE TABLE IF NOT EXISTS `product` ( `product_id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `description` varchar(255) DEFAULT NULL, `image` varchar(255) DEFAULT NULL, `price` int(10) DEFAULT '0', PRIMARY KEY (`product_id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; INSERT INTO `product` (`product_id`, `name`, `description`, `image`, `price`) VALUES (1, 'toyota', 'Toyota Sienna 2015 là một trong những chiếc minivan bán chạy nhất tại Mỹ. Nhìn chung, mẫu xe này được đánh giá là rộng rãi, an toàn và tiết kiệm nhiên liệu.', 'img_1.jpg', 100), (2, 'camry', 'Không chỉ kiêu hãnh với vẻ bên ngoài mà Toyota Camry 2018 còn gây thiện cảm với mọi khách hàng đặc biệt với vẻ nội thất đẳng cấp. ', 'img_2.jpg', 200); |
Bước 2: Tạo file style.css
File này dùng để chỉnh sửa giao diện tạo giỏ hàng PHP (shopping cart php) của chúng ta các bạn chép đoạn sau vào:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
#products-wrapper { width: 800px; margin-right: auto; margin-left: auto; font: 12px Arial, Helvetica, sans-serif; } .container { width: 800px; margin-right: auto; margin-left: auto; } .products { width: 60%; float:left; margin-right: 10px; } .product { margin-bottom: 10px; height: 100px; background: #F0F0F0; padding: 10px; border: 1px solid #DDD; border-radius: 5px; box-shadow: 2px 2px 2px #F8F8F8; } .product .product-thumb { float: left; height: 100px; width: 100px; margin-right: 10px; } .product .product-content{ overflow:hidden; } .product .product-content h3 { font-size: 18px; margin: 0px; padding: 0px; color: #707070; } .product .product-info { float: right; font-size: 13px; font-weight: bold; margin-top:10px; } .shopping-cart{ width: 30%; float:left; background: #F0F0F0; padding: 10px; border: 1px solid #DDD; border-radius: 5px; } .shopping-cart h2 { background: #E2E2E2; padding: 4px; font-size: 14px; margin: -10px -10px 5px; color: #707070; } .shopping-cart h3,.view-cart h3 { font-size: 12px; margin: 0px; padding: 0px; } .shopping-cart ol{ padding: 1px 0px 0px 15px; } .shopping-cart .cart-itm, .view-cart .cart-itm{ border-bottom: 1px solid #DDD; font-size: 11px; font-family: arial; margin-bottom: 5px; padding-bottom: 5px; } .shopping-cart .remove-itm, .view-cart .remove-itm{ font-size: 14px; float: right; background: #D5D5D5; padding: 4px; line-height: 8px; border-radius: 3px; } .shopping-cart .remove-itm:hover, .view-cart .remove-itm:hover{ background: #C4C4C4; } .shopping-cart .remove-itm a, .view-cart .remove-itm a{ color: #888; text-shadow: 1px 1px 1px #ECECEC; text-decoration:none; } .check-out-txt{ float:right; } /*** view cart **/ .view-cart{ width: 80%; float:left; background: #F0F0F0; padding: 10px; border: 1px solid #DDD; border-radius: 5px; } .view-cart .p-price{ float: right; margin-right: 10px; font-size: 12px; font-weight: bold; } .view-cart .product-info{width:60%;} |
Bước 3: Tạo file config.php
File này dùng để cấu hình kết nối cơ sở dữ liệu mà chúng ta đã làm ở bước 1. Các bạn có thể chỉnh sửa lại thông tin kết nối theo máy các bạn nhé. Các bạn chép đoạn sau vào file config.php.
1 2 3 4 5 6 7 8 |
<?php $currency = '$'; // đơn vị tiền tệ $db_username = 'root'; // user name $db_password = '123456';// password $db_name = 'demo'; // tên cơ sở dữ liệu $db_host = 'localhost'; $mysqli = new mysqli($db_host, $db_username, $db_password,$db_name); ?> |
Bước 4: Tạo file index.php
Đây sẽ là trang chính của chúng ta dùng để hiển thị sản phẩm và giỏ hàng. Các bạn chép đoạn sau vào file index.php.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
<?php session_start(); include_once("config.php"); ?> <html> <header> <link href="style.css" rel="stylesheet"> </header> <body> <div class="container"><h1>Tất cả sản phẩm</h1> <div id="products-wrapper"> <div class="products"> <?php //URL hiện tại của trang. cart_update.php sẽ chuyển lại trang này. $current_url = base64_encode($_SERVER['REQUEST_URI']); $results = $mysqli->query("SELECT * FROM product ORDER BY product_id ASC"); if ($results) { //output results from database while($obj = $results->fetch_object()) { echo '<div class="product">'; echo '<form method="post" action="cart_update.php">'; echo '<div class="product-thumb"><img src="images/'.$obj->image.'" width="100px"></div>'; echo '<div class="product-content"><h3>'.$obj->name.'</h3>'; echo '<div class="product-desc">'.$obj->description.'</div>'; echo '<div class="product-info">Giá '.$currency.$obj->price.' <input type="text" size="5" name="product_qty" value="1"><button class="add_to_cart">Thêm vào giỏ hàng</button></div>'; echo '</div>'; echo '<input type="hidden" name="product_id" value="'.$obj->product_id.'" />'; echo '<input type="hidden" name="type" value="add" />'; echo '<input type="hidden" name="return_url" value="'.$current_url.'" />'; echo '</form>'; echo '</div>'; } } ?> </div> <div class="shopping-cart"> <h2>Giỏ Hàng</h2> <?php if(isset($_SESSION["products"])) { $total = 0; echo '<ol>'; foreach ($_SESSION["products"] as $cart_itm) { echo '<li class="cart-itm">'; echo '<span class="remove-itm"><a href="cart_update.php?removep='.$cart_itm["id"].'&return_url='.$current_url.'">×</a></span>'; echo '<h3>'.$cart_itm["name"].'</h3>'; echo '<div class="p-code">Mã sản phẩm : '.$cart_itm["id"].'</div>'; echo '<div class="p-qty">Số lượng : '.$cart_itm["qty"].'</div>'; echo '<div class="p-price">Giá :'.$currency.$cart_itm["price"].'</div>'; echo '</li>'; $subtotal = ($cart_itm["price"]*$cart_itm["qty"]); $total = ($total + $subtotal); } echo '</ol>'; echo '<span class="check-out-txt"><strong>Tổng : '.$currency.$total.'</strong> <a href="view_cart.php">Thanh toán!</a></span>'; echo '<span class="empty-cart"><a href="cart_update.php?emptycart=1&return_url='.$current_url.'">Xóa tất cả</a></span>'; }else{ echo 'Giỏ hàng trống'; } ?> </div> </div> </div> </body> </html> |
Giải thích: Vì tạo giỏ hàng PHP sử dụng biến $_SESSION nên chúng ta phải khai báo trên đầu trang bằng hàm session_start(), và cũng lấy dữ liệu từ database nên chúng ta include file config.php bằng lệnh include_once(“config.php”). Phần hiển thị thông tin sản phẩm sẽ lấy từ database. Phần thông tin giỏ hàng sẽ lấy từ biến $_SESSION[“products”]. Biến này sẽ được tạo ở trang cart_update.php sau khi các bạn thêm sản phẩm vào giỏ hàng.
Bước 5: Tạo file cart_update.php
Các bạn chép đoạn sau vào file cart_update.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
<?php session_start(); //Bắt đầu session include_once("config.php"); //include config file //Xóa giỏ hàng bằng cách hủy SESSION if(isset($_GET["emptycart"]) && $_GET["emptycart"]==1) { $return_url = base64_decode($_GET["return_url"]); //return url session_destroy(); header('Location:'.$return_url); } //Thêm sản phẩm vào giỏ hàng if(isset($_POST["type"]) && $_POST["type"]=='add') { $product_id = filter_var($_POST["product_id"], FILTER_SANITIZE_STRING); //product id $product_qty = filter_var($_POST["product_qty"], FILTER_SANITIZE_NUMBER_INT); //số lượng $return_url = base64_decode($_POST["return_url"]); // url trả về //Giới hạn sản phẩm if($product_qty > 10){ die('<div align="center">Ví dụ này không quá 10 sản phẩm</div>'); } //Lấy thông tin chi tiết sản phẩm bằng product_id $results = $mysqli->query("SELECT name, price FROM product WHERE product_id='$product_id' LIMIT 1"); $obj = $results->fetch_object(); if ($results) { //Kiểm tra có dữ liệu hay không //Chuẩn bị array(mảng) để lưu thông tin sản phẩm $new_product = array(array('name'=>$obj->name, 'id'=>$product_id, 'qty'=>$product_qty, 'price'=>$obj->price)); if(isset($_SESSION["products"])) //Hàm kiểm tra nếu có sản phẩm trong giỏ hàng rồi thì cập nhật lại { $found = false; //Thiết lập mặc định ban đầu biến kiểm tra sản phẩm tồn tại thành false foreach ($_SESSION["products"] as $cart_itm) //vòng lặp mảng SESSION { if($cart_itm["id"] == $product_id){ //sản phẩm đã tồn tại trong mảng $product[] = array('name'=>$cart_itm["name"], 'id'=>$cart_itm["id"], 'qty'=>$product_qty, 'price'=>$cart_itm["price"]); $found = true; // Thiết lập biến kiểm tra sản phẩm tồn tại thành true }else{ //item doesn't exist in the list, just retrive old info and prepare array for session var $product[] = array('name'=>$cart_itm["name"], 'id'=>$cart_itm["id"], 'qty'=>$cart_itm["qty"], 'price'=>$cart_itm["price"]); } } if($found == false) //Không tìm thấy sản phẩm trong giỏ hàng { //Thêm mới sản phẩm vào mảng $_SESSION["products"] = array_merge($product, $new_product); }else{ //Tìm thấy sản phẩm đã có trong mảng SESSION nên chỉ cập nhật lại số lượng(QTY) $_SESSION["products"] = $product; } }else{ //Tạo biến SESSION mới hoàn toàn nếu không có sản phẩm nào trong giỏ hàng $_SESSION["products"] = $new_product; } } //Trở về lại trang cũ header('Location:'.$return_url); } //Xóa sản phẩm trong giỏ hàng if(isset($_GET["removep"]) && isset($_GET["return_url"]) && isset($_SESSION["products"])) { $product_id = $_GET["removep"]; //Lấy product_id để xóa $return_url = base64_decode($_GET["return_url"]); //lấy url hiện tại foreach ($_SESSION["products"] as $cart_itm) //Vòng lặp biến SESSION { if($cart_itm["id"]!=$product_id){ //Lọc lại giỏ hàng, sản phẩm nào trùng product_id muốn xóa sẽ bị loại bỏ $product[] = array('name'=>$cart_itm["name"], 'id'=>$cart_itm["id"], 'qty'=>$cart_itm["qty"], 'price'=>$cart_itm["price"]); } //Tạo mới biến SESSION lưu giỏ hàng $_SESSION["products"] = $product; } //Trở về lại trang cũ header('Location:'.$return_url); } |
Giải thích: file này sẽ đảm nhiệm chức năng thêm sản phẩm vào giỏ hàng, cập nhật lại giỏ hàng và xóa giỏ hàng. Nó sẽ nhận dữ liệu từ index.php sau khi các bạn bấm vào nút “Thêm vào giỏ hàng” dữ liệu sẽ được chuyển sang cart_update.php theo phương thức POST. Tại đây chúng ta sẽ xữ lý tất cả thông qua product_id được POST từ form. Các bạn có thể xem chú thích tạo giỏ hàng PHP (Shopping cart php) trong code mà mình đã chú thích rõ từng hàm.
Bước 6: Tạo file view_cart.php
File này sẽ hiển thị sau khi các bạn bấm vào phần “Thanh Toán” ở trang index.php. Các bạn chép đoạn sau vào file view_cart.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
<?php session_start(); include_once("config.php"); ?> <html> <header> <link href="style.css" rel="stylesheet"> </header> <body> <div class="container"><h1>Thanh Toán</h1> <div id="products-wrapper"> <div class="view-cart"> <?php if(isset($_SESSION["products"])) { $current_url = base64_encode($_SERVER['REQUEST_URI']); $total = 0; echo '<form method="post" action="PAYMENT-GATEWAY">'; echo '<ul>'; $cart_items = 0; foreach ($_SESSION["products"] as $cart_itm) { $product_id = $cart_itm["id"]; $results = $mysqli->query("SELECT name, description, price FROM product WHERE product_id ='$product_id' LIMIT 1"); $obj = $results->fetch_object(); echo '<li class="cart-itm">'; echo '<span class="remove-itm"><a href="cart_update.php?removep='.$cart_itm["id"].'&return_url='.$current_url.'">×</a></span>'; echo '<div class="p-price">'.$currency.$obj->price.'</div>'; echo '<div class="product-info">'; echo '<h3>'.$obj->name.' (Mã sản phẩm :'.$product_id.')</h3> '; echo '<div class="p-qty">Số lượng : '.$cart_itm["qty"].'</div>'; echo '<div>'.$obj->description.'</div>'; echo '</div>'; echo '</li>'; $subtotal = ($cart_itm["price"]*$cart_itm["qty"]); $total = ($total + $subtotal); echo '<input type="hidden" name="item_name['.$cart_items.']" value="'.$obj->name.'" />'; echo '<input type="hidden" name="item_code['.$cart_items.']" value="'.$product_id.'" />'; echo '<input type="hidden" name="item_desc['.$cart_items.']" value="'.$obj->description.'" />'; echo '<input type="hidden" name="item_qty['.$cart_items.']" value="'.$cart_itm["qty"].'" />'; $cart_items ++; } echo '</ul>'; echo '<span class="check-out-txt">'; echo '<strong>Tổng : '.$currency.$total.'</strong> '; echo '</span>'; echo '</form>'; }else{ echo 'Giỏ hàng trống'; } ?> </div> </div> </div> </body> </html> |
Giải thích: Đây thường là trang kiểm tra tổng quát sau khi tạo giỏ hàng PHP (Shopping cart php) và trước khi các bạn thực hiện thanh toán thông qua các phương thức như thanh toán online, internetbanking v.v.v. Phần thanh toán này các bạn có thể áp dụng vào bằng API của nhà cung cấp nha. Vì là demo đơn giản nên mình sẽ không đề cập trong bài viết này ^^.
Sau khi làm hết các bước trên các bạn truy cập vào trang index.php xem kết quả nhé! ví dụ: http://localhost/shop/index.php
2. Lời kết
Như vậy là mình đã hướng dẫn các bạn tạo giỏ hàng PHP (shopping cart php) đơn giản nhất. Các bạn có thể tùy chỉnh để áp dụng vào những dự án của các bạn. Nếu có thắc mắc các bạn hãy để lại bình luận nhé!.
Cám ơn các bạn đã xem bài viết của mình. Thân!
Nguồn: phpcanban.com
Tag: Shoppping cart php, Tạo giỏ hàng PHP, cách tạo giỏ hàng PHP (Shopping cart php), code tạo giỏ hàng PHP (Shopping cart php) đơn giản, demo tạo giỏ hàng PHP (Shopping cart php), hướng dẫn tạo giỏ hàng PHP (Shopping cart php) chi tiết