4

I want to dynamically create a Table in MySQL from Node.js

con.query('CREATE TABLE ?', req.params.username + '(id INT(100) NOT NULL
AUTO_INCREMENT, name TINYTEXT, PRIMARY KEY(id))', function (err, result) {
                        if (err) console.log(err);
                        else console.log('Table created ' + result);
                    });

When the query is hard-coded like ,

con.query('CREATE TABLE Sample (id INT(100) NOT NULL AUTO_INCREMENT, name 
TINYTEXT, PRIMARY KEY(id))', function (err, result) {
                        if (err) console.log(err);
                        else console.log('Table created ' + result);
                    });

It works.

So, my question is how to create a table dynamically ?

1 Answer 1

5

You're trying to use a parameterized query to substitute a table name. You Can't Do That™. You can't do it with column names either.

You need to write code containing a text string with your data-definition language without ? parameters and then run it. That's easy to do with string manipulation in JS.

var tableDef = 'CREATE TABLE '+ req.params.username + ' (id INT(100) NOT NULL AUTO_INCREMENT, name TINYTEXT, PRIMARY KEY(id))';
con.query(tableDef, ...etc )
Sign up to request clarification or add additional context in comments.

1 Comment

Be sure to sanitize req.params.username before concatenation, as this is currently vulnerable to SQL injection

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.