本文目录导读:

我来为你详细介绍PHP数据处理记录的多种方法。
数据记录基础方法
文件记录(简单日志)
// 简单日志记录函数
function logData($message, $data = null) {
$logFile = __DIR__ . '/data_log.txt';
$timestamp = date('Y-m-d H:i:s');
$logEntry = "[{$timestamp}] {$message}";
if ($data !== null) {
$logEntry .= " | Data: " . json_encode($data, JSON_UNESCAPED_UNICODE);
}
$logEntry .= PHP_EOL;
file_put_contents($logFile, $logEntry, FILE_APPEND);
}
// 使用示例
$userData = ['id' => 1, 'name' => '张三', 'action' => 'login'];
logData('用户操作', $userData);
数据库记录
MySQL记录
// 创建数据记录表
$sql = "CREATE TABLE IF NOT EXISTS data_records (
id INT AUTO_INCREMENT PRIMARY KEY,
record_type VARCHAR(50),
record_data JSON,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_type (record_type)
)";
// 插入记录
function insertRecord($pdo, $type, $data) {
$stmt = $pdo->prepare("INSERT INTO data_records (record_type, record_data) VALUES (?, ?)");
return $stmt->execute([$type, json_encode($data, JSON_UNESCAPED_UNICODE)]);
}
// 查询记录
function getRecords($pdo, $type = null, $limit = 10) {
if ($type) {
$stmt = $pdo->prepare("SELECT * FROM data_records WHERE record_type = ? ORDER BY created_at DESC LIMIT ?");
$stmt->execute([$type, $limit]);
} else {
$stmt = $pdo->query("SELECT * FROM data_records ORDER BY created_at DESC LIMIT $limit");
}
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
MongoDB记录
// MongoDB 连接
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
// 插入文档
function insertMongoRecord($manager, $type, $data) {
$bulk = new MongoDB\Driver\BulkWrite;
$doc = [
'record_type' => $type,
'record_data' => $data,
'created_at' => new MongoDB\BSON\UTCDateTime()
];
$bulk->insert($doc);
return $manager->executeBulkWrite('database.data_records', $bulk);
}
日志系统记录
// 使用 Monolog 库
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\RotatingFileHandler;
class DataLogger {
private $logger;
public function __construct($logName = 'data_processing') {
$this->logger = new Logger($logName);
// 每日轮转日志
$this->logger->pushHandler(
new RotatingFileHandler(__DIR__ . '/logs/data.log', 30, Logger::INFO)
);
}
public function record($event, $data) {
$this->logger->info($event, [
'data' => $data,
'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
'timestamp' => microtime(true)
]);
}
public function recordError($event, $error, $data = null) {
$this->logger->error($event, [
'error' => $error,
'data' => $data
]);
}
}
// 使用
$logger = new DataLogger();
$logger->record('用户登录', ['user_id' => 123, 'username' => '张三']);
数据变更记录
class DataChangeTracker {
private $pdo;
private $changes = [];
public function __construct($pdo) {
$this->pdo = $pdo;
}
public function trackChange($table, $recordId, $action, $oldData, $newData) {
$change = [
'table_name' => $table,
'record_id' => $recordId,
'action' => $action, // INSERT, UPDATE, DELETE
'old_data' => json_encode($oldData, JSON_UNESCAPED_UNICODE),
'new_data' => json_encode($newData, JSON_UNESCAPED_UNICODE),
'changed_by' => $_SESSION['user_id'] ?? 0,
'changed_at' => date('Y-m-d H:i:s')
];
$stmt = $this->pdo->prepare("
INSERT INTO data_changes
(table_name, record_id, action, old_data, new_data, changed_by, changed_at)
VALUES (?, ?, ?, ?, ?, ?, ?)
");
return $stmt->execute(array_values($change));
}
public function getHistory($table, $recordId, $limit = 10) {
$stmt = $this->pdo->prepare("
SELECT * FROM data_changes
WHERE table_name = ? AND record_id = ?
ORDER BY changed_at DESC
LIMIT ?
");
$stmt->execute([$table, $recordId, $limit]);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
性能监控记录
class PerformanceTracker {
private static $records = [];
public static function start($label) {
self::$records[$label] = [
'start' => microtime(true),
'memory_start' => memory_get_usage()
];
}
public static function end($label) {
if (isset(self::$records[$label])) {
$record = self::$records[$label];
$executionTime = microtime(true) - $record['start'];
$memoryUsed = memory_get_usage() - $record['memory_start'];
$logEntry = sprintf(
"[%s] %s | Time: %.4f sec | Memory: %s bytes | Peak: %s bytes\n",
date('Y-m-d H:i:s'),
$label,
$executionTime,
number_format($memoryUsed),
number_format(memory_get_peak_usage())
);
file_put_contents(__DIR__ . '/performance.log', $logEntry, FILE_APPEND);
unset(self::$records[$label]);
}
}
}
// 使用示例
PerformanceTracker::start('大数据处理');
// 处理数据...
PerformanceTracker::end('大数据处理');
完整的记录类
class DataRecorder {
private $storage;
private $config;
public function __construct(array $config = []) {
$this->config = array_merge([
'storage' => 'file', // file, database, both
'file_path' => __DIR__ . '/data_records/',
'db_connection' => null,
'date_format' => 'Y-m-d',
'compress' => false,
'max_file_size' => 10485760 // 10MB
], $config);
$this->initialize();
}
private function initialize() {
if ($this->config['storage'] === 'file' || $this->config['storage'] === 'both') {
if (!file_exists($this->config['file_path'])) {
mkdir($this->config['file_path'], 0755, true);
}
}
}
public function record($type, $data, $metadata = []) {
$record = [
'id' => uniqid('rec_', true),
'type' => $type,
'data' => $data,
'metadata' => $metadata,
'timestamp' => date('Y-m-d H:i:s'),
'ip' => $this->getClientIp(),
'debug' => $this->getDebugInfo()
];
$result = [];
if (in_array($this->config['storage'], ['file', 'both'])) {
$result['file'] = $this->saveToFile($record);
}
if (in_array($this->config['storage'], ['database', 'both'])) {
$result['database'] = $this->saveToDatabase($record);
}
return $result;
}
private function saveToFile($record) {
$dateFile = $this->config['file_path'] . date('Y-m-d') . '.json';
$existing = [];
if (file_exists($dateFile)) {
$content = file_get_contents($dateFile);
if ($this->config['compress']) {
$content = gzuncompress($content);
}
$existing = json_decode($content, true) ?? [];
}
$existing[] = $record;
// 检查文件大小
if (count($existing) > 1000) {
$existing = array_slice($existing, -1000);
}
$content = json_encode($existing, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
if ($this->config['compress']) {
$content = gzcompress($content, 9);
}
return file_put_contents($dateFile, $content) !== false;
}
private function saveToDatabase($record) {
if (!$this->config['db_connection']) {
return false;
}
try {
$stmt = $this->config['db_connection']->prepare("
INSERT INTO data_records (record_id, record_type, record_data, metadata, created_at, client_ip)
VALUES (?, ?, ?, ?, NOW(), ?)
");
return $stmt->execute([
$record['id'],
$record['type'],
json_encode($record['data'], JSON_UNESCAPED_UNICODE),
json_encode($record['metadata'], JSON_UNESCAPED_UNICODE),
$record['ip']
]);
} catch (Exception $e) {
error_log("Database save failed: " . $e->getMessage());
return false;
}
}
private function getClientIp() {
$headers = ['HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR', 'HTTP_CLIENT_IP'];
foreach ($headers as $header) {
if (!empty($_SERVER[$header])) {
$ips = explode(',', $_SERVER[$header]);
return trim($ips[0]);
}
}
return 'unknown';
}
private function getDebugInfo() {
return [
'memory_usage' => memory_get_usage(true),
'peak_memory' => memory_get_peak_usage(true),
'php_version' => PHP_VERSION,
'server_software' => $_SERVER['SERVER_SOFTWARE'] ?? 'unknown'
];
}
public function queryRecords(array $filters = []) {
// 根据存储方式查询记录
}
}
// 使用示例
$recorder = new DataRecorder([
'storage' => 'both',
'compress' => true
]);
$recorder->record('user_action',
['user_id' => 123, 'action' => 'purchase'],
['source' => 'web', 'campaign' => 'summer_sale']
);
使用建议
-
选择合适的存储方式
- 简单记录:文件系统
- 大量数据:数据库
- 实时分析:Elasticsearch
-
性能考虑
- 批量写入,避免频繁IO
- 使用缓冲机制
- 定期归档旧数据
-
安全考虑
- 过滤敏感信息
- 加密存储
- 访问控制
-
备份策略
- 定期备份
- 异地容灾
- 数据恢复机制
这些方法可以根据你的具体需求组合使用,需要我详细解释某个特定场景的实现吗?