prepare('SELECT * FROM `' . $module['table'] . '` WHERE id = ?'); $stmt->execute([$id]); $record = $stmt->fetch() ?: []; if (!$record) { http_response_code(404); exit('資料不存在。'); } } $error = ''; if ($_SERVER['REQUEST_METHOD'] === 'POST') { verify_csrf(); $data = []; foreach ($module['fields'] as $name => $field) { if ($field['type'] === 'file') continue; $value = $field['type'] === 'checkbox' ? (isset($_POST[$name]) ? 1 : 0) : trim((string) ($_POST[$name] ?? '')); if (!empty($field['required']) && $value === '') $error = '請完成所有必填欄位。'; $data[$name] = $value === '' ? null : $value; } if ($key === 'media' && isset($_FILES['file_path']) && $_FILES['file_path']['error'] !== UPLOAD_ERR_NO_FILE) { $file = $_FILES['file_path']; $allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/gif' => 'gif', 'image/webp' => 'webp', 'application/pdf' => 'pdf', 'video/mp4' => 'mp4']; $mime = (new finfo(FILEINFO_MIME_TYPE))->file($file['tmp_name']); if ($file['error'] !== UPLOAD_ERR_OK || $file['size'] > $config['max_upload_bytes'] || !isset($allowed[$mime])) { $error = '檔案格式不支援或超過 8 MB。'; } else { if (!is_dir($config['upload_dir'])) mkdir($config['upload_dir'], 0755, true); $safeName = bin2hex(random_bytes(12)) . '.' . $allowed[$mime]; if (!move_uploaded_file($file['tmp_name'], $config['upload_dir'] . '/' . $safeName)) { $error = '檔案儲存失敗。'; } else { $data['file_path'] = $config['upload_url'] . '/' . $safeName; $data['original_name'] = $file['name']; $data['mime_type'] = $mime; $data['file_size'] = $file['size']; } } } elseif ($key === 'media' && $id) { $data['file_path'] = $record['file_path']; } elseif ($key === 'media') { $error = '新增媒體時必須選擇檔案。'; } if ($error === '') { if ($id) { $sets = []; foreach ($data as $name => $_) $sets[] = "`$name` = ?"; $stmt = db()->prepare('UPDATE `' . $module['table'] . '` SET ' . implode(', ', $sets) . ' WHERE id = ?'); $stmt->execute([...array_values($data), $id]); audit('update', $module['table'], $id, $data); flash('success', '資料已更新。'); } else { $names = array_keys($data); $stmt = db()->prepare('INSERT INTO `' . $module['table'] . '` (`' . implode('`,`', $names) . '`) VALUES (' . implode(',', array_fill(0, count($names), '?')) . ')'); $stmt->execute(array_values($data)); $id = (int) db()->lastInsertId(); audit('create', $module['table'], $id, $data); flash('success', '資料已新增。'); } redirect('records.php?module=' . urlencode($key)); } $record = array_merge($record, $data); } render_header(($id ? '編輯' : '新增') . $module['label'], $key); ?>
$field): $value = $record[$name] ?? ($field['default'] ?? ''); ?>
取消