MySQL swap results using PHP

How would you divide the MySQL results into "next" and "previous" if the output was very long?

$data = mysql_query("SELECT * FROM table WHERE ... AND ...") or die(mysql_error()); while($info = mysql_fetch_array( $data )) { echo $info['value']; } 

Where will the values ​​be listed from 1 to 10, and then move on to the next? The first page can be done using LIMIT 10 , but how will I do the following?

+4
source share
2 answers
 SELECT * FROM table WHERE ... AND ... LIMIT 10 OFFSET 10 

I prefer to have the word OFFSET just because it is a little readable.

Also remember that the offset is based on 0 (the offset of the first returned string is 0, not 1). Thus, LIMIT 10 OFFSET 10 will return lines 10 through 19.

+5
source

You can specify the offset in the LIMIT clause:

 LIMIT 0, 10 LIMIT 10, 10 LIMIT 20, 10 ... 

Therefore, when creating a LIMIT clause, your code should look like this:

 $offset = ($current_page - 1) * $items_per_page; $sql = "[...] LIMIT $offset, $items_per_page"; 

Of course, you need to make sure $current_page - >= 1 . But this is easy to do:

 $current_page = empty($_GET['current_page']) ? 1 : max(1, (int)$_GET['current_page']); 
+4
source

Source: https://habr.com/ru/post/1336873/


All Articles