Here is the simple pagination code which combine
PHP
and
MYSQL
.
To make this example you will need:
- PHP basic knowledge
- MYSQL basic knowledge
I will pass the connect database in this example. So remember to write your connect database code before do this pagination example.
<?php $post_per_page = 10;// Number of posts per page // set default page when load is zero (0) if ( !$_GET['page'] ) { $page = 0 ; } // Get data from database, return how many posts in data $post_number = mysql_num_rows(mysql_query("SELECT * FROM `data` ") ) or die(mysql_error()); //Count page number. We divide the total post in database with the number of post per page /* For example, 20 post in database. each page show 10 post => So the page number will be 20/10 = 2 pages */ $number_page = $post_number/$post_per_page; // Get data // We use the LIMIT query in MYSQL // For instance we will get 10 post, from number 20 the query will be LIMIT 20,10 $result =mysql_query("SELECT * FROM `data`ORDER BY `id` DESC LIMIT {$page}*{$post_number},{$post_number} ") or die(mysql_error()); /* Why {$page}*{$post_number} ? Because we are in page 0. so the data will get from post number 0 if we're in page 1 so the data will get post from number 10 */ // Show on browser while ( $info = mysql_fetch_array($result )) { echo <<<EOT $info['title'] <br /> $info['content'] EOT; } //Here is the code for display page number so we can click in it. for ( $page = 0; $page <= $number_page; $page ++ ) { echo "<a href='index.php?page={$page}'>{$page}</a>"; }