0

I want to query my mysql database in Node for a complete table. The name of the table is supplied via a string from javascript. Mysql throws an error because if I insert it into the query in the following way it results in this error:

'{"code":"ER_PARSE_ERROR","errno":1064,"sqlMessage":"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 ''1$2_Anzahl_der_Anrufe'' at line 1","sqlState":"42000","index":0,"sql":"SELECT * FROM '1$2_Anzahl_der_Anrufe'"}'

    let result = [];
    tableName = '1$2_Anzahl_der_Anrufe'

    connectionData.query('SELECT * FROM ?', [tableName], function (err, res) {
        if (err) return callback(err);
        if (res.length) {
            for (var i = 0; i < res.length; i++) {
                result.push(res[i]);
            }
        }
        callback(result);
    });

If I try it directly in mysql without the quotes everything works or if insert it directly without the question mark in my js code. How can I escape the quotes?

user3742929
  • 360
  • 3
  • 17
  • If you allow the user to specify the table name, that's as good as any other SQL injection. `SELECT * FROM admin_users`. Why, thanks. – deceze May 16 '19 at 09:26
  • The user selects the name indirectly from a dropdown menu and isn't able to change it. – user3742929 May 16 '19 at 09:28
  • `SELECT * FROM 1$2_Anzahl_der_Anrufe` isn't a valid query when I run it. Regardless, this isn't about the quotes. Your code inserts `1$2_Anzahl_der_Anrufe`, not `'1$2_Anzahl_der_Anrufe'`. –  May 16 '19 at 09:29
  • As for the injection issue, you can change client side code easily. Anything a user sends has to be validated and sanitized on the server, always. And anybody can write, say, a Python script that pretends to be a browser and sends arbitrary requests to your server. –  May 16 '19 at 09:30
  • *"from a dropdown menu and isn't able to change it"* – *laughs in HTTP* – If you believe a client-side dropdown menu will prevent users from submitting arbitrary values via HTTP, you know nothing Jon Snow. – deceze May 16 '19 at 09:31
  • After it is sent to the server, it is checked against an existing list of names. Is that fine? – user3742929 May 16 '19 at 09:31
  • Yes, that'd be fine. And if you do that, you don't need to parameterise the value and can simply concatenate it into the string. – deceze May 16 '19 at 09:32

0 Answers0