Làm cách nào để thêm nhiều mặt hàng vào giỏ hàng trong PHP?

Chức năng giỏ hàng là một phần quan trọng của mọi dự án Thương mại điện tử. Nó giúp người dùng chọn và mua nhiều mặt hàng cùng một lúc. Ngoài ra, giỏ hàng trực tuyến cho phép xem các mặt hàng đã chọn và tổng giá trước khi gửi đơn đặt hàng. Nếu bạn muốn xây dựng một giỏ hàng PHP đơn giản từ đầu, hướng dẫn từng bước này sẽ giúp bạn rất nhiều. Trong hướng dẫn này, chúng tôi sẽ cung cấp hướng dẫn đầy đủ và mã ví dụ để tạo một giỏ mua hàng đơn giản trong PHP bằng SESSION và MySQL

Kịch bản giỏ hàng ví dụ này được thiết kế theo cách có thể triển khai dễ dàng trong dự án PHP và hướng dẫn giúp bạn dễ hiểu khái niệm giỏ hàng trong ứng dụng web. Trong tập lệnh mẫu của chúng tôi, chúng tôi sẽ sử dụng phiên PHP để lưu trữ thông tin sản phẩm trong giỏ hàng. Sau khi người dùng gửi đơn đặt hàng, thông tin sản phẩm sẽ được chèn vào cơ sở dữ liệu bằng PHP và MySQL

Các chức năng sau sẽ được triển khai trong tập lệnh PHP Shopping Cart

  • Lấy sản phẩm từ cơ sở dữ liệu và liệt kê chúng trên trang web
  • Xây dựng thư viện tùy chỉnh để xử lý các hoạt động của giỏ hàng bằng PHP
  • Thêm nhiều sản phẩm vào giỏ hàng
  • Kiểm tra các mặt hàng giỏ hàng
  • Xem trước tóm tắt đơn đặt hàng và gửi

Trước khi bắt đầu, hãy xem cấu trúc tệp của tập lệnh giỏ hàng PHP

php_shopping_cart/
├── index.php
├── viewCart.php
├── checkout.php
├── orderSuccess.php
├── config.php
├── dbConnect.php
├── cartAction.php
├── Cart.class.php
├── js/
|   └── jquery.min.js
├── css/
|   ├── bootstrap.min.css
|   └── style.css
└── images/

Tạo bảng cơ sở dữ liệu

Một số bảng được yêu cầu trong cơ sở dữ liệu để lưu trữ thông tin về sản phẩm, khách hàng và đơn đặt hàng. Chúng tôi sẽ sử dụng 4 bảng cơ sở dữ liệu (sản phẩm, khách hàng, đơn đặt hàng và order_items) để tạo một giỏ mua hàng dựa trên phiên đơn giản trong PHP với MySQL

SQL sau đây tạo một bảng products để lưu trữ thông tin sản phẩm trong cơ sở dữ liệu MySQL

CREATE TABLE `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  `price` float(10,2) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

SQL sau đây tạo một bảng

CREATE TABLE `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  `price` float(10,2) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
0 để lưu trữ thông tin liên hệ của người dùng trong cơ sở dữ liệu MySQL

CREATE TABLE `customers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
  `last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `phone` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  `address` text COLLATE utf8_unicode_ci NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

SQL sau đây tạo một bảng

CREATE TABLE `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  `price` float(10,2) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
1 trong cơ sở dữ liệu MySQL để lưu trữ thông tin đơn đặt hàng do khách hàng gửi.
CREATE TABLE `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  `price` float(10,2) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
2 sẽ là một FOREIGN KEY được liên kết với bảng
CREATE TABLE `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  `price` float(10,2) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
0

CREATE TABLE `orders` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `customer_id` int(11) NOT NULL,
  `grand_total` float(10,2) NOT NULL,
  `created` datetime NOT NULL,
  `status` enum('Pending','Completed','Cancelled') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'Pending',
  PRIMARY KEY (`id`),
  KEY `customer_id` (`customer_id`),
  CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

SQL sau đây tạo một bảng

CREATE TABLE `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  `price` float(10,2) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
4 để lưu trữ các mục của mỗi đơn đặt hàng trong cơ sở dữ liệu MySQL.
CREATE TABLE `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  `price` float(10,2) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
5 sẽ là một FOREIGN KEY được liên kết với bảng
CREATE TABLE `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  `price` float(10,2) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
1

