PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, ]; $pdo = new PDO($dsn, $user, $pass, $options); // 폼 데이터 수집 $userId = $_SESSION['user']['userId']; // auth.php에서 세션에 담긴 userId $category = trim($_POST['category'] ?? ''); $title = trim($_POST['title'] ?? ''); $content = trim($_POST['content'] ?? ''); $secret = isset($_POST['secret']) ? 1 : 0; // 체크박스 $status = 'await'; // 항상 답변대기 // 유효성 검사 $errors = []; $allowedCats = ['error','improvement','general','notice']; if (!$category || !in_array($category, $allowedCats, true)) { $errors[] = '올바른 구분을 선택해주세요.'; } if (mb_strlen($title) > 100 || $title === '') { $errors[] = '제목은 1~100자 사이여야 합니다.'; } if (mb_strlen($content) === 0) { $errors[] = '내용을 입력해주세요.'; } if ($errors) { // 에러 처리: 뒤로 가기 or JSON 리턴 foreach ($errors as $e) echo "
$e
"; echo ""; exit; } try { // 트랜잭션 시작 $pdo->beginTransaction(); // 1) 게시글 INSERT $sql = "INSERT INTO qa_posts (user_id, category, title, content, is_secret, status, created_at) VALUES (:uid, :cat, :tit, :cont, :sec, :st, NOW())"; $stmt = $pdo->prepare($sql); $stmt->execute([ ':uid' => $userId, ':cat' => $category, ':tit' => $title, ':cont' => $content, ':sec' => $secret, ':st' => $status, ]); $postId = $pdo->lastInsertId(); // 2) 첨부파일 처리 (uploads/qa/YYYYMMDD 디렉토리) if (!empty($_FILES['attach']) && is_array($_FILES['attach']['tmp_name'])) { $baseDir = __DIR__ . '/uploads/qa/' . date('Ymd'); if (!is_dir($baseDir)) mkdir($baseDir, 0755, true); $fileStmt = $pdo->prepare( "INSERT INTO qa_attachments (post_id, file_name, file_path, file_size, uploaded_at) VALUES (:pid, :fname, :fpath, :fsize, NOW())" ); foreach ($_FILES['attach']['tmp_name'] as $i => $tmp) { if (!is_uploaded_file($tmp)) continue; $origName = $_FILES['attach']['name'][$i]; $size = $_FILES['attach']['size'][$i]; // 파일명 충돌 방지 $ext = pathinfo($origName, PATHINFO_EXTENSION); $newName = uniqid() . ($ext ? ".$ext" : ''); $dest = "$baseDir/$newName"; if (move_uploaded_file($tmp, $dest)) { $fileStmt->execute([ ':pid' => $postId, ':fname' => $origName, ':fpath' => substr($dest, strlen(__DIR__)), ':fsize' => $size, ]); } } } $pdo->commit(); // 완료 후 상세 보기로 header("Location: view.php?id={$postId}"); exit; } catch (Exception $e) { $pdo->rollBack(); exit('오류 발생: ' . $e->getMessage()); }