본문 바로가기
WEB/Nodejs-mysql

[Nodejs-mysql] 데이터 넣고 출력하기

by Ellen571 2020. 8. 5.

[생활코딩] MySQL로 글생성 기능 구현

 

else if(pathname === '/create_process'){

      var body = '';
      request.on('data', function(data){
          body = body + data;
      });
      
      request.on('end', function(){
          var post = qs.parse(body);
          var title = post.title;
          var description = post.description;

          db.query(`INSERT INTO topic (title, description, created, author_id) VALUES (?, ?, NOW(), ?)`, [title, description, 1], function(err, result){
          // 사용자가 입력한 값(title, description)을 배열로 받아 값 ?에 넣음
          // insert된 값은 result에 담김
          
            if(err){ throw error; }
            
            response.writeHead(302, {Location: `/?id=${result.insertId}`});
            // insertId로 result의 id값 가져옴
            response.end();
          });
      });
}

 

데이터 넣기 쿼리문

INSERT INTO topic (title, description, created, author_id) VALUES (?, ?, NOW(), ?)

 

데이터 id값 가져오기

result.insertId

반응형