0

I have query for adding columns to a database in my Node server:

const query = 'ALTER TABLE ' + mysql.escape(tableData[i]) + ' ADD ' + mysql.escape(attributeData[0]) + ' FLOAT DEFAULT NULL;'

If I use they query without mysql.escape() it adds the columns as it is supposed to. However when using the escape function for preventing sql injections it no longer works. Why is that?

Here is an example query with the escape function, it returns no error but also doesn't add the column to the table:

ALTER TABLE '1$0_Test_2018' ADD 'Eigenschaft_3' FLOAT DEFAULT NULL;

This query works just fine, however I want to make sure to escape user data:

ALTER TABLE 1$0_Test_2018 ADD Eigenschaft_3 FLOAT DEFAULT NULL;
16
  • 1
    What's some example data? Commented Jun 13, 2019 at 8:02
  • 1
    @Jacquesジャック The OP didn't mention errors, they just stated the code isn't functioning. Commented Jun 13, 2019 at 8:04
  • 2
    @JackBashford You are correct, but I'm sure with your 25k rep, you know as well as I do that questions with this sparse of details tend to leave out important information, like example data, errors. etc. Commented Jun 13, 2019 at 8:06
  • 1
    The example data point was requested in the first comment, and the OP has stated they are "getting no errors". Commented Jun 13, 2019 at 8:07
  • 2
    Ah, I found this in the docs: If you can't trust an SQL identifier (database / table / column name) because it is provided by a user, you should escape it with mysql.escapeId(identifier) So change escape to escapeId in your code for column/table names. Commented Jun 13, 2019 at 8:22

1 Answer 1

1

It looks like your issue is probably that the escape method returns the value wrapped with quotes instead of backticks.

In the github docs it looks like you just need to change escape to escapeId.

If you can't trust an SQL identifier (database / table / column name) because it is provided by a user, you should escape it with mysql.escapeId(identifier)

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.