我有两个数组如下
var fieldarray = [ 'category',
'bookid',
'bookauthor',
'booktitle',
'price',
'publication',
'publication_date' ]
var dataarray = [ 'fantasy',
'',
'JKR',
'',
'',
'',
'' ]
每次
我必须在mysql语句中使用这些数组。我期望mysql查询如下
select category,bookid,bookauthor,booktitle,price,publication,publication_date from tbl_books where category like '%fantasy%' OR bookauthor like '%JKR%'
如何根据nodejs中的fiedarray和dataarray元素动态创建mysql语句
答案 0 :(得分:0)
var filters = [];
dataarray.forEach((val, index) => {
if(val)
filters.push(`${fieldarray[index]} like '%${val}%'`);
});
var result = `select ${fieldarray.join(",")} from tbl_books where ${filters.join(" OR ")} `;
只需迭代数据阵列,检查字段是否为空,并将其连接到生成的查询。始终保证您不受SQL注入的影响!
答案 1 :(得分:0)
首先使用reduce
准备地图,首先将字段与数据相关联var map = fieldarray.reduce( ( a, c, i ) => ( dataarray[i] && (a[c] = dataarray[i]), a ) , {}) ;
现在使用join
和map
var query = "SELECT " + fieldarray.join(" , ") + "from tbl_books where " + Object.keys(map).map(f => (f + " like '%" + map[f] + "%'")).join(" AND ");
<强>演示强>
var fieldarray = ['category',
'bookid',
'bookauthor',
'booktitle',
'price',
'publication',
'publication_date'
]
var dataarray = ['fantasy',
'',
'JKR',
'',
'',
'',
''
];
var map = fieldarray.reduce((a, c, i) => (dataarray[i] && (a[c] = dataarray[i]), a), {});
var query = "SELECT " + fieldarray.join(" , ") + "from tbl_books where " + Object.keys(map).map(f => (f + " like '%" + map[f] + "%'")).join(" AND ");
console.log(query);
为了避免sql-injection将值作为params传递,而不是使用mysqljs
在查询中对它们进行硬编码var query = "SELECT " + fieldarray.join(" , ") + "from tbl_books where " + Object.keys(map).map(f => (f + " like ?")).join(" AND ");
connection.query( query, Object.values(map), function (error, results, fields) {
if (error) throw error;
// ...
});