In the wiki for node-mysql, I noticed that variables (kind of) were inserted into the SQL query in 2 different ways, one is by inserting a variable in the middle of the query string, and the other way is by putting ? in the query string and defining the values for these ? in an array in the next argument. The values replacing ? in the query are escaped.
What is the difference and when should I use one over the other? (If we want the table name to be a variable, should it be escaped?)
Wiki Code
client.query(
'INSERT INTO '+TEST_TABLE+' '+
'SET title = ?, text = ?, created = ?',
['super cool', 'this is a nice text', '2010-08-16 10:00:23']
);
Wiki Link: https://github.com/felixge/node-mysql
Wiki extract:
Sends a sql query to the server. ‘?’ characters can be used as placeholders for an array of params that will be safely escaped before sending the final query.
This method returns a Query object which can be used to stream incoming row data.
Always favor option 2, since they are SQL injection proof. Option 1 will get your site hacked within 5 minutes, while hackers are going to have a hard time breaking option 2.
Even in performance option 2 may be a little bit faster.
However: Table names cannot be escaped with the
?so don’t go there. Just make sure that users can’t enter the table name manually and you’ll be safe from hackers.-edit-
Why would you want to make table names variable anyway?