CREATE TABLE `order_items` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `order_id` int(11) NOT NULL,
  `product_id` int(11) NOT NULL,
  `quantity` int(5) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `order_id` (`order_id`),
  CONSTRAINT `order_items_ibfk_1` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Thư viện giỏ hàng (Cart. tầng lớp. php)

Thư viện Giỏ hàng là một PHP tùy chỉnh xử lý các hoạt động liên quan đến giỏ hàng. Các phương thức của lớp Cart giúp bạn tích hợp chức năng giỏ hàng trong PHP

  • nội dung () – Trả về toàn bộ nội dung giỏ hàng dưới dạng một mảng
  • get_item() – Trả về chi tiết một mặt hàng cụ thể trong giỏ hàng
  • total_items() – Trả về tổng số mặt hàng trong giỏ hàng
  • total() – Trả về tổng giá của giỏ hàng
  • insert() – Chèn các mặt hàng vào giỏ hàng và lưu chúng trong PHIÊN
  • update() – Cập nhật các mặt hàng trong giỏ hàng
  • remove() – Xóa một mặt hàng khỏi giỏ hàng
  • hủy () – Dọn sạch giỏ hàng và hủy PHIÊN
// Start session
if(!session_id()){
    session_start();
}

/**
 * Shopping Cart Class
 *
 * @package        PHP Library
 * @category    Shopping Cart
 * @author        CodexWorld Dev Team
 * @link        https://www.codexworld.com
 */
class Cart {
    protected $cart_contents = array();

    public function __construct(){
        // get the shopping cart array from the session
        $this->cart_contents = !empty($_SESSION['cart_contents'])?$_SESSION['cart_contents']:NULL;
        if ($this->cart_contents === NULL){
            // set some base values
            $this->cart_contents = array('cart_total' => 0, 'total_items' => 0);
        }
    }

    /**
     * Cart Contents: Returns the entire cart array
     * @param    bool
     * @return    array
     */
    public function contents(){
        // rearrange the newest first
        $cart = array_reverse($this->cart_contents);

        // remove these so they don't create a problem when showing the cart table
        unset($cart['total_items']);
        unset($cart['cart_total']);

        return $cart;
    }

    /**
     * Get cart item: Returns a specific cart item details
     * @param    string    $row_id
     * @return    array
     */
    public function get_item($row_id){
        return (in_array($row_id, array('total_items', 'cart_total'), TRUE) OR ! isset($this->cart_contents[$row_id]))
            ? FALSE
            : $this->cart_contents[$row_id];
    }

    /**
     * Total Items: Returns the total item count
     * @return    int
     */
    public function total_items(){
        return $this->cart_contents['total_items'];
    }

    /**
     * Cart Total: Returns the total price
     * @return    int
     */
    public function total(){
        return $this->cart_contents['cart_total'];
    }

    /**
     * Insert items into the cart and save it to the session
     * @param    array
     * @return    bool
     */
    public function insert($item = array()){
        if(!is_array($item) OR count($item) === 0){
            return FALSE;
        }else{
            if(!isset($item['id'], $item['name'], $item['price'], $item['qty'])){
                return FALSE;
            }else{
                /*
                 * Insert Item
                 */
                // prep the quantity
                $item['qty'] = (float) $item['qty'];
                if($item['qty'] == 0){
                    return FALSE;
                }
                // prep the price
                $item['price'] = (float) $item['price'];
                // create a unique identifier for the item being inserted into the cart
                $rowid = md5($item['id']);
                // get quantity if it's already there and add it on
                $old_qty = isset($this->cart_contents[$rowid]['qty']) ? (int) $this->cart_contents[$rowid]['qty'] : 0;
                // re-create the entry with unique identifier and updated quantity
                $item['rowid'] = $rowid;
                $item['qty'] += $old_qty;
                $this->cart_contents[$rowid] = $item;

                // save Cart Item
                if($this->save_cart()){
                    return isset($rowid) ? $rowid : TRUE;
                }else{
                    return FALSE;
                }
            }
        }
    }

