Ejs,Mysql로 CRUD 구현하기

개발정리·2022년 3월 29일
1
post-thumbnail

🪓Ejs,Mysql로 CRUD 구현하기

ejs로 CRUD를 구현하면서 Ejs 문법을 익혀보겠습니다.

글 보기 귀찮으신분들은 깃허브에서 소스코드 보시면됩니다.

EJS 자동완성

Ejs자동완성없으면 진짜 하기싫으니까
여기서 다운받아주세요

Topic 테이블생성

제가 Egoing생활코딩을 보면서 CRUD를 공부해서그런지 글,내용이 들어가는 테이블의 이름은 항상 Topic으로 해둡니다.
별로 중요한 내용이 아니니 그냥 넘어가겠습니다.

create table Topics(
    id int auto_increment primary key,
    Title varchar(30) not null,
    Article varchar(100) not null,
    Created date not null
)

Main페이지 (READ)

app.get("/main", (req, res) => {
  const query = "SELECT * from Topics";
  db.query(query, (err, result) => {
    err ? res.send(err) : res.render("main", { data: result });
  });
});

테이블의 모든 데이터를 main.ejs에 넘겨줍니다.

  <body>
    <div class="btnBox">
      <button
        onclick="location.href = '/create'"
        class="w-50 mb-5 mt-2 btn btn-success"
      >
        글쓰기
      </button>
    </div>

    <table class="table TableBox">
      <thead>
        <tr>
          <th scope="col">#</th>
          <th scope="col">글 제목</th>
          <th scope="col">내용</th>
          <th scope="col">날짜</th>
          <th scope="col">수정/삭제</th>
        </tr>
      </thead>

      <tbody>
        <% data.forEach((el,index) => {%>
        <tr>
          <th scope="row"><%= index + 1%></th>
          <td><%= el.Title %></td>
          <td><%= el.Article %></td>
          <td><%= el.Created.toLocaleDateString() %></td>
          <td>
            <a class="btn btn-warning" href="/edit/<%= el.id %> ">수정/삭제</a>
          </td>
        </tr>
      </tbody>
      <% }) %>
    </table>
  </body>
</html>

그냥 bootstrap-Table복사붙여넣기했습니다. 중요한건 이게아니고
ejseach(자동완성)으로 받아온 Data를 foreach문으로
테이블에 하나하나 추가해줍니다.
중요한건

<a class="btn btn-warning" href="/edit/<%= el.id %> ">수정/삭제</a>

이 부분인데 리액트처럼 저런식으로 데이터를 html사이에 쏙 집어넣을수있습니다. 아 그리고 vscode에서 저거 자동완성을 잡아주지않고 prettier쓰시는 분들은 자꾸 이상하게

"/edit/<%= "el.id" %>"

이런식으로 가둬버리는데 처음부터 끝까지 하드코딩해야지 이상한 자동완성이 안됩니다.

main.ejs



글 쓰기 구현 (CREATE)

Create.ejs

<body>
    <form
      id="edit"
      style="height: 100vh"
      class="container d-flex flex-column justify-content-center"
      action="/create"
      method="post"
    >
      <h2 class="text-center">Create</h2>
      
      <div class="d-flex justify-content-center">
        <input name="Title" class="w-50 form-control text-center" type="text" />
      </div>
      
      <textarea name="Article" class="mt-4 text-center form-control" rows="8">/textarea>
     
      <div class="text-center mt-3">
        <button type="submit" class="btn btn-primary">글쓰기</button>
      </div>
      
    </form>
 </body>

그냥 /create로 post요청을 보냅니다.

app.post("/create", (req, res) => {
  const Title = req.body.Title;
  const Article = req.body.Article;
  const query = `
  insert into Topics(Title ,Article,Created)
  values(?,?,DATE_FORMAT(now(), '%Y-%m-%d'))`;
  
db.query(query, [Title, Article], (err, result) => {
      err ? res.send(err) : res.send('<script>location.href = "/main"</script>');
 });
});

body-parser로 제목과 글을 받아와서 insert문으로 Topics Table에 추가해줍니다.
db.qeury의 두번째 인자로 집어넣는게 익숙하지않다면 익숙하게 바꾼 형태는 이렇습니다.

  insert into Topics(Title ,Article,Created)
  values(${Title},${Article},DATE_FORMAT(now(), '%Y-%m-%d'))`;





수정 기능 구현(UPDATE)

  const ID = req.params.id;
  const query = "select * from Topics where id = ?";
  db.query(query, ID, (err, result) => {
    if (err) {
      res.send(err);
    } else if (result == "") {
      res.send("찾으시는 페이지가 존재하지않습니다.");
    } else res.render("Edit", { id: ID, Data: result[0] });
  });
});

단순히 id를 파라미터로 (/id/3)이런식으로 받아와서
where문으로 찾은 글을 리턴해줍니다.
만약에 찾지못해서 결과값이 [] < 이거라면 찾으시는 페이지가 없다고 해줍니다.

  <form id="delete" action="/delete" method="post"></form>
    <form
      id="edit"
      style="height: 100vh"
      class="container d-flex flex-column justify-content-center"
      action="/edit"
      method="post"
    >
      <h2 class="text-center">
        <%= Data.Created.toLocaleDateString() + "에 작성됨"%>
      </h2>
      <input
        name="Title"
        class="text-center form-control"
        value="<%= Data.Title %> "
        type="text"
      />
      <input name="id" type="hidden" value="<%= Data.id %> " />
      <input name="id" form="delete" type="hidden" value="<%= Data.id %> " />
      <textarea name="Article" class="mt-4 text-center form-control" rows="8">
    <%= Data.Article %> 
    </textarea
      >
      <div class="text-center mt-3">
        <button type="submit" class="btn btn-warning">수정</button>
        <button type="submit" form="delete" class="btn m-3 btn-danger">
          삭제
        </button>
      </div>
    </form>

다 비슷비슷해서 ejs부분은 설명을 안해도되지만 자세히 보시면
form이 두개입니다. 이 부분만 조심하시면될거같습니다.
지금보니까 왜 저렇게 코드를 짯을까 싶네요 귀찮아서 어거지로 짠 느낌

/edit post요청 처리

app.post("/edit", (req, res) => {
const Title = req.body.Title;
const Article = req.body.Article;
const ID = req.body.id;
const query = `
  update Topics set Title = ?, 
  Article = ?, 
  Created = DATE_FORMAT(now(), '%Y-%m-%d') where id = ? `;
db.query(query, [Title, Article, ID], (err, result) => {
  err ? console.log(err)
  : res.send('<script>location.href = "/main"</script>');
});

update문을 사용해서 수정기능을 구현했습니다.




완성된 모습

https://github.com/leejw05/ejs-board/blob/master/README.md
(동영상있음)

근데 CRUD 중에 D가없는이유는(Delete)
제 글 보고 따라하시는 분이 없을거같지만 혹시라도 계신다면
Delete기능은 직접 구현해보세요 안되면 git clone해서 본인걸로 만들어버리면됩니다.

profile
배운거 정리해요

0개의 댓글