0

I'm trying to send the inserted data with raw queries using sequelize then show it. Below is my code:

const c_product_post = async (req, res) => {
try {
    const sql = `INSERT INTO products (p_name, p_price, p_stock, p_review, "createdAt", "updatedAt")
    VALUES ('${req.body.product_name}', ${req.body.product_price}, ${req.body.product_stock}, ${req.body.product_review}, now(), now());`
    const postData = await Product.sequelize.query(sql)
    // await postData.save()
    res.send({
        message: "success add new product",
        data: postData
    })
}
catch (err) {
    res.send({
        message: err
    })
  }
}

what I'm trying to achieve is that after the data is inserted then it will be shown (see below image in red):

enter image description here

Muhammad Haekal
  • 477
  • 6
  • 22

1 Answers1

1

Add RETURNING clause to your query. Try this

INSERT INTO products (p_name, p_price, p_stock, p_review, "createdAt", "updatedAt")
    VALUES ('${req.body.product_name}', ${req.body.product_price}, ${req.body.product_stock}, ${req.body.product_review}, now(), now()) 
RETURNING *;

Please note that your approach is highly SQLi prone. Consider using prepared statements instead of text substitution.

Stefanov.sm
  • 11,215
  • 2
  • 21
  • 21
  • Thanks @Stefanov.sm it worked, but sorry can you explain more about "Consider using prepared statements instead of text substitution". I didn't get what you mean or may you give me a better approach for my queries if you don't mind. I'm still new about this really sorry for extra question. – Muhammad Haekal Jul 29 '21 at 05:38
  • You can start diving into the issue [here](https://stackoverflow.com/questions/8263371/how-can-prepared-statements-protect-from-sql-injection-attacks) and [here](https://stackoverflow.com/questions/49242772/how-to-create-prepared-statements-in-sequelize) – Stefanov.sm Jul 29 '21 at 06:35
  • Thanks @Stefanov.sm I will dive into both links you provided, thanks for the help appreciated. – Muhammad Haekal Jul 29 '21 at 11:51