본문 바로가기
WEB/Nodejs-mysql

[Nodejs-mysql] Select값 수정하기

by Ellen571 2020. 8. 7.

[생활코딩] 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 넣기
}
반응형