반응형
[생활코딩] MySQL join을 이용해서 글수정 구현
수정페이지에 Select 넣고 선택되었던 option 출력하기
main.js
if(pathname === '/update'){
db.query('SELECT*FROM topic', function(error, topics){
if(error){ throw error; }
db.query('SELECT*FROM topic WHERE id=?', [queryData.id], function(error2, topic){
if(error2){ throw error2; }
db.query('SELECT*FROM author', function(error3, authors){
// author값 받아서 authors에 담기
var list = template.list(topics);
var html = template.HTML(topic[0].title, list,
`
<form action="/update_process" method="post">
<input type="hidden" name="id" value="${topic[0].id}">
<p><input type="text" name="title" placeholder="title" value="${topic[0].title}"></p>
<p><textarea name="description" placeholder="description">${topic[0].description}</textarea></p>
<p>${template.authorSelect(authors, topic[0].author_id)}</p>
<p><input type="submit"></p>
</form>
`,
`<a href="/create">create</a> <a href="/update?id=${topic[0].id}">update</a>`
);
// template.js의 authorSelect 사용하고 두번째 인자로 선택된 topic의 author_id값 넘기기
response.writeHead(200);
response.end(html);
});
});
});
}
template.js
module.exports = {
HTML:function(title, list, body, control){...},
list:function(topics){...},
authorSelect:function(authors, author_id){ // 두번째 인자로 author_id 받기
var tag = '';
var i = 0;
while(i < authors.length){ // option을 생성할 때
var selected = '';
if(authors[i].id === author_id){
// author의 id와 인자로 받은 topic[0].author_id가 같으면
selected = ' selected'; // selected에 문자 selected 넣기
}
tag += `<option value="${authors[i].id}"${selected}>${authors[i].name}</option>`;
// option 태그에 selected값 넣기
i++;
}
return `
<select name="author">
<option selected disabled hidden>Select</option>
${tag}
</select>
`
}
}
Select의 option 수정하고 저장하기
if(pathname === '/update_process'){
var body = '';
request.on('data', function(data){
body = body + data;
});
request.on('end', function(){
var post = qs.parse(body);
db.query('UPDATE topic SET title=?, description=?, author_id=? WHERE id=?', [post.title, post.description, post.author, post.id], function(error, result){
response.writeHead(302, {Location: `/?id=${post.id}`});
response.end();
});
});
// 업데이트할 author_id값으로 post.author 넣기
}
반응형
'Dev > Nodejs-mysql' 카테고리의 다른 글
[Nodejs-mysql] 테이블 만들고 모듈 분리하기 (0) | 2020.08.07 |
---|---|
[Nodejs-mysql] DB 관련 코드 모듈로 분리하기 (0) | 2020.08.07 |
[Nodejs-mysql] 데이터 Select의 option으로 출력하고 선택값 저장 (0) | 2020.08.06 |
[Nodejs-mysql] Join된 테이블에서 값 가져오기 (0) | 2020.08.06 |
[Nodejs-mysql] 데이터 수정/삭제하기 (0) | 2020.08.06 |