반응형
    
    
    
  
수정할 데이터 폼에 출력
if(pathname === '/update'){
      db.query('SELECT*FROM topic', function(error, topics){
      // topic 데이터 불러와 topics에 담음
      
        if(error){ throw error; } // 예외처리
        
        db.query('SELECT*FROM topic WHERE id=?', [queryData.id], function(error2, topic){
        // topic의 특정 id값을 가져와 topic에 담음
        // id값은 배열로 가져와 ?에 치환하며, 그 값은 queryData.id
        
          if(error2){ throw error2; } // 예외처리
          var list = template.list(topics); // 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>
                <input type="submit">
              </p>
            </form>
            `,
            `<a href="/create">create</a> <a href="/update?id=${topic[0].id}">update</a>`
          );
          // 해당 id의 값인 topic은 배열 형태이기에 topic[0]으로 선택해줘야 함
          
          response.writeHead(200);
          response.end(html);
        });
      });
}
수정된 데이터 데이터베이스에 업데이트 시키기
if(pathname === '/update_process'){
      
      var body = '';
      request.on('data', function(data){
          body = body + data;
      });
      
      request.on('end', function(){
        var post = qs.parse(body); // post방식으로 전송된 값 객체 형태로 분석해 post에 담음
        
        db.query('UPDATE topic SET title=?, description=?, author_id=1 WHERE id=?', [post.title, post.description, post.id], function(error, result){
        // post에 담긴 값 해당 id에 업데이트
          response.writeHead(302, {Location: `/?id=${post.id}`});
          response.end();
        });
      });
}
글 삭제하기
if(pathname === '/delete_process'){
      var body = '';
      request.on('data', function(data){
          body = body + data;
      });
      request.on('end', function(){
          var post = qs.parse(body);
          db.query('DELETE FROM topic WHERE id=?', [post.id], function(error, result){
          // id값 가져와 삭제하기
          
            if(error){ throw error; }
            response.writeHead(302, {Location: `/`});
            response.end();
          })
      });
}반응형
    
    
    
  'Dev > Nodejs-mysql' 카테고리의 다른 글
| [Nodejs-mysql] 데이터 Select의 option으로 출력하고 선택값 저장 (0) | 2020.08.06 | 
|---|---|
| [Nodejs-mysql] Join된 테이블에서 값 가져오기 (1) | 2020.08.06 | 
| [Nodejs-mysql] 데이터 넣고 출력하기 (0) | 2020.08.05 | 
| [Nodejs-mysql] 데이터 가져와서 출력하기 (0) | 2020.08.05 | 
| [Nodejs-mysql] nodejs에서 mysql 사용하기 (0) | 2020.08.05 |