Skip to content
Advertisement

node-postgres: I can’t figure out what’s wrong with my query? (ERROR: syntax error at or near “a”)

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, jpfdhdl@live.com, 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

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement