2

I have a node.js app using node-mysql to query a MySQL database.

Problem: It appears that when I make the table name in the query a variable, things stop working. Did I miss out on something?

Working Node Code

client.query('SELECT * from tableA',
                function(error, results, fields) {
                    if (error)
                        throw error;
                    callback(results);
                });

Non-working Node Code

client.query('SELECT * from ?',
                [ tableA ],
                function(error, results, fields) {
                    if (error)
                        throw error;
                    callback(results);
                });
2

2 Answers 2

3

You could probably just append the table name to the string (pseudo code, I don't know node.js)

client.query('SELECT * from ' + [tablaA],
                function(error, results, fields) {
                    if (error)
                        throw error;
                    callback(results);
                });
Sign up to request clarification or add additional context in comments.

3 Comments

and you kinda have the answer in your previous question stackoverflow.com/questions/8317472/… :)
Right, I was wondering if this applies to MySQL queries in general like in PHP, or is this node.js specific
In Mysql table names are not allowed to be variables (?) in prepared statements and I guess that nodejs is doing a prepared statement in the background.
0

They reason why it's not working is pretty clear.

The query from the non-working code will be :

SELECT * from 'tableA'

A solution is the one from @Andreas, but you will have the same problem in a where statement or insert for other values you don't want to be escaped like "null" value. ( convert into a string)

Same problem here

Check out the source how format && escape from node-mysql works.

2 Comments

Am i right to say that table names, database names, column names cannot be escaped, while values to be added to the columns and MySQL functions can?
I would say yes, placeholders are normally for dynamic data (parameters)

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.