    /**
     * Update the cart
     * @param    array
     * @return    bool
     */
    public function update($item = array()){
        if (!is_array($item) OR count($item) === 0){
            return FALSE;
        }else{
            if (!isset($item['rowid'], $this->cart_contents[$item['rowid']])){
                return FALSE;
            }else{
                // prep the quantity
                if(isset($item['qty'])){
                    $item['qty'] = (float) $item['qty'];
                    // remove the item from the cart, if quantity is zero
                    if ($item['qty'] == 0){
                        unset($this->cart_contents[$item['rowid']]);
                        return TRUE;
                    }
                }

                // find updatable keys
                $keys = array_intersect(array_keys($this->cart_contents[$item['rowid']]), array_keys($item));
                // prep the price
                if(isset($item['price'])){
                    $item['price'] = (float) $item['price'];
                }
                // product id & name shouldn't be changed
                foreach(array_diff($keys, array('id', 'name')) as $key){
                    $this->cart_contents[$item['rowid']][$key] = $item[$key];
                }
                // save cart data
                $this->save_cart();
                return TRUE;
            }
        }
    }

    /**
     * Save the cart array to the session
     * @return    bool
     */
    protected function save_cart(){
        $this->cart_contents['total_items'] = $this->cart_contents['cart_total'] = 0;
        foreach ($this->cart_contents as $key => $val){
            // make sure the array contains the proper indexes
            if(!is_array($val) OR !isset($val['price'], $val['qty'])){
                continue;
            }

            $this->cart_contents['cart_total'] += ($val['price'] * $val['qty']);
            $this->cart_contents['total_items'] += $val['qty'];
            $this->cart_contents[$key]['subtotal'] = ($this->cart_contents[$key]['price'] * $this->cart_contents[$key]['qty']);
        }

        // if cart empty, delete it from the session
        if(count($this->cart_contents) <= 2){
            unset($_SESSION['cart_contents']);
            return FALSE;
        }else{
            $_SESSION['cart_contents'] = $this->cart_contents;
            return TRUE;
        }
    }

    /**
     * Remove Item: Removes an item from the cart
     * @param    int
     * @return    bool
     */
     public function remove($row_id){
        // unset & save
        unset($this->cart_contents[$row_id]);
        $this->save_cart();
        return TRUE;
     }

    /**
     * Destroy the cart: Empties the cart and destroy the session
     * @return    void
     */
    public function destroy(){
        $this->cart_contents = array('cart_total' => 0, 'total_items' => 0);
        unset($_SESSION['cart_contents']);
    }
}

Cấu hình trang web và cơ sở dữ liệu (config. php)

Trong tệp

CREATE TABLE `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  `price` float(10,2) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
7, một số cài đặt chung và cơ sở dữ liệu được xác định trong các biến không đổi

hằng số chung

  • CURRENCY – Chỉ định mã tiền tệ mặc định
  • CURRENCY_SYMBOL – Chỉ định ký hiệu tiền tệ

Hằng số cơ sở dữ liệu

  • DB_HOST – Chỉ định máy chủ cơ sở dữ liệu
  • DB_USERNAME – Chỉ định tên người dùng cơ sở dữ liệu
  • DB_PASSWORD – Chỉ định mật khẩu cơ sở dữ liệu
  • DB_NAME – Chỉ định tên cơ sở dữ liệu
// Common settings
define('CURRENCY', 'USD');
define('CURRENCY_SYMBOL', '$');

// Database configuration
define('DB_HOST', 'MySQL_Database_Host');
define('DB_USERNAME', 'MySQL_Database_Username');
define('DB_PASSWORD', 'MySQL_Database_Password');
define('DB_NAME', 'MySQL_Database_Name');

Kết nối cơ sở dữ liệu (dbConnect. php)

File

CREATE TABLE `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  `price` float(10,2) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
8 dùng để kết nối và chọn cơ sở dữ liệu MySQL bằng PHP

