嗨我在nodejs上有一些问题需要在mysql上获取数据
我的问题是'如何将var n添加到“%drawing eye%”中以获取数据库中的数据?'
function showResult(req, res){
var n = req.query.query
mysql_conn.query('SELECT query_text FROM catalogsearch_query WHERE query_text LIKE "%drawing eye%" ORDER BY popularity DESC LIMIT 0 , 10', function(error, rows){
res.render('result.html',{result:n , related: rows.map(row => row.query_text)})
})
}
答案 0 :(得分:0)
做这样的事情LIKE "%' + n + '%" ORDER BY
function showResult(req, res) {
var n = req.query.query
mysql_conn.query('SELECT query_text FROM catalogsearch_query WHERE query_text LIKE "%' + n + '%" ORDER BY popularity DESC LIMIT 0 , 10', function(error, rows) {
res.render('result.html', {
result: n,
related: rows.map(row => row.query_text)
})
})
}
答案 1 :(得分:0)
mysql
模块支持queries with placeholders,其中这些占位符被您传递的变量替换(正确转义,以防止SQL注入):
function showResult(req, res) {
var n = req.query.query;
mysql_conn.query(`
SELECT query_text
FROM catalogsearch_query
WHERE query_text LIKE ?
ORDER BY popularity DESC
LIMIT 0, 10`,
'%' + n + '%',
function(error, rows) {
if (err) return res.sendStatus(500);
res.render('result.html',{result:n , related: rows.map(row => row.query_text)})
}
)
}
?
之后的LIKE
是占位符,将被'%' + n + '%'
的转义版本替换。