I have two approaches to execute sql query in node.js
, I want to know difference between these two. Which one is recommended to use ?
and why ??
var userId = 1;
var columns = ['username', 'email'];
var query = connection.query('SELECT ?? FROM ?? WHERE id = ?',
[columns, 'users', userId], function(err, results)
{
// ...
});
var userId = 1;
var query = connection.query('SELECT username,email FROM UserTable WHERE id=?',
[userId], function(err, results)
{
// ...
});
Please tell me exact use of these two mechanisms.
One of the benefits of prepared statements and placeholders is that parameter binding operations automatically handle escaping of characters such as quotes and backslashes that you have to worry about yourself if you put the data values into the query yourself.
Placeholders can be understood as predefined “search and replace” templates that will be replaced with some actual values at execution time. They are usually used for MySQL queries.
A placeholder expression provides a location in a SQL statement for which a third-generation language bind variable will provide a value. You can specify the placeholder expression with an optional indicator variable.
12 years, 11 months ago. it's for php to know how to handle the parameters, %d – the argument is treated as an integer, and presented as a (signed) decimal number. %s – the argument is treated as and presented as a string. in your examples, $slug is a string and $this->id is an integer.
The double question mark syntax ??
in the substitution string wraps the substituted parameters in delimiters before sending them to the server. The delimiters are appropriate for table and column names. So your first example, 'SELECT ?? FROM ?? WHERE id = ?'
sends
SELECT `username`, `email` FROM `users` WHERE id = '1'
to the server.
The second one, 'SELECT username,email FROM UserTable WHERE id=?'
, sends
SELECT username,email FROM UserTable WHERE id='1'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With