// Include the configuration file
require_once 'config.php';

// Connect with the database
$db = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

// Display error if failed to connect
if ($db->connect_errno) {
    printf("Connect failed: %s\n", $db->connect_error);
    exit();
}

Bộ điều khiển yêu cầu giỏ hàng (cartAction. php)

Tệp

CREATE TABLE `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  `price` float(10,2) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
9 xử lý tất cả các hành động do người dùng yêu cầu từ giao diện người dùng trang web. Các khối mã sẽ được thực thi dựa trên hành động được yêu cầu

  • thêm vào giỏ hàng -
    • Tìm nạp chi tiết sản phẩm từ cơ sở dữ liệu theo ID sản phẩm được chỉ định và chèn mặt hàng vào giỏ hàng bằng lớp Cart
    • Sau khi thao tác thành công, người dùng được chuyển hướng đến trang
      CREATE TABLE `customers` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
        `last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
        `email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
        `phone` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
        `address` text COLLATE utf8_unicode_ci NOT NULL,
        `created` datetime NOT NULL,
        `modified` datetime NOT NULL,
        `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
        PRIMARY KEY (`id`)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
      0
  • updateCartItem – Cập nhật giỏ hàng theo
    CREATE TABLE `customers` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
      `last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
      `email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
      `phone` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
      `address` text COLLATE utf8_unicode_ci NOT NULL,
      `created` datetime NOT NULL,
      `modified` datetime NOT NULL,
      `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    1 cụ thể bằng cách sử dụng lớp Cart và trả về thông báo trạng thái
  • loại bỏCartItem –
    • Xóa mặt hàng khỏi giỏ hàng theo id mặt hàng cụ thể bằng cách sử dụng lớp Giỏ hàng
    • Sau khi thao tác thành công, người dùng được chuyển hướng đến trang
      CREATE TABLE `customers` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
        `last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
        `email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
        `phone` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
        `address` text COLLATE utf8_unicode_ci NOT NULL,
        `created` datetime NOT NULL,
        `modified` datetime NOT NULL,
        `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
        PRIMARY KEY (`id`)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
      0
  • đặt hàng –
    • Chèn dữ liệu khách hàng vào cơ sở dữ liệu
    • Chèn đơn đặt hàng vào cơ sở dữ liệu với ID khách hàng
    • Chèn dữ liệu các mặt hàng trong giỏ hàng vào bảng
      CREATE TABLE `products` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
        `name` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
        `description` text COLLATE utf8_unicode_ci NOT NULL,
        `price` float(10,2) NOT NULL,
        `created` datetime NOT NULL,
        `modified` datetime NOT NULL,
        `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
        PRIMARY KEY (`id`)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
      4 và liên kết ID đơn hàng
    • Xóa các mặt hàng trong giỏ hàng khỏi SESSION bằng lớp Giỏ hàng
    • Sau khi thao tác thành công, người dùng được chuyển hướng đến trang
      CREATE TABLE `customers` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
        `last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
        `email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
        `phone` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
        `address` text COLLATE utf8_unicode_ci NOT NULL,
        `created` datetime NOT NULL,
        `modified` datetime NOT NULL,
        `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
        PRIMARY KEY (`id`)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
      4
// Include the database connection file
require_once 'dbConnect.php';

// Initialize shopping cart class
require_once 'Cart.class.php';
$cart = new Cart;

