데이터 입력
👉 M product.js
...
save() {
return db.execute(
"INSERT INTO products (title, price, imageUrl, description) VALUES (?,?,?,?)",
[this.title, this.price, this.imageUrl, this.description]
);
}
...
🧐 데이터 삽입
- 데이터 삽입에는 INSERT INTO를 사용한다. 그 다음 데이터를 삽입할 테이블을 정의하는데 지금은 'products' 테이블에 괄호를 열어 값을 넣고싶은 필드를 나열한다.
- VALUES 키워드 다음에 괄호 안에 값을 입력하는데 사용자가 웹 페이지 입력 필드에 특이 데이터를 삽입해 SQL 쿼리로 실행될 때 발생하는 공격 패턴인 SQL 인젝션을 방지하기 위해 물음표를 써야한다.
- 그래서 데이터를 삽입하는 필드마다 물음표를 입력하고 쉼표로 나누고, 물음표 대신 삽입하는 값을 실행하기 위해 두 번째 인자를 전달한다. 즉 보안을 추가로 확보하는 것.
- [] 배열에 this.title 같은 요소를 넣어서 promise를 반환 받는다.
👉 C admin.js
exports.postAddProduct = (req, res, next) => {
const title = req.body.title;
const imageUrl = req.body.imageUrl;
const price = req.body.price;
const description = req.body.description;
const product = new Product(null, title, imageUrl, description, price);
product
.save()
.then(() => {
res.redirect("/");
})
.catch((err) => console.log(err));
};
단일 조건 데이터 가져오기
👉 M product.js
...
static findById(id) {
return db.execute("SELCET * FROM products WHERE product.id = ?", [id]);
}
...
🧐 where 조건
- id = ?를 입력하면 MySQL에 값을 다시 주입하라고 알려주는 것임, 여기서 인수는 id다. 이 promise를 반환하기 위해 앞에 return을 입력하면된다.
👉 C shop.js
...
exports.getProduct = (req, res, next) => {
const prodId = req.params.productId;
Product.findById(prodId)
.then(([product]) => {
console.log(product);
res.render("shop/product-detail", {
product: product[0],
pageTitle: product.title,
path: "/products",
});
})
.catch((err) => console.log(err));
};
...