当前位置:首页 > PHP

php实现银行转帐

2026-03-13 05:23:32PHP

PHP实现银行转账功能

银行转账功能需要处理资金的安全转移,涉及数据库操作、事务处理和安全性验证。以下是实现步骤:

数据库设计

创建相关数据表存储账户和交易信息:

CREATE TABLE accounts (
    id INT PRIMARY KEY AUTO_INCREMENT,
    account_number VARCHAR(20) UNIQUE NOT NULL,
    account_name VARCHAR(100) NOT NULL,
    balance DECIMAL(15,2) DEFAULT 0.00
);

CREATE TABLE transactions (
    id INT PRIMARY KEY AUTO_INCREMENT,
    from_account VARCHAR(20) NOT NULL,
    to_account VARCHAR(20) NOT NULL,
    amount DECIMAL(15,2) NOT NULL,
    transaction_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    status ENUM('pending', 'completed', 'failed') DEFAULT 'pending'
);

转账核心逻辑

使用PDO实现带事务处理的转账操作:

function transferFunds($fromAccount, $toAccount, $amount) {
    $db = new PDO('mysql:host=localhost;dbname=banking', 'username', 'password');
    $db->beginTransaction();

    try {
        // 检查转出账户余额
        $stmt = $db->prepare("SELECT balance FROM accounts WHERE account_number = ? FOR UPDATE");
        $stmt->execute([$fromAccount]);
        $fromBalance = $stmt->fetchColumn();

        if ($fromBalance < $amount) {
            throw new Exception("Insufficient funds");
        }

        // 扣减转出账户金额
        $stmt = $db->prepare("UPDATE accounts SET balance = balance - ? WHERE account_number = ?");
        $stmt->execute([$amount, $fromAccount]);

        // 增加转入账户金额
        $stmt = $db->prepare("UPDATE accounts SET balance = balance + ? WHERE account_number = ?");
        $stmt->execute([$amount, $toAccount]);

        // 记录交易
        $stmt = $db->prepare("INSERT INTO transactions (from_account, to_account, amount, status) VALUES (?, ?, ?, 'completed')");
        $stmt->execute([$fromAccount, $toAccount, $amount]);

        $db->commit();
        return true;
    } catch (Exception $e) {
        $db->rollBack();
        // 记录失败交易
        $stmt = $db->prepare("INSERT INTO transactions (from_account, to_account, amount, status) VALUES (?, ?, ?, 'failed')");
        $stmt->execute([$fromAccount, $toAccount, $amount]);
        return false;
    }
}

安全验证

实现必要的安全验证:

php实现银行转帐

function validateTransfer($fromAccount, $toAccount, $amount) {
    // 验证金额为正数
    if ($amount <= 0) {
        throw new InvalidArgumentException("Amount must be positive");
    }

    // 验证账户不同
    if ($fromAccount === $toAccount) {
        throw new InvalidArgumentException("Cannot transfer to same account");
    }

    // 验证账户存在
    $db = new PDO('mysql:host=localhost;dbname=banking', 'username', 'password');
    $stmt = $db->prepare("SELECT COUNT(*) FROM accounts WHERE account_number = ?");
    $stmt->execute([$fromAccount]);
    if ($stmt->fetchColumn() == 0) {
        throw new InvalidArgumentException("Invalid source account");
    }

    $stmt->execute([$toAccount]);
    if ($stmt->fetchColumn() == 0) {
        throw new InvalidArgumentException("Invalid destination account");
    }
}

完整调用示例

try {
    validateTransfer('123456789', '987654321', 1000.00);
    if (transferFunds('123456789', '987654321', 1000.00)) {
        echo "Transfer completed successfully";
    } else {
        echo "Transfer failed";
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

注意事项

  • 使用预处理语句防止SQL注入
  • 事务处理确保数据一致性
  • 账户锁定(FOR UPDATE)防止并发问题
  • 记录所有交易便于审计
  • 在生产环境中应添加更严格的身份验证和授权检查

标签: 银行转帐php
分享给朋友:

相关文章

php搜索功能实现

php搜索功能实现

实现基本的PHP搜索功能 使用MySQL数据库和PHP实现简单的关键词搜索功能。需要确保数据库中有可供搜索的表和数据。 // 连接数据库 $conn = new mysqli('localhost'…

php实现定时

php实现定时

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

php 实现mvc

php 实现mvc

PHP 实现 MVC 架构的方法 MVC(Model-View-Controller)是一种常见的软件设计模式,用于分离业务逻辑、用户界面和用户输入。以下是 PHP 实现 MVC 架构的关键步骤:…

php 实现排名

php 实现排名

PHP 实现排名的方法 在 PHP 中实现排名功能通常涉及对数据进行排序、计算排名以及输出结果。以下是几种常见的实现方式: 基本数组排序排名 $scores = [85, 92, 78, 95, 8…

php实现投票

php实现投票

PHP实现投票功能 数据库设计 创建数据库表存储投票数据,例如: CREATE TABLE `votes` ( `id` int(11) NOT NULL AUTO_INCREMENT,…

php多态实现

php多态实现

PHP 多态的实现方法 多态是面向对象编程的三大特性之一,允许不同类的对象对同一消息做出响应。PHP 主要通过以下方式实现多态: 通过继承和方法重写 子类继承父类并重写父类方法,实现不同子类对同一方…