2

I want to store an array of languages a user knows in the database.

My code:

 router.post('/create-user', async (req, res) =>{
      const query = `INSERT INTO users(name, languages, created_at, updated_at, deleted) 
                     VALUES ('${name}', ${languages}, NOW(), NOW(), 0)`;
      const result = await db.query(query);
      // rest of code..
    });

I defined a column languages in the database of type JSON.

I call this API in postman with body:

{
  "name" : "test",
  "languages" : "['English', 'German']"
}

But I get the following error:

 "error": "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'English', 'German'].

How can I solve this issue?

2

2 Answers 2

1

You are directly writing query - which is VERY BAD practice. Instead use:

  const query = 'INSERT INTO users(name, languages, created_at, updated_at, deleted) VALUES (?, ?, NOW(), NOW(), ?)';
  const result = await db.query(query, [name, language, 0]);

Which will escape all problematic characters in the query, more you can read here: https://www.npmjs.com/package/mysql2#using-prepared-statements

2
  • I'm actually getting an error using this approach - Error: Incorrect datetime value: 'NOW()' for column 'created_at' at row 1. My created_at column's type is TIMESTAMP.
    – Jadenkun
    Commented Mar 20, 2020 at 8:46
  • 1
    Updated answer..... NOW() shouldbt be escaped so it shouldnt be in parameters and inserterd by ?. Should work for you now
    – Seti
    Commented Mar 21, 2020 at 10:43
-1

It looks like you're trying to pass multiple values at once. Try:

 router.post('/create-user', async (req, res) =>{
      languages.forEach((language) => {

      const query = `INSERT INTO users(name, languages, created_at, updated_at, deleted) 
                     VALUES ('${name}', ${language}, NOW(), NOW(), 0)`;
      const result = await db.query(query);
      })

      // rest of code..
    });
1
  • Please - dont teach bad examples to new programmers. You should NEVER EVER write direct queries without sanitizing data before pushing them into the database. Example here should look like (at least): const query = 'INSERT INTO users(name, languages, created_at, updated_at, deleted) VALUES (?, ?, ?, ?, ?)'; const result = await db.query(query, [name, language, 'NOW()', 'NOW()', 0]);
    – Seti
    Commented Mar 9, 2020 at 16:07

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.