본문 바로가기
WEB/Nodejs-mysql

[Nodejs-mysql] 테이블값 업데이트 하기

by Ellen571 2020. 8. 7.

[생화코딩] 저자 수정 기능 구현

 

 

lib/template.js

authorTable: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>delete</td>
            </tr>
        `;
        i++;
    };
    // update에 a태그 붙이고 이동 링크는 author/update?id=author의 id값
    tag += '</table>';
    return tag;
}

 

lib/author.js

var db = require('./db');
var template = require('./template.js');
var qs = require('querystring');
var url = require('url');

exports.update = function(request, response){
    db.query('SELECT*FROM topic', function(error, topics){
        db.query('SELECT*FROM author', function(error2, authors){

            var _url = request.url;
            var queryData = url.parse(_url, true).query;

            db.query('SELECT*FROM author WHERE id=?', [queryData.id], function(error3, author){
            // id가 queryData.id값인 author값 가져와 author에 담기
            
                var title = 'Author';
                var list = template.list(topics);
                var html = template.HTML(title, list,
                    `
                        ${template.authorTable(authors)}
                        <style>
                            table { border-collapse: collapse}
                            td {border: 1px solid #333; padding: 5px 10px}
                        </style>
                        <form action="/author/update_process" method="post">
                            <input type="hidden" name="id" value="${queryData.id}">
                            <p><input type="text" name="name" value="${author[0].name}"></p>
                            <p><textarea name="profile">${author[0].profile}</textarea></p>
                            <p><input type="submit" value="update"></p>
                        </form>
                    `,
                    ``
                );
                // update클릭 시 /author/update_process로 이동하면서 id값으로 queryDate.id 전달
                // name에 선택된 author 이름값 출력
                // profile에 선택된 author 프로파일값 출력
                
                response.writeHead(200);
                response.end(html);
            });
        });
    });    
}

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

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

        db.query('UPDATE author SET name=?, profile=? WHERE id=?', [post.name, post.profile, post.id], function(error, result){
        // 받아온 post값 업데이트
        
            if(error){ throw error; }
            response.writeHead(302, {Location: `/author`});
            response.end();
        });
    });
}
반응형