beginTransaction();
try {
foreach ($lines as $line_num => $line) {
$line = trim($line);
if (empty($line)) continue;
$row = str_getcsv($line);
if (count($row) < 9) {
$errors[] = "第 " . ($line_num + 2) . " 行列数不足,跳过";
$skip_count++;
continue;
}
$title = trim($row[0]);
$cinema_name = trim($row[2]);
$watch_date = trim($row[3]);
$viewer_names = trim($row[4]);
$ticket_file = trim($row[5]);
$poster_file = trim($row[6]);
$remark = trim($row[7]);
$photo_file = trim($row[8]);
if (empty($title)) {
$errors[] = "第 " . ($line_num + 2) . " 行缺少电影名称,跳过";
$skip_count++;
continue;
}
// 处理日期(允许为空)
$formatted_date = null;
if (!empty($watch_date)) {
$timestamp = strtotime($watch_date);
if ($timestamp === false) {
$errors[] = "第 " . ($line_num + 2) . " 行日期格式无效: $watch_date,跳过";
$skip_count++;
continue;
}
$formatted_date = date('Y-m-d', $timestamp);
}
// 电影院去重
$cinema_id = null;
if (!empty($cinema_name)) {
if (!isset($cinema_cache[$cinema_name])) {
$stmt = $db->prepare("SELECT id FROM cinemas WHERE name = ?");
$stmt->execute([$cinema_name]);
$existing = $stmt->fetch();
if ($existing) {
$cinema_cache[$cinema_name] = $existing['id'];
} else {
$stmt = $db->prepare("INSERT INTO cinemas (place, name, address) VALUES (?, ?, ?)");
$stmt->execute(['', $cinema_name, '']);
$cinema_id = $db->lastInsertId();
$cinema_cache[$cinema_name] = $cinema_id;
}
}
$cinema_id = $cinema_cache[$cinema_name];
}
$ticket_filename = extractFileName($ticket_file);
$poster_filename = extractFileName($poster_file);
$photo_filename = extractFileName($photo_file);
$ticket_path = !empty($ticket_filename) ? 'uploads/tickets/' . $ticket_filename : null;
$poster_path = !empty($poster_filename) ? 'uploads/posters/' . $poster_filename : null;
$photo_path = !empty($photo_filename) ? 'uploads/photos/' . $photo_filename : null;
$stmt = $db->prepare("
INSERT INTO movies (title, info, remark, poster_path, ticket_path, photo_path, cinema_id, watch_date)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
");
$stmt->execute([
$title,
'',
$remark,
$poster_path,
$ticket_path,
$photo_path,
$cinema_id,
$formatted_date
]);
$movie_id = $db->lastInsertId();
// 处理观影人:按空白字符分割(空格、制表符等)
if (!empty($viewer_names)) {
$viewers = preg_split('/\s+/', trim($viewer_names));
$viewers = array_filter($viewers, function($v) { return !empty($v); });
if (!empty($viewers)) {
$stmt = $db->prepare("INSERT INTO viewers (movie_id, name) VALUES (?, ?)");
foreach ($viewers as $name) {
$stmt->execute([$movie_id, $name]);
}
}
}
$import_count++;
}
$db->commit();
$result = [
'success' => true,
'imported' => $import_count,
'skipped' => $skip_count,
'errors' => $errors
];
} catch (Exception $e) {
$db->rollBack();
$error = '导入过程中发生错误:' . $e->getMessage();
}
}
}
?>
CSV导入 - 电影日志