本文目录导读:

在 PHP 中,你提到的“事务授权”通常涉及两个不同的概念,我将分别说明:
数据库事务(Transaction)
这是最常见的“事务”场景,用于保证数据库操作的原子性。
MySQLi 示例
$mysqli = new mysqli("localhost", "username", "password", "database");
// 开始事务
$mysqli->begin_transaction();
try {
// 执行多个SQL操作
$mysqli->query("UPDATE accounts SET balance = balance - 100 WHERE id = 1");
$mysqli->query("UPDATE accounts SET balance = balance + 100 WHERE id = 2");
// 提交事务
$mysqli->commit();
echo "事务提交成功";
} catch (Exception $e) {
// 发生错误,回滚事务
$mysqli->rollback();
echo "事务回滚: " . $e->getMessage();
}
PDO 示例(推荐)
try {
$pdo = new PDO("mysql:host=localhost;dbname=database", "username", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// 开始事务
$pdo->beginTransaction();
// 执行操作
$pdo->exec("UPDATE accounts SET balance = balance - 100 WHERE id = 1");
$pdo->exec("UPDATE accounts SET balance = balance + 100 WHERE id = 2");
// 提交
$pdo->commit();
echo "事务成功";
} catch (Exception $e) {
// 回滚
$pdo->rollBack();
echo "失败: " . $e->getMessage();
}
授权/权限控制(Authorization)
如果你是指“授权”用户执行特定操作:
用户角色权限系统
// 简单的权限检查函数
function checkPermission($userId, $requiredPermission) {
// 从数据库获取用户权限
$userPermissions = getUserPermissions($userId);
if (in_array($requiredPermission, $userPermissions)) {
return true;
}
return false;
}
// 使用示例
if (checkPermission($currentUserId, 'delete_user')) {
// 执行删除操作
deleteUser($userId);
} else {
die("权限不足");
}
中间件方式(适用于框架)
// 自定义授权中间件
class AuthMiddleware {
public function handle($request, $next) {
if (!$this->hasPermission($request->user, $request->route)) {
return response('无权限', 403);
}
return $next($request);
}
}
结合使用 - 带授权检查的事务
function transferMoney($fromUserId, $toUserId, $amount, $currentUserId) {
// 检查授权
if (!canTransferMoney($currentUserId)) {
throw new Exception("您没有转账权限");
}
$pdo = getDBConnection();
try {
$pdo->beginTransaction();
// 执行转账
$pdo->prepare("UPDATE accounts SET balance = balance - ? WHERE user_id = ?")
->execute([$amount, $fromUserId]);
$pdo->prepare("UPDATE accounts SET balance = balance + ? WHERE user_id = ?")
->execute([$amount, $toUserId]);
$pdo->commit();
return true;
} catch (Exception $e) {
$pdo->rollBack();
throw $e;
}
}
最佳实践建议
- 使用 PDO:比 MySQLi 更安全、功能更丰富
- 错误处理:总是使用 try-catch 处理事务
- 权限检查:在事务开始前进行
- 日志记录:记录事务操作和授权检查
请根据你的具体需求,明确是需要数据库事务还是权限授权,或者两者都需要结合使用。