php实现银行转帐
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;
}
}
安全验证
实现必要的安全验证:

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)防止并发问题
- 记录所有交易便于审计
- 在生产环境中应添加更严格的身份验证和授权检查






