简体   繁体   中英

how to get a specific id within 5 rows in a paging query in Mysql

I have a function in php I use it for paging it is like this :

$query = "SELECT id, 
      FROM table
      ORDER BY id ASC
      LIMIT $offset,5";

this work fine but what I want is to get the page that contain id number let say 10 and with it the other 4 rows, I want it to return something like this:

  • 7,8,9,10,11,12 -> if I give it id number 10.
  • 25,26,27,28,29 -> if I give it id number 26 and so on.

like it would return the 5 rows but I want to know how to set the offset that will get me the page that have the 5 rows with the specified id included.

what should I do like adding where clause or something to get what I want!

Try something like this

//but for pagination to work $page should be $page*$limit, so new rows will come to your page

$limit = 5;
$start = ($page*limit) -2;  // for normal pagination
$start = $page -2; // for your case, if you want ids around the $page value - in this case for id = 10 you will get 8 9 10 11 12
if ($start < 0) $start = 0; // for first page not to try and get negative values

$query = "SELECT id, 
          FROM rowa
          ORDER BY id ASC
          LIMIT $start,$limit";

Notice that the IDs in your table won't be consecutive if you delete some rows. The code below should work in such conditions:

$result = mysql_query('select count(*) from table where id < ' . $someId);
$offset = mysql_result($result, 0, 0);

$result = mysql_query('select * from table order by id limit ' . max($offset - 2, 0) . ',5');
while ($row = mysql_fetch_assoc($result)) {
    print_r($row);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM