0

I'm working on a side project and have hit a bit of a dead end when coming across this error. I've ascertained that it's originating from node-postgres package somewhere, but I see nothing inherently wrong with my query!

Here's my code:

router.post("/product/:id", async (req, res) => {
  const id = req.params.id;
  if (!id) throw new Error("ID not present");

  if (!validateProductReviewForm(req.body))
    throw new Error("Form not valid. Please fix and try again");

  const { name, email, rating, comment } = req.body;
  const date = new Date();

  const sqlText = `INSERT INTO reviews ("name", email, rating, comment, date, productid) VALUES (${name}, ${email}, ${rating}, ${comment}, ${date}, ${id})`;
  console.log(sqlText);
  const { rows } = await query(sqlText);
  res.send(rows);
});

And here is my logged query:

INSERT INTO reviews ("name", email, rating, comment, date, productid) VALUES (Bill, [email protected], 2, testing a review post, Tue Mar 30 2021 17:59:22 GMT+0100 (British Summer Time), 2)

Any help would be much appreciated. Many thanks

1
  • 3
    Single quotes around the values? Commented Mar 30, 2021 at 17:08

1 Answer 1

3

You were missing the quote delimiters for the string and date values in your query. However instead of adding the necessary single quotes to the sqlText variable, use a better technique and pass the values as an array.

const sqlText = 'INSERT INTO reviews ("name", email, rating, comment, date, productid) VALUES ($1, $2, $3, $4, $5, $6)';
const values = [name, email, rating, comment, date, id];
const { rows } = await query(sqlText, values);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.