Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How MySQL query works with and without placeholders (?)?

Tags:

node.js

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 ??

First Approach

var userId = 1;
var columns = ['username', 'email'];    
var query = connection.query('SELECT ?? FROM ?? WHERE id = ?', 
  [columns, 'users', userId], function(err, results) 
{   
  // ... 
});

Second Approach

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.

like image 246
mukund shelke Avatar asked Jan 12 '17 13:01

mukund shelke


People also ask

What is the advantage of using a placeholder in a SQL statement?

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.

What is placeholder in MySQL?

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.

What is placeholder SQL query?

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.

What is %s in MySQL?

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.


1 Answers

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'
like image 144
O. Jones Avatar answered Oct 23 '22 20:10

O. Jones