Tuesday, 13 March 2012

Simple pagination with Php and MySql

$max = 2; //amount of records per page. change to what to want

$p = $_GET['p'];

if(empty($p))

{

$p = 1;

}

$limits = ($p - 1) * $max;

//view the news article!

//view all the pagess in rows

$sql = mysql_query("SELECT * FROM table LIMIT ".$limits.",$max") or die(mysql_error());

//the total rows in the table

$totalres = mysql_result(mysql_query("SELECT COUNT(id) AS tot FROM table"),0);   

//the total number of pages (calculated result), math stuff...

$totalpages = ceil($totalres / $max);

//the table

echo "<table><tr><td>Title</td><td>Author</td></tr>";

while($r = mysql_fetch_array($sql))

{

    $title = $r['title'];

   $author = $r['author'];

   echo "<tr><td>$title</td><td>$author</td></tr>";

}

//close up the table

echo "</table>";

for($i = 1; $i <= $totalpages; $i++)
{

//this is the pagination link

echo "<a href='news.php?p=$i'>$i</a>|";

}