here's how you can do it:
1// pages/api/products.js
2import mysql from 'mysql2/promise';
3
4const pool = mysql.createPool({ /* connection from env */ });
5
6export default async function handler(req, res) {
7 const page = parseInt(req.query.page || '1', 10);
8 const limit = parseInt(req.query.limit || '10', 10);
9 const offset = (page - 1) * limit;
10
11 const [rows] = await pool.execute(
12 'SELECT * FROM products LIMIT ? OFFSET ?',
13 [limit, offset]
14 );
15 res.status(200).json({ page, limit, data: rows });
16}
17
1// pages/api/products.js
2import mysql from 'mysql2/promise';
3
4const pool = mysql.createPool({ /* connection from env */ });
5
6export default async function handler(req, res) {
7 const page = parseInt(req.query.page || '1', 10);
8 const limit = parseInt(req.query.limit || '10', 10);
9 const offset = (page - 1) * limit;
10
11 const [rows] = await pool.execute(
12 'SELECT * FROM products LIMIT ? OFFSET ?',
13 [limit, offset]
14 );
15 res.status(200).json({ page, limit, data: rows });
16}
17
- Client calls
/api/products?page=2&limit=20. LIMIT ? OFFSET ?slices the results.