一聚教程网:一个值得你收藏的教程网站

热门教程

nodejs mysql如何实现分页

时间:2022-06-29 01:30:49 编辑:袖梨 来源:一聚教程网

这两天学习了nodejs mysql 实现分页,很重要,所以,今天添加一点小笔记。

代码如下

 

 代码如下复制代码

varexpress = require('express');

varrouter = express.Router();

varsettings = require('../settings.js');

varmysql = require('mysql2');

 

router.get('/',function(req, res, next) {

  varcurrent_page = 1;//默认为1

  varnum = 9;//一页条数

  if(req.query.page) {

    current_page = parseInt(req.query.page);

  }

 

  varlast_page = current_page - 1;

  if(current_page <= 1) {

    last_page = 1;

  }

  varnext_page = current_page + 1;

  varstr ='SELECT left(paragraph,50) as paragraph,date,id FROM notice limit '+ num +' offset '+ num * (current_page - 1);

  varconn = mysql.createConnection(settings.db);

 

  conn.connect();

  conn.query(str,function(err, rows, fields) {

    if(err) {

      req.flash('error','数据查询有误');

    }

    if(!err) {

      if(!rows[0]) {

        req.flash('error','已到最后一页,请返回');

      }

      res.render('notice', {

        last_page: last_page,

        next_page: next_page,

        current_page: current_page,

        mes: rows,

        error: req.flash('error').toString()

      });

 

    }

  });

  conn.end();

});

 

module.exports = router;

 

热门栏目