Skip to content
Advertisement

Syntax error in SQL when inserting data via nodejs

I have a simple nodejs code in pipedream that sends the body email to mySQL Database. i have checked the connection to database and its working. Here is my code

const mysql = require('mysql2/promise');

const { host, port, username, password, database } = auths.mysql

const connection = await mysql.createConnection({
  host,
  port,//3306
  user:"u648845344_demo",
  password,
  database,
});

const [rows, fields] = await connection.execute(
  "INSERT INTO Testing (Email) VALUES (${JSON.stringify(steps.trigger.event.body.email)})"
  );
console.log(rows);
//console.log(${JSON.stringify(steps.trigger.event.body.email)})

Error i am getting

ErrorYou have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ‘{JSON.stringify(steps.trigger.event.body.email)})’ at line 1 at PromiseConnection.execute (/tmp/ee/node_modules/mysql2/promise.js:110:22) at Object.module.exports (/steps/mysql.js:14:41) at process._tickCallback (internal/process/next_tick.js:68:7)

i tried getting email on console log but then error i am getting is

TypeError [ERR_INVALID_ARG_TYPE]The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type undefined

Advertisement

Answer

This is a classic SQL injection bug, and it’s easily fixed by using prepared statements:

const [rows, fields] = await connection.execute(
  "INSERT INTO Testing (Email) VALUES (?)",
  [ steps.trigger.event.body.email ]
);

If you write your queries without data, just placeholders, and use methods like this to add the data to the query via the driver you will not create any SQL injection bugs. These are an extremely serious form of bug because a single one, if discovered, could lead to a catastrophic outcome for you, your project and any business you’re working for.

Using JSON.stringify for SQL protection is, and I cannot stress this enough, completely and wildly inappropriate. That escapes JSON and only JSON. You must use SQL-specific escaping functions if that occasion arises, but use prepared statements with placeholder values whenever possible.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement