Pagination in nodejs with mysql

后端 未结 4 855
鱼传尺愫
鱼传尺愫 2021-02-08 10:48

In my project I need to query the db with pagination and provide user the functionality to query based on current search result. Something like limit, I am not able to find anyt

4条回答
  •  梦谈多话
    2021-02-08 11:51

    I taked the solution of @Benito and I tried to make it more clear

    var numPerPage = 20;
    var skip = (page-1) * numPerPage; 
    var limit = skip + ',' + numPerPage; // Here we compute the LIMIT parameter for MySQL query
    sql.query('SELECT count(*) as numRows FROM users',function (err, rows, fields) {
        if(err) {
            console.log("error: ", err);
            result(err, null);
        }else{
            var numRows = rows[0].numRows;
            var numPages = Math.ceil(numRows / numPerPage);
            sql.query('SELECT * FROM users LIMIT ' + limit,function (err, rows, fields) {
                if(err) {
                    console.log("error: ", err);
                    result(err, null);
                }else{
                    console.log(rows)
                    result(null, rows,numPages);
                }
            });            
        }
    });
    

提交回复
热议问题