I have a question about mysql.format.
I am trying to put my string variable into mysql.format depending on the condition in the if statement with Javascript.
For example.
var query = mysql.format(`SELECT * FROM employees WHERE ?
, [isAlwaystrue ? 1 : 'emp_no = 1']
But with this approach, the query does not work well.
To find out the problem, look up the query for mysql.format as shown below.
SELECT * FROM employees WHRERE 'emp_no = 1';
It looks like emp_no = 1 is surrounded by a single dot.
I'll ask for help. please
If you are using string literals you could change your statement to this
var query = mysql.format(`SELECT * FROM employees WHERE ?
, ${isAlwaystrue ? 1 : 'emp_no = 1'}
You could keep the logic easy to understand and do it the long way:
var query;
if (isAlwaystrue) {
query = mysql.format(`SELECT * FROM employees`);
} else {
query = mysql.format(`SELECT * FROM employees WHERE emp_no = 1`);
}
Or you can try the shorter way, but make the code more confusing:
mysql.format(`SELECT * FROM employees WHERE ${isAlwaystrue ? 1 : 'emp_no = 1'}`);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.