Sunday, June 24, 2012

Simple Pagination Using Php with CSS

Today I have accomplished here, Pagination Tutorial, using PHP with CSS. This is by far the simplest Tutorial for pagination you will find on internet. Simple Php code is used to mathematically divide total messages fetched from MySql table, into pages. Take a look at this Tutorial.


Download the Script


Create Database

CREATE TABLE messages
msg_id INT PRIMARY KEY AUTO_INCREMENT,
message VARCHAR(200),like INT);

Adding Data to the Database

Simply add the data to your database, enter atleast 6 rows, with msg_id (1 to 6) .


  db.php  

In db.php you must change the SERVER_NAME, USERNAME, PASSWORD and DATABASE to your own MySql settings.

<?php

define('DB_SERVER', 'SERVER_NAME');
define('DB_USERNAME', 'USERNAME');
define('DB_PASSWORD', 'PASSWORD');
define('DB_DATABASE', 'DATABASE');
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
$database = mysql_select_db(DB_DATABASE) or die(mysql_error());

?>


  pagination.php  


<?php
include ("db.php");
$result=mysql_query("select count(*) from messages");
$row=mysql_fetch_row($result);
$tr=$row[0];
$rpp=5;  
//rpp is rows per page,declare it as per your requirement
$pn=1;
//pn is page number,setting default as 1
if(isset($_GET['pn']))
{
  $pn=$_GET['pn'];
}
$tp=($tr/$rpp);
//tp is total pages
if($tr%$rpp>0)
{
$tp++;
}
$from=(($pn-1)*$rpp)+1;
$to=($pn)*($rpp);
$result=mysql_query("select * from messages where msg_id between $from and $to");
while($row=mysql_fetch_row($result))
{
echo "<div class='msg'>$row[1]</div>";

echo "<ul id='pages'>";
for($i=1;$i<=$tp;$i++)
{
echo "<li><a href='pagination.php?pn=$i'>$i</a></li>";
}
echo "</ul>";
?>




11 comments :

  1. Thanks a lot for this code. I really use this code into my site.

    ReplyDelete
  2. You should rewrite this to use limit instead of "between" on id's. In theory it should work fine, it just seems clunky. :)

    ReplyDelete
  3. dudeee you rock..thank u so much for this. cant thank u enough.. i saw all the codes elswhere but urs is the simplest and best indeed. thank u. god bless u

    ReplyDelete
    Replies
    1. Thanks a lot for appreciating my work. Keep visiting for more great scripts.

      Delete
  4. Hello, how to do this using LIMIT in the query?

    ReplyDelete
  5. Omg... $tp, $rpp... and of course, all with the comments. Next time try use this: $totalPages, $rowsPerPage... Then you dont need useless comments and code is understandable at first sight :-).

    ReplyDelete
  6. hmm does seem to work with the new PHP and MySQLi

    ReplyDelete