Blog

[CRUD]UPDATE

문의사항에 업데이트 기능을 추가
Table of Content

테이블 수정

우선 현재 테이블의 구조는 다음과 같다.
CREATE TABLE `contact` ( `id` int NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `phone` varchar(20) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, `memo` text, `create_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `modify_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
JavaScript
복사
여기에 status라는 글의 상태를 추가하여 ongoing(진행중), done(완료) 로 문의에 대한 답변 상태를 추가하고자 한다. 따라서 문의가 생성되면 기본값으로 ongoing상태를 가져야 하며 관리자가 글의 상태를 변경(업데이트) 할 수 있도록 한다.
테이블에 status라는 컬럼을 추가해야 한다. 테이블을 변경하는 것이기 때문에 alter table로 시작되며 status 컬럼을 추가(add)하게 된다. default로 ongoing 값을 가지도록 설정했다.
ALTER TABLE `contact` ADD COLUMN `status` varchar(20) DEFAULT 'ongoing';
JavaScript
복사
기본값 설정에 따라 기존 모든 데이터들도 기본값이 적용되어 ongoing 상태로 나타나는 것을 볼 수 있다.

Update API 작성

app.js Update API 작성

post요청을 통해 id를 PathVariable로 받아온다. update 쿼리를 통해서 해당 id의 row중 status 컬럼값을 done으로 수정한다.
app.post('/api/contactUpdate/:id', function (req, res) { const id = req.params.id; const status = "done"; // 커넥션 풀에서 커넥션을 얻어옵니다. connectionPool.getConnection((err, connection) => { if (err) { console.error('MySQL 커넥션 얻는 중 에러 발생:', err); res.status(500).send('내부 서버 오류'); } else { const updateQuery = ` UPDATE contact SET status = '${status}' WHERE id = '${id}'; `; // 얻어온 커넥션을 사용하여 쿼리를 실행합니다. connection.query(updateQuery, function (queryErr, result) { // 쿼리 실행이 끝나면 반드시 커넥션을 풀에 반환합니다. connection.release(); if (queryErr) { console.error('데이터 업데이트 중 에러 발생:', queryErr); res.status(500).send('내부 서버 오류'); } else { console.log('데이터가 업데이트되었습니다.'); res.send("<script>alert('문의사항이 업데이트되었습니다.'); location.href='/contactList'</script>"); } }); } }); });
JavaScript
복사

contactList.ejs 요청 부분 수정

추가된 데이터의 컬럼인 status를 볼 수 있도록 테이블 컬럼을 추가하고 update버튼을 추가한다.
<%-include('header.ejs')%> <h2>문의 목록입니다.</h2> <table border=1> <tr> <th>id</th> <th>name</th> <th>phone</th> <th>email</th> <th>content</th> <th>create_at</th> <th>modify_at</th> <th>status</th> <th>DONE</th> <th>DELETE</th> </tr> <% lists.forEach(function(item) { %> <tr> <td><%=item.id%></td> <td><%=item.name%></td> <td><%=item.phone%></td> <td><%=item.email%></td> <td><%=item.memo%></td> <td><%=item.create_at%></td> <td><%=item.modify_at%></td> <td><%=item.status%></td> <td> <form action="/api/contactUpdate/<%=item.id%>" method="post"> <button type="submit" onclick="return confirm('완료 하시겠습니까?')">UPDATE</button> </form> </td> <td> <form action="/api/contactDelete/<%=item.id%>" method="post"> <button type="submit" onclick="return confirm('정말 삭제하시겠습니까?')">DELETE</button> </form> </td> </tr> <% }) %> </table> <%-include('footer.ejs')%>
JavaScript
복사
문의사항 완료 후 정상적으로 status 컬럼의 값이 수정된 것을 확인 할 수 있다.