본문 바로가기
WEB/Nodejs-mysql

[Nodejs-mysql] 테이블값 삭제하기

by Ellen571 2020. 8. 7.

[생활코딩] 저자 삭제 기능 구현

 

 

테이블값 삭제하기

 

lib/template.js

uthorTable:function(authors){
    var tag = '<table>';
    var i = 0;
    while(i < authors.length){
        tag += `
            <tr>
                <td>${authors[i].name}</td>
                <td>${authors[i].profile}</td>
                <td><a href="/author/update?id=${authors[i].id}">update</a></td>
                <td>
                  <form action="/author/delete_process" method="post">
                    <input type="hidden" name="id" value="${authors[i].id}">
                    <input type="submit" value="delete">
                  </form>
                </td>
            </tr>
        `;
        // delete는 링크가 아닌 form으로 만들어야 함
        // delete는 클릭 시 /author/delete_process 이동하고 id값으로 authors[i].id 전달
        i++;
    };
    tag += '</table>';
    return tag;
  }

 

lib/author.js

exports.delete_process = function(request, response){
    var body = '';
    request.on('data', function(data){
        body += data;
    });

    request.on('end', function(){
        var post = qs.parse(body);

        db.query('DELETE FROM author WHERE id=?', [post.id], function(error, result){
        // post로 받은 id값과 일치하는 author값 삭제
            if(error){ throw error; }
            response.writeHead(302, {Location: `/author`});
            response.end();
        });
    });
}

 

main.js

else if(pathname === '/author/delete_process'){
      author.delete_process(request,response);
}

 

 

삭제될 테이블과 연관된 다른 테이블의 값도 삭제하기

 

lib/author.js

exports.delete_process = function(request, response){
    var body = '';
    request.on('data', function(data){
        body += data;
    });

    request.on('end', function(){
        var post = qs.parse(body);

        db.query('DELETE FROM topic WHERE author_id=?', [post.id], function(error1, result1){
        // 삭제될 author id값을 가지는 topic 값 삭제하기
        
            if(error1){ throw error; }
            
            db.query('DELETE FROM author WHERE id=?', [post.id], function(error2, result){
                if(error2){ throw error; }
                response.writeHead(302, {Location: `/author`});
                response.end();
            });
        });        
    });
}
반응형