|
Following examples teaches how to query a mySQL database and getting results in pages. Every page displays results maximum 10 results in a single page. <head> <title>Paging Results in PHP</title> </head><body> <?php mysql_connect("localhost","username","password"); //(mysql server, username, password) mysql_select_db("mynews") or die("Can not find database"); //type here your database, mynews etc ... if (empty($page)) { $s=0; } else { $s = $page; } // SQL Query with limiting results // 10 results will be displayed in each page $limitQuery = 10; $query = "select newsID, title, summary from newsTable LIMIT $s, $limitQuery" ; $numresults=mysql_query($query); $numrows=mysql_num_rows($numresults); if ($numrows == 0) { echo "<h4>There is no any news found .... </h4>"; } $result = mysql_query($query) or die("SQL Query failed ..."); $count = 1 + $s ; while ($row= mysql_fetch_array($result)) { $title = $row["title"]; $newsID = $row["newsID"]; echo "<h1><a href=\"read.php?id=$newsID\">"$title</a></h1>" ; echo "<br>$summary</br>" ; $count++ ; } $currPage = (($s/$limitQuery) + 1); echo "<br />"; if ($s>=1) { $prevs=($s-$limit); print " <a href=\"$PHP_SELF?page=$prevs\"><< Prev 10</a>  "; } $pages=intval($numrows/$limit); if ($numrows%$limit) { $pages++; } if (!((($s+$limit)/$limit)==$pages) && $pages!=1) { $news=$s+$limit; echo " <a href=\"$PHP_SELF?page=$news\">Next 10 >></a>"; } $a = $s + ($limit) ; if ($a > $numrows) { $a = $numrows ; } $b = $s + 1 ; echo "<p>Pages $b to $a of $numrows</p>"; ?> </body> </html> |