当前位置:首页 > PHP

php实现购买操作

2026-02-15 20:42:23PHP

PHP 实现购买操作

数据库设计

创建必要的数据库表存储商品、订单和用户信息。例如:

CREATE TABLE products (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    price DECIMAL(10,2),
    stock INT
);

CREATE TABLE orders (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT,
    total DECIMAL(10,2),
    status VARCHAR(20),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE order_items (
    id INT AUTO_INCREMENT PRIMARY KEY,
    order_id INT,
    product_id INT,
    quantity INT,
    price DECIMAL(10,2)
);

商品展示页面

从数据库获取商品信息并展示给用户:

$conn = new mysqli("localhost", "username", "password", "database");
$result = $conn->query("SELECT * FROM products WHERE stock > 0");
while($row = $result->fetch_assoc()) {
    echo "<div class='product'>";
    echo "<h3>".$row['name']."</h3>";
    echo "<p>价格: ".$row['price']."</p>";
    echo "<form method='post' action='add_to_cart.php'>";
    echo "<input type='hidden' name='product_id' value='".$row['id']."'>";
    echo "<input type='number' name='quantity' min='1' max='".$row['stock']."'>";
    echo "<button type='submit'>加入购物车</button>";
    echo "</form>";
    echo "</div>";
}

购物车功能

实现购物车添加和显示功能:

// add_to_cart.php
session_start();
$product_id = $_POST['product_id'];
$quantity = $_POST['quantity'];

if(!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = array();
}

if(isset($_SESSION['cart'][$product_id])) {
    $_SESSION['cart'][$product_id] += $quantity;
} else {
    $_SESSION['cart'][$product_id] = $quantity;
}

header("Location: cart.php");

// cart.php
session_start();
$total = 0;
foreach($_SESSION['cart'] as $product_id => $quantity) {
    $product = getProductById($product_id); // 自定义函数获取商品详情
    $subtotal = $product['price'] * $quantity;
    $total += $subtotal;
    // 显示购物车商品
}
echo "总价: ".$total;
echo "<form method='post' action='checkout.php'>";
echo "<button type='submit'>结算</button>";
echo "</form>";

结算处理

处理订单创建和库存更新:

// checkout.php
session_start();
$conn = new mysqli("localhost", "username", "password", "database");

// 开始事务
$conn->begin_transaction();

try {
    // 创建订单
    $total = calculateTotal($_SESSION['cart']); // 自定义计算总价函数
    $user_id = $_SESSION['user_id']; // 假设用户已登录
    $conn->query("INSERT INTO orders (user_id, total, status) VALUES ($user_id, $total, 'pending')");
    $order_id = $conn->insert_id;

    // 添加订单项
    foreach($_SESSION['cart'] as $product_id => $quantity) {
        $product = getProductById($product_id);
        $price = $product['price'];
        $conn->query("INSERT INTO order_items (order_id, product_id, quantity, price) VALUES ($order_id, $product_id, $quantity, $price)");

        // 更新库存
        $conn->query("UPDATE products SET stock = stock - $quantity WHERE id = $product_id");
    }

    // 清空购物车
    unset($_SESSION['cart']);

    $conn->commit();
    header("Location: order_success.php?order_id=$order_id");
} catch(Exception $e) {
    $conn->rollback();
    header("Location: checkout_error.php");
}

支付集成

集成第三方支付网关(以支付宝为例):

// 配置支付宝参数
$alipay_config = array(
    'partner' => '2088xxxxxxxxxx',
    'key' => 'xxxxxxxxxxxxxxxx',
    'seller_email' => 'your@email.com',
    'notify_url' => 'http://yourdomain.com/notify_url.php',
    'return_url' => 'http://yourdomain.com/return_url.php'
);

// 构造请求参数
$parameter = array(
    "service" => "create_direct_pay_by_user",
    "partner" => $alipay_config['partner'],
    "payment_type" => "1",
    "notify_url" => $alipay_config['notify_url'],
    "return_url" => $alipay_config['return_url'],
    "out_trade_no" => $order_id,
    "subject" => "订单支付",
    "total_fee" => $total,
    "seller_email" => $alipay_config['seller_email']
);

// 生成支付表单
function buildRequestForm($para, $alipay_config) {
    $sHtml = "<form id='alipaysubmit' name='alipaysubmit' action='https://mapi.alipay.com/gateway.do?_input_charset=utf-8' method='post'>";
    while (list ($key, $val) = each ($para)) {
        $sHtml.= "<input type='hidden' name='".$key."' value='".$val."'/>";
    }
    $sHtml.= "<input type='submit' value='确认支付'></form>";
    return $sHtml;
}

echo buildRequestForm($parameter, $alipay_config);

订单状态更新

处理支付回调更新订单状态:

// notify_url.php
$verify_result = verifyNotify(); // 自定义验证函数

if($verify_result) {
    $order_id = $_POST['out_trade_no'];
    $trade_status = $_POST['trade_status'];

    if($trade_status == 'TRADE_FINISHED' || $trade_status == 'TRADE_SUCCESS') {
        $conn->query("UPDATE orders SET status = 'paid' WHERE id = $order_id");
    }
    echo "success";
} else {
    echo "fail";
}

安全考虑

实现必要的安全措施:

php实现购买操作

  • 使用预处理语句防止SQL注入
  • 验证用户输入
  • 实现CSRF防护
  • 对敏感数据进行加密
  • 使用HTTPS传输数据

以上实现涵盖了从商品展示到支付完成的完整购买流程,可根据实际需求进行调整和扩展。

标签: 操作php
分享给朋友:

相关文章

php 实现登录

php 实现登录

PHP 登录功能实现 使用 PHP 实现登录功能通常需要结合数据库验证和会话管理。以下是一个基本的登录实现流程: 数据库准备 创建用户表存储用户名和密码(建议使用哈希加密): CREATE TAB…

php实现异步

php实现异步

PHP 实现异步的方法 PHP 本身是同步执行的脚本语言,但可以通过以下方法模拟异步操作或实现异步效果: 使用多进程(pcntl_fork) 通过 pcntl_fork 创建子进程实现异步,适用于…

php 实现验证码

php 实现验证码

使用 PHP 生成验证码 验证码(CAPTCHA)用于防止自动化脚本提交表单,以下是几种常见的 PHP 实现方法。 使用 GD 库生成图片验证码 GD 库是 PHP 的图像处理扩展,可用于生成验证码…

php实现的分页

php实现的分页

PHP 实现分页的方法 基本分页逻辑 分页的核心在于计算总页数、当前页码以及数据偏移量。假设每页显示 10 条数据: $current_page = isset($_GET['page']) ? (…

php实现定时

php实现定时

PHP 实现定时任务的方法 PHP 本身是脚本语言,通常需要借助外部工具或框架实现定时任务。以下是几种常见方法: 使用 Cron 任务 Linux 系统自带的 Cron 是常用的定时任务工具。通过编…

php 实现链表

php 实现链表

PHP 实现链表的方法 链表是一种线性数据结构,由节点组成,每个节点包含数据和指向下一个节点的指针。PHP 中可以通过类和对象来实现链表。 定义链表节点类 创建一个 ListNode 类,用于表示链…