通过准备好的Query语句进行nodejs mysql分页返回forEach属性未定义的错误

时间:2018-08-30 12:59:44

标签: mysql node.js

以下用于从数据库中检索内容的nodejs代码可以正常工作。现在,当我尝试通过预准备的查询语句按照以下代码通过分页获取内容

   db.query('SELECT * FROM posts1 limit row=?, rowperpage=?', [parseInt(row),parseInt(rowperpage)], function (error, results, fields) {

});

返回错误“ 无法读取每个未定义的属性

下面是完整的代码

exports.display = function (req, res) {
var row = 0;
var rowperpage = 3;

console.log(row);
console.log(rowperpage);


var objs1 = []; 
    db.query('SELECT * FROM posts1 limit row=?, rowperpage=?', [parseInt(row),parseInt(rowperpage)], function (error, results, fields) {

   // db.query('SELECT * FROM posts1', function (error, results, fields) {

  results.forEach(function(row) {

             var id = row.id;
            var title = row.title;
            var content = row.content;
var shortcontent = row.content;
var link = row.link;


objs1.push({
id: id, 
title: title,
shortcontent: shortcontent,
content: content,
link: link,

});

});
res.end(JSON.stringify(objs1));

});



}

1 个答案:

答案 0 :(得分:0)

在下面添加以下代码,即可解决问题

//parse int Convert String to number 
      let startNum = parseInt(row);
      let LimitNum = parseInt(rowperpage);


var objs1 = []; 
 db.query("SELECT * FROM ?? limit ? offset ?", ["posts1",LimitNum,startNum], function (error, results, fields) {

谢谢