简体   繁体   中英

How to fetch data in mysql with next and previous

I have a database which has more than 5,000 records, I would like to fetch 50 rows and then fetch the next 50 when user clicks next and the opposite when user click previous.

Table name: events

my trial was to

select * from events where entred_by = '$id' limit $limit, 50

but the problem is I am failing to calculate the next rows and previous rows.

edit

        $start = '0';
        $PAGE_P = $_GET['p'];
        $PAGE_N = $_GET['n'];
        if(!numeric($PAGE_N)){ 
            $PAGE_N = 50;
            $PAGE_P = 0;
            $start = '0';
        }else{
            if(isset($_GET['n'])){
                $PAGE_N = $PAGE_N + 50;
                $PAGE_P = $PAGE_N - 50;
                $start = $PAGE_N;
            }else{
                $PAGE_N = $PAGE_P + 50;
                $PAGE_P = $PAGE_N - 50; 
                $start = $PAGE_P;               
            }
        }
        $this->query = SQL::get("
            SELECT * FROM event 
            INNER JOIN user
            ON user.user_id = event.entered_by
            ORDER BY event_id ASC LIMIT $start,50
        ");

I have made an edit, with the edit I am able to use next button, which works, but when I press previous it is going back to row 1.

SELECT * FROM events WHERE entred_by = '$id' ORDER BY id LIMIT $start, $limit

Set the $start value (row number to start on) and $limit (50).

You need to use the LIMIT keyword and probably ORDER BY too.

Update for edit:

Okay, ignoring the validation, it should be something like this:

$this->query = SQL::get("
            SELECT * FROM event 
            INNER JOIN user
            ON user.user_id = event.entered_by
            ORDER BY event_id ASC 
            LIMIT $start_row, $number_of_rows
        ");

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