// Default redirect page
$redirectURL = 'index.php';

// Process request based on the specified action
if(isset($_REQUEST['action']) && !empty($_REQUEST['action'])){
    if($_REQUEST['action'] == 'addToCart' && !empty($_REQUEST['id'])){
        $product_id = $_REQUEST['id'];

        // Fetch product details from the database
        $sqlQ = "SELECT * FROM products WHERE id=?";
        $stmt = $db->prepare($sqlQ);
        $stmt->bind_param("i", $db_id);
        $db_id = $product_id;
        $stmt->execute();
        $result = $stmt->get_result();
        $productRow = $result->fetch_assoc();

        $itemData = array(
            'id' => $productRow['id'],
            'image' => $productRow['image'],
            'name' => $productRow['name'],
            'price' => $productRow['price'],
            'qty' => 1
        );

        // Insert item to cart
        $insertItem = $cart->insert($itemData);

        // Redirect to cart page
        $redirectURL = $insertItem?'viewCart.php':'index.php';
    }elseif($_REQUEST['action'] == 'updateCartItem' && !empty($_REQUEST['id'])){
        // Update item data in cart
        $itemData = array(
            'rowid' => $_REQUEST['id'],
            'qty' => $_REQUEST['qty']
        );
        $updateItem = $cart->update($itemData);

        // Return status
        echo $updateItem?'ok':'err';die;
    }elseif($_REQUEST['action'] == 'removeCartItem' && !empty($_REQUEST['id'])){
        // Remove item from cart
        $deleteItem = $cart->remove($_REQUEST['id']);

        // Redirect to cart page
        $redirectURL = 'viewCart.php';
    }elseif($_REQUEST['action'] == 'placeOrder' && $cart->total_items() > 0){
        $redirectURL = 'checkout.php';

        // Store post data
        $_SESSION['postData'] = $_POST;

        $first_name = strip_tags($_POST['first_name']);
        $last_name = strip_tags($_POST['last_name']);
        $email = strip_tags($_POST['email']);
        $phone = strip_tags($_POST['phone']);
        $address = strip_tags($_POST['address']);

        $errorMsg = '';
        if(empty($first_name)){
            $errorMsg .= 'Please enter your first name.
';
        }
        if(empty($last_name)){
            $errorMsg .= 'Please enter your last name.
';
        }
        if(empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)){
            $errorMsg .= 'Please enter a valid email.
';
        }
        if(empty($phone)){
            $errorMsg .= 'Please enter your contact number.
';
        }
        if(empty($address)){
            $errorMsg .= 'Please enter your address.
';
        }

        if(empty($errorMsg)){
            // Insert customer data into the database
            $sqlQ = "INSERT INTO customers (first_name,last_name,email,phone,address,created,modified) VALUES (?,?,?,?,?,NOW(),NOW())";
            $stmt = $db->prepare($sqlQ);
            $stmt->bind_param("sssss", $db_first_name, $db_last_name, $db_email, $db_phone, $db_address);
            $db_first_name = $first_name;
            $db_last_name = $last_name;
            $db_email = $email;
            $db_phone = $phone;
            $db_address = $address;
            $insertCust = $stmt->execute();

            if($insertCust){
                $custID = $stmt->insert_id;

                // Insert order info in the database
                $sqlQ = "INSERT INTO orders (customer_id,grand_total,created,status) VALUES (?,?,NOW(),?)";
                $stmt = $db->prepare($sqlQ);
                $stmt->bind_param("ids", $db_customer_id, $db_grand_total, $db_status);
                $db_customer_id = $custID;
                $db_grand_total = $cart->total();
                $db_status = 'Pending';
                $insertOrder = $stmt->execute();

                if($insertOrder){
                    $orderID = $stmt->insert_id;

                    // Retrieve cart items
                    $cartItems = $cart->contents();

                    // Insert order items in the database
                    if(!empty($cartItems)){
                        $sqlQ = "INSERT INTO order_items (order_id, product_id, quantity) VALUES (?,?,?)";
                        $stmt = $db->prepare($sqlQ);
                        foreach($cartItems as $item){
                            $stmt->bind_param("ids", $db_order_id, $db_product_id, $db_quantity);
                            $db_order_id = $orderID;
                            $db_product_id = $item['id'];
                            $db_quantity = $item['qty'];
                            $stmt->execute();
                        }

                        // Remove all items from cart
                        $cart->destroy();

                        // Redirect to the status page
                        $redirectURL = 'orderSuccess.php?id='.base64_encode($orderID);
                    }else{
                        $sessData['status']['type'] = 'error';
                        $sessData['status']['msg'] = 'Something went wrong, please try again.';
                    }
                }else{
                    $sessData['status']['type'] = 'error';
                    $sessData['status']['msg'] = 'Something went wrong, please try again.';
                }
            }else{
                $sessData['status']['type'] = 'error';
                $sessData['status']['msg'] = 'Something went wrong, please try again.';
            }
        }else{
            $sessData['status']['type'] = 'error';
            $sessData['status']['msg'] = '

Please fill all the mandatory fields.

'.$errorMsg;
        }

        // Store status in session
        $_SESSION['sessData'] = $sessData;
    }
}

// Redirect to the specific page
header("Location: $redirectURL");
exit();

Thư viện Bootstrap và jQuery

Chúng tôi sẽ sử dụng thư viện Bootstrap 5 để thiết kế danh sách sản phẩm, giỏ hàng, biểu mẫu thanh toán và giao diện người dùng trạng thái đơn hàng

  • jQuery được sử dụng trong trang giỏ hàng để cập nhật các mặt hàng trong giỏ hàng qua AJAX

Danh sách sản phẩm (chỉ mục. php)

Ban đầu, tất cả các sản phẩm được lấy từ cơ sở dữ liệu và được liệt kê trên trang web

  • Nút Add to Cart được đính kèm trên mỗi hộp sản phẩm
  • Nút Thêm vào giỏ hàng chuyển hướng người dùng đến trang
    CREATE TABLE `products` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
      `name` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
      `description` text COLLATE utf8_unicode_ci NOT NULL,
      `price` float(10,2) NOT NULL,
      `created` datetime NOT NULL,
      `modified` datetime NOT NULL,
      `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    9 với loại hành động (
    CREATE TABLE `customers` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
      `last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
      `email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
      `phone` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
      `address` text COLLATE utf8_unicode_ci NOT NULL,
      `created` datetime NOT NULL,
      `modified` datetime NOT NULL,
      `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    6) và ID sản phẩm tương ứng (
    CREATE TABLE `customers` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
      `last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
      `email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
      `phone` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
      `address` text COLLATE utf8_unicode_ci NOT NULL,
      `created` datetime NOT NULL,
      `modified` datetime NOT NULL,
      `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    7)
  • Giỏ hàng được đặt ở đầu trang để hiển thị tóm tắt các mặt hàng trong giỏ hàng. Nó chuyển hướng người dùng đến trang xem giỏ hàng

Giỏ hàng (viewCart. php)

Ban đầu, tất cả các mặt hàng trong giỏ hàng được liệt kê ở định dạng bảng

  • Nội dung giỏ hàng được lấy từ PHIÊN bằng cách sử dụng thư viện Giỏ hàng và hiển thị các mặt hàng trong giỏ hàng với tổng giá
  • Người mua có thể cập nhật hoặc xóa các mặt hàng khỏi giỏ hàng
  • Người mua sẽ có thể thêm nhiều mặt hàng hơn vào giỏ hàng bằng nút Tiếp tục mua hàng hoặc Thanh toán từ giỏ hàng
  • Nút Thanh toán chuyển hướng người mua đến trang
    CREATE TABLE `customers` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
      `last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
      `email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
      `phone` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
      `address` text COLLATE utf8_unicode_ci NOT NULL,
      `created` datetime NOT NULL,
      `modified` datetime NOT NULL,
      `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    8 để xem trước đơn đặt hàng trước khi gửi

Xem trước đơn hàng (thanh toán. php)

Tại trang thanh toán, người mua có thể xem trước sản phẩm đã chọn trước khi gửi đơn hàng

  • Hiển thị tóm tắt giỏ hàng với tổng giá
  • Biểu mẫu HTML để cung cấp thông tin liên hệ của người mua
  • Sau khi khách hàng gửi đơn đặt hàng, chi tiết liên hệ của người mua sẽ được gửi đến tệp
    CREATE TABLE `products` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
      `name` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
      `description` text COLLATE utf8_unicode_ci NOT NULL,
      `price` float(10,2) NOT NULL,
      `created` datetime NOT NULL,
      `modified` datetime NOT NULL,
      `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    9 với yêu cầu đặt hàng

Đặt hàng thành công (orderSuccess. php)

Khi đơn đặt hàng được gửi thành công, khách hàng được chuyển hướng đến trang này

  • Chi tiết đơn đặt hàng được tìm nạp từ cơ sở dữ liệu dựa trên ID đơn đặt hàng được chuyển vào URL
  • Hiển thị thông tin đơn hàng và người mua
  • Liệt kê các mục đặt hàng ở định dạng bảng

Triển khai giỏ hàng trong CodeIgniter

Phần kết luận

Hy vọng hướng dẫn này sẽ giúp bạn hiểu chức năng giỏ hàng cơ bản trong PHP với SESSION và MySQL. Sử dụng thư viện Giỏ hàng PHP và mã ví dụ này, bạn sẽ có thể triển khai giỏ hàng trong ứng dụng web của mình ngay lập tức. Ngoài ra, bạn có thể tùy chỉnh thiết kế và nâng cao chức năng của tập lệnh giỏ hàng dựa trên giao diện người dùng của trang web

Bạn có muốn nhận trợ giúp triển khai hay sửa đổi hoặc nâng cao chức năng của tập lệnh này không?

Làm cách nào để thêm các mặt hàng vào giỏ hàng bằng PHP?

page=cart) cùng với phương thức được đặt để đăng . Trang giỏ hàng (cart. php) sẽ thêm sản phẩm vào giỏ hàng. Với trường mẫu số lượng, chúng ta có thể đặt giá trị tối đa, giá trị này được đặt thành số lượng của sản phẩm (lấy từ bảng sản phẩm).

Làm cách nào để thêm sản phẩm trong PHP?

addProduct. php chứa biểu mẫu và thêm sản phẩm. nhận sản phẩm. php hiển thị thông tin chi tiết của một sản phẩm đã chọn.

Làm cách nào để xây dựng giỏ hàng trong PHP và MySQL?

Các bước để tạo một giỏ hàng đơn giản bằng PHP và MySQL .
Tạo cơ sở dữ liệu, bảng và kết xuất dữ liệu mẫu
Tạo kết nối cơ sở dữ liệu
Tạo một tệp chỉ mục
Tạo một tập tin giỏ hàng
Tạo một tệp CSS

Làm cách nào để tạo giỏ hàng trực tuyến bằng PHP MySQL AJAX?

Bước1. Tạo bảng cơ sở dữ liệu MySQL. Đầu tiên chúng ta sẽ tạo bảng cơ sở dữ liệu MySQL shop_products và chèn sản phẩm vào bảng này để hiển thị các sản phẩm trong cửa hàng để thêm vào giỏ hàng
Bước2. Liệt kê sản phẩm trong cửa hàng. .
Bước 3. Thêm sản phẩm vào giỏ hàng. .
Bước4. Quản lý giỏ hàng với PHP SESSION. .
Bước5. Xem chi tiết giỏ hàng. .
Bước 6. Đặt hàng thanh toán