不能添加或更新子行:外键约束失败。
你的PHP应用在使用PDO连接MySQL时遇到了外键约束问题:
'pdo_code' => '23000',
'db_code' => 1452,
'db_error' => 'Cannot add or update a child row: a foreign key constraint fails'
try {
$pdo->beginTransaction();
$checkStmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE id = ?");
$checkStmt->execute([$userId]);
$userExists = $checkStmt->fetchColumn();
if (!$userExists) {
throw new Exception("用户ID {$userId} 不存在");
}
$stmt = $pdo->prepare("INSERT INTO orders (user_id, amount, status) VALUES (?, ?, ?)");
$stmt->execute([$userId, $amount, 'pending']);
$pdo->commit();
echo "订单创建成功";
} catch (PDOException $e) {
$pdo->rollBack();
if ($e->getCode() == '23000' && strpos($e->getMessage(), '1452') !== false) {
echo "外键约束错误:引用的用户记录不存在";
} else {
throw $e;
}
} catch (Exception $e) {
$pdo->rollBack();
echo $e->getMessage();
}