I am unable to do pagination. The code display all the data retrieve from the mysql. Please help me to get it right.....
function.php
function pagination($limit=5) //here limit is not taken by the code
{
//$limit=5; if I uncomment this line limit will work
global $admin;
$sql = "SELECT FOUND_ROWS();";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result);
$numrows = $row[0];
$pagelinks = "<div class=pagelinks>";
if ($numrows > $limit) {
if(isset($_GET['page'])){
$page = $_GET['page'];
} else {
$page = 1;
}
$currpage = $_SERVER['PHP_SELF'] . "?" . $_SERVER['QUERY_STRING'];
$currpage = str_replace("&page=".$page,"",$currpage);
if($page == 1){
$pagelinks .= "<span class='pageprevdead'>< PREV</span>";
}else{
$pageprev = $page - 1;
$pagelinks .= "<a class='pageprevlink' href='" . $currpage .
"&page=" . $pageprev . "'>< PREV</a>";
}
$numofpages = ceil($numrows / $limit);
$range = $admin['pageRange']['value'];
if ($range == "" or $range == 0) $range = 7;
$lrange = max(1,$page-(($range-1)/2));
$rrange = min($numofpages,$page+(($range-1)/2));
if (($rrange - $lrange) < ($range - 1)) {
if ($lrange == 1) {
$rrange = min($lrange + ($range-1), $numofpages);
} else {
$lrange = max($rrange - ($range-1), 0);
}
}
if ($lrange > 1) {
$pagelinks .= "..";
} else {
$pagelinks .= " ";
}
for($i = 1; $i <= $numofpages; $i++){
if($i == $page){
$pagelinks .= "<span class='pagenumdead'>$i</span>";
}else{
if ($lrange <= $i and $i <= $rrange) {
$pagelinks .= "<a class='pagenumlink' href='" . $currpage .
"&page=" . $i . "'>" . $i . "</a>";
}
}
}
if ($rrange < $numofpages) {
$pagelinks .= "..";
} else {
$pagelinks .= " ";
}
if(($numrows - ($limit * $page)) > 0){
$pagenext = $page + 1;
$pagelinks .= "<a class='pagenextlink' href='" . $currpage .
"&page=" . $pagenext . "'>NEXT ></a>";
} else {
$pagelinks .= "<span class='pagenextdead'>NEXT ></span>";
}
} else {
$pagelinks .= "<span class='pageprevdead'>
< PREV</span> ";
$pagelinks .= "<span class='pagenextdead'>
NEXT ></span> ";
}
$pagelinks .= "</div>";
return $pagelinks;
}'
index.php
$sql = "SELECT id FROM articles WHERE is_published=1 " .
"ORDER BY date_published DESC"; //this is the query to retrive data from mysql
$result = mysql_query($sql,$conn);
if (mysql_num_rows($result) == 0) {
echo " <br />\n";
echo " There are currently no articles to view.\n";
} else {
while ($row = mysql_fetch_array($result)) {
outputStory($row['article_id'],TRUE);
}
}
echo pagination($limit);`
This code is incomplete. However the first thing you need to do is add the $limit to the actual sql query:
$sql = "SELECT id FROM articles WHERE is_published=1 " .
"ORDER BY date_published DESC LIMIT {$limit}";
Try this.
Just create a mysql table called players with 3 fields:- id, firstname, lastname to check how the code is working.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View Records</title>
</head>
<body>
<?php
/*
VIEW-PAGINATED.PHP
Displays all data from 'players' table
This is a modified version of view.php that includes pagination
*/
// connect to the database
include('dbconfig.php');
// number of results to show per page
$per_page = 2;
// figure out the total pages in the database
$result = mysql_query("SELECT * FROM players");
$total_results = mysql_num_rows($result);
$total_pages = ceil($total_results / $per_page);
// check if the 'page' variable is set in the URL (ex: view-paginated.php?page=1)
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$show_page = $_GET['page'];
// make sure the $show_page value is valid
if ($show_page > 0 && $show_page <= $total_pages)
{
$start = ($show_page -1) * $per_page;
$end = $start + $per_page;
}
else
{
// error - show first set of results
$start = 0;
$end = $per_page;
}
}
else
{
// if page isn't set, show first set of results
$start = 0;
$end = $per_page;
}
// display pagination
echo "<p><a href='view.php'>View All</a> | <b>View Page:</b> ";
for ($i = 1; $i <= $total_pages; $i++)
{
echo "<a href='view-paginated.php?page=$i'>$i</a> ";
}
echo "</p>";
// display data in table
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th></th> <th></th></tr>";
// loop through results of database query, displaying them in the table
for ($i = $start; $i < $end; $i++)
{
// make sure that PHP doesn't try to show results that don't exist
if ($i == $total_results) { break; }
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . mysql_result($result, $i, 'id') . '</td>';
echo '<td>' . mysql_result($result, $i, 'firstname') . '</td>';
echo '<td>' . mysql_result($result, $i, 'lastname') . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
// pagination
?>
<p>Add a new record</p>
</body>
</html>
Related
Here is my script which I got from the internet,
<?php
// connect to the database
include('connect-db.php');
// number of results to show per page
$per_page = 5;
// figure out the total pages in the database
if ($result = $mysqli->query("SELECT * FROM players ORDER BY id"))
{
if ($result->num_rows != 0)
{
$total_results = $result->num_rows;
// ceil() returns the next highest integer value by rounding up value if necessary
$total_pages = ceil($total_results / $per_page);
// check if the 'page' variable is set in the URL (ex: view-paginated.php?page=1)
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$show_page = $_GET['page'];
// make sure the $show_page value is valid
if ($show_page > 0 && $show_page <= $total_pages)
{
$start = ($show_page -1) * $per_page;
$end = $start + $per_page;
}
else
{
// error - show first set of results
$start = 0;
$end = $per_page;
}
}
else
{
// if page isn't set, show first set of results
$start = 0;
$end = $per_page;
}
// display pagination
echo "<p><a href='view.php'>View All</a> | <b>View Page:</b> ";
for ($i = 1; $i <= $total_pages; $i++)
{
if (isset($_GET['page']) && $_GET['page'] == $i)
{
echo $i . " ";
}
else
{
echo "<a href='view-paginated.php?page=$i'>$i</a> ";
}
}
echo "</p>";
// display data in table
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th></th> <th></th></tr>";
// loop through results of database query, displaying them in the table
for ($i = $start; $i < $end; $i++)
{
// make sure that PHP doesn't try to show results that don't exist
if ($i == $total_results) { break; }
// find specific row
$result->data_seek($i);
$row = $result->fetch_row();
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row[0] . '</td>';
echo '<td>' . $row[1] . '</td>';
echo '<td>' . $row[2] . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
}
else
{
echo "No results to display!";
}
}
// error with the query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
?>
This program views the 1st page but I want to set the default view into last page after inserted the last row data into the table "players". I got one something like reverse pagination but I don't know how to set it. I'm not good at php. please help!
I have the code below and am trying to get the next 25 results from my sql table to appear on page. However, whenever I click the next button, no information is displayed. I have my offset = ($page - 1) * $items_per_page......I'm struggling to figure this out as it seems so simple compared the other code I've written, but is proving to be very elusive to me....any assistance would be greatly appreciated. My primary issue is that the next link does not provide the next 25 results and I'm unable to determine why and how to correct.
echo "<h3 style='text-align:center;'>Welcome to the Exchange Portal, " . $row['name'] . "! </h3>";
$items_per_page = 25;
$sql_count = "SELECT pin, title, title2, email, phone FROM crown_acura";
$result_cnt = mysqli_query($conn, $sql_count);
if(false === $result_cnt) {
throw new Exception('Query failed with: ' . mysqli_error());
} else {
$row_count = mysqli_num_rows($result_cnt);
// free the result set as you don't need it anymore
//mysqli_free_result($result_cnt);
}
echo $row_count;
echo " ";
if (!isset($_GET['Page'])) {
$Page = 1;
} else {
$Page = $_GET['Page'];
}
echo $page;
echo " ";
$page_count = 0;
if (0 === $row_count) {
// maybe show some error since there is nothing in your table
} else {
// determine page_count
$page_count = (int)ceil($row_count / $items_per_page);
// double check that request page is in range
if($page > $page_count) {
// error to user, maybe set page to 1
$page = 1;
}
}
echo " ";
echo $page_count;
echo " ";
echo $items_per_page;
$offset = ($page-1)*$items_per_page;
//echo $paging_info;
//echo " ";
echo "<br />";
//Query for displaying results
$list_sql = "SELECT pin, title, title2, email, phone FROM crown_acura LIMIT $offset, $items_per_page";
$result_query = $conn->query($list_sql);
//Table for displaying query results
echo "<table class='verify'>";
echo "<tr >";
echo "<td><h3>Name</h3></td><td> </td><td><h3>E-mail</h3></td><td><h3>Phone</h3></td>";
echo "</tr>";
for($i = 1; $i<= $page_count; $i++) {
if ($result_query->num_rows > 0) {
// output data of each row
while($row3 = mysqli_fetch_array($result_query)) {
echo "<tr>";
echo "<td class='dltd2 dlcl'>" . $row3["title"] . "</td><td>" . $row3["title2"] . "</td><td><a href='mailto:" . $row3['email'] . "'>" . $row3["email"] . "</a> </td><td>" . $row3["phone"] . " </td>";
echo "</tr>";
}
} else {
echo "0 results";
}
}
echo "<tr></tr>";
$next_page = $page + 1;
$last_page = $page - 1;
if($paging_info['curr_page'] <= 1) {
echo "<tr>";
echo "<td></td><td colspan='2'><a class='loadlink' href='" . $_PHP_SELF . "'>Next 25</a></td><td></td>";
echo "</tr>";
} elseif ($paging_info['curr_page'] < $page_count) {
echo "<tr>";
echo "<td></td><td><a href='" . $_PHP_SELF . "?page=" . $last_page . "'>Prev 25</a></td><td><a href='" . $_PHP_SELF . "?page=" . $next_page . "'>Next 25</a></td><td></td>";
echo "</tr>";
} elseif ($paging_info['curr_page'] === $page_count) {
echo "<tr>";
echo "<td></td><td colspan='2'><a href='" . $_PHP_SELF . "?page=" . $last_page . "'>Prev 25</a></td><td></td>";
echo "</tr>";
}
echo "</table>";
}
}
}
Have you tried to run the rendered SQL.
Output to browser:
"SELECT pin, title, title2, email, phone FROM crown_acura LIMIT $offset, $items_per_page"
try this... and change $page for different values (2,3,...,etc)
<?php
$items_per_page = 25;
$sql_count = "SELECT pin, title, title2, email, phone FROM crown_acura";
$result_cnt = mysqli_query($conn, $sql_count);
if (false === $result_cnt) {
throw new Exception('Query failed with: ' . mysqli_error());
} else {
$row_count = mysqli_num_rows($result_cnt);
// free the result set as you don't need it anymore
//mysqli_free_result($result_cnt);
}
echo $row_count;
echo " ";
if (!isset($_GET['Page'])) {
$Page = 1;
} else {
$Page = $_GET['Page'];
}
echo $page;
echo " ";
$page_count = 0;
if (0 === $row_count) {
// maybe show some error since there is nothing in your table
} else {
// determine page_count
$page_count = (int)ceil($row_count / $items_per_page);
// double check that request page is in range
if ($page > $page_count) {
// error to user, maybe set page to 1
$page = 1;
}
}
echo " ";
echo $page_count;
echo " ";
echo $items_per_page;
$offset = ($page - 1) * $items_per_page;
//echo $paging_info;
//echo " ";
echo "<br />";
//Query for displaying results
$list_sql = "SELECT pin, title, title2, email, phone FROM crown_acura LIMIT $offset, $items_per_page";
$result_query = $conn->query($list_sql);
echo ("RESULTS: ".$result_query->num_rows());
?>
my default load page is ok with next and prev results.. but for search results i can get only first page then blank for the next page. let say total search results row is 9, it display 3 pages with next link. but when i click the next link, it queries no result on the page 2. here is my code:
echo '<table><tr><td>';
echo '<form method="post" name="frmSearch" action="mypage.php>
Search by name
<input type="text" name="txtSearch">
<input type="submit" name="submit" value="Search">
</form>';
$per_page = 5;
$page = 1;
if (isset($_GET['page']))
{
$page = intval($_GET['page']);
if($page < 1) $page = 1;
}
$start_from = ($page - 1) * $per_page;
$Prev_Page = $page - 1;
$Next_Page = $page + 1;
if (!$_POST){
//$sql = "SELECT * FROM mytable LIMIT $start_from, $per_page";
//$totalr = mysql_query("SELECT COUNT(*) FROM mytable");
//$totalr = mysql_fetch_row($totalr);
//$totalr = $totalr[0];
//$total_pages = $totalr / $per_page;
//$total_pages = ceil($total_pages);
//$listresult = mysql_query($sql);
//$total = mysql_num_rows($listresult);
}
else {
if ($_POST['txtSearch']!="") {$cond1 = " name LIKE
'%".$_POST['txtSearch']."%' ";} else {$cond1 = 1; }
$sql = "SELECT * FROM mytable WHERE ".$cond1." LIMIT $start_from, $per_page";
$totalr = mysql_query("SELECT COUNT(*) FROM mytable WHERE name LIKE
'%".$_POST['txtSearch']."%' ");
$totalr = mysql_fetch_row($totalr);
$totalr = $totalr[0];
$total_pages = $totalr / $per_page;
$total_pages = ceil($total_pages);
$listresult = mysql_query($sql);
$total = mysql_num_rows($listresult);
}
if($total == 0){
echo "<center>No records found.</center>";
}
echo "<span style='float:right;margin-top:8px;'>[ <a href='new.php'>Add New</a>
]</span></td></tr>";
echo "<table>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
";
while ($_POST = mysql_fetch_assoc($listresult)){
echo "<tr>";
echo "<td>" . $_POST['id'] . "</td>";
echo "<td>" . $_POST['name'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo "</table>";
echo $totalr." result";
echo "<br>";
if ($Prev_Page) {
echo " <a href ='{$_SERVER['PHP_SELF']}?page=$Prev_Page'><< Prev</a> ";
}
if ($totalr > $per_page) {
for($i = 1; $i <= $total_pages; ++$i)
{
echo "<a href='{$_SERVER['PHP_SELF']}?page=$i'>$i</a> | ";
}
}
if ($page!=$total_pages) {
echo " <a href='{$_SERVER['PHP_SELF']}?page=$Next_Page'>Next >></a> ";
}
maybe you need to use SELECT COUNT(*) FROM mytable WHERE name LIKE '%$search%' ... remember to escape the $_POST['txtSearch']
The following script is showing only first page and link to next page is there but is not leading anywhere. Can someone help me?
$var = #$_GET['q'] ;
$trimmed = trim($var);
$limit = 10;
if ($trimmed == "")
{
echo "<p>What are you looking for?...</p>";
exit;
}
if (!isset($var))
{
echo "<p>We dont seem to have a search parameter!</p>";
exit;
}
mysql_connect('xxx', 'yyy', 'zzz');
mysql_select_db('yyy') or die('Unable to select database');
$query = "select * from table where NAME like '%$trimmed%' order by NAME";
$numresults = mysql_query($query);
$numrows = mysql_num_rows($numresults);
if ($numrows == 0)
{
echo "<h4>Results</h4>";
echo "<p>Sorry, your search: "" . $trimmed . "" returned zero results</p>";
echo "<p><a href=\"http://www.google.com/search?q="
. $trimmed . "\" target=\"_blank\" title=\"Look up
" . $trimmed . " on Google\">Click here</a> to try the search on google</p>";
}
if (empty($s))
{
$s = 0;
}
$query .= " limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
echo "<p>You searched for: "" . $var . ""</p>";
echo "Results";
$count = 1 + $s;
while ($row= mysql_fetch_array($result))
{
$title = $row["NAME"];
echo "$count.- $title" ;
$count++ ;
}
$currPage = (($s/$limit) + 1);
echo "<br />";
if ($s >= 1)
{
// bypass PREV link if s is 0
$prevs = ($s - $limit);
print " <a href=\"$PHP_SELF?s=$prevs&q=$var\"><<
Prev 10</a> ";
}
$pages = intval($numrows/$limit);
if ($numrows % $limit)
{
$pages++;
}
if (!((($s+$limit)/$limit) == $pages) && $pages != 1)
{
$news = $s + $limit;
print "Next 10 >>";
}
$a = $s + ($limit);
if ($a > $numrows)
{
$a = $numrows;
}
$b = $s + 1;
echo "<p>Showing results $b to $a of $numrows</p>";
In your code, $s gets reset every time the page is reloaded or the next page link is clicked. You should have $s = $_REQUEST['s'] at the beginning of your code.
PHP_SELF is a $_SERVER variable. Regardless, you should use $_SERVER['SCRIPT_NAME'] here.
echo "Next 10 >>";
Among a few notable improvements, you should really look into sanitizing the variables you put in the querystring with urlencode() as well.
I'm using this script to pagination. But when url does have $_GET['word'] I cant change URL's of Links. How can I do it?
<?
if (isset($_GET['page']) ) {
$pageno = $_GET['page'];
} else {
$pageno = 1;
} // if
$limit = "";
if(isset($_GET['word'])) {
$word = mysql_real_escape_string($_GET['word']);
$word = $word{0};
$limit = " WHERE baslik LIKE '$word%'";
}
$query = mysql_query("SELECT count(*) FROM m3_music_mp3" .$limit);
$query_data = mysql_fetch_row($query);
$numrows = $query_data[0];
$rows_per_page = 30;
$lastpage = ceil($numrows/$rows_per_page);
$pageno = (int)$pageno;
if ($pageno > $lastpage) {
$pageno = $lastpage;
} // if
if ($pageno < 1) {
$pageno = 1;
} // if
$limit .= " ORDER BY id DESC LIMIT " .($pageno - 1) * $rows_per_page .',' .$rows_per_page;
//$limit = 'ORDER BY id DESC LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;
$query = mysql_query("SELECT * FROM m3_music_mp3 $limit");
if ($pageno == 1) {
echo "<a>««</a> <a>«</a> ";
} else {
echo " <a href='{$_SERVER['PHP_SELF']}?sayfa=1'>««</a> ";
$prevpage = $pageno-1;
echo " <a href='{$_SERVER['PHP_SELF']}?sayfa=$prevpage'>«</a> ";
} // if
for($page_number = 1; $page_number <= $lastpage; $page_number++)
if($page_number == $pageno) {
echo "<span class='current'>$pageno</span>";
}
else {
echo "<a href='{$_SERVER['PHP_SELF']}?sayfa=$page_number' class='page' title='$page_number'>$page_number</a>";
}
if ($pageno == $lastpage) {
echo " <a>»</a> <a>»»</a> ";
} else {
$nextpage = $pageno+1;
echo " <a href='{$_SERVER['PHP_SELF']}?sayfa=$nextpage'>»</a> ";
echo " <a href='{$_SERVER['PHP_SELF']}?sayfa=$lastpage'>»»</a> ";
} // if
?>
I'm trying to do if isset $_GET['word'] set urls <a href='{$_SERVER['PHP_SELF']}?word=$word&page=$lastpage'>»»</a> if NOT <a href='{$_SERVER['PHP_SELF']}?page=$lastpage'>»»</a> i cant let it work thank you if you will help
Try following:
$word_str = "";
if(isset($_GET['word'])) {
$word_str = "&word=".$_GET['word'];
//......
}
And then just append $word_str to urls, for example
echo " <a href='{$_SERVER['PHP_SELF']}?sayfa='.$nextpage.$word_str.'>»</a> ";
You should better use $_SERVER['REQUEST_URI'] to get the current requested URI path and query. You can then use parse_url to get just the URI path and http_build_query to build the query from an array:
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
// …
$href = htmlspecialchars($_SERVER['REQUEST_URI_PATH']."?".http_build_query(array('sayfa'=>1)+$_GET), ENT_QUOTES);
echo " <a href='$href'>««</a> ";
$prevpage = $pageno-1;
$href = htmlspecialchars($_SERVER['REQUEST_URI_PATH']."?".http_build_query(array('sayfa'=>$prevpage)+$_GET), ENT_QUOTES);
echo " <a href='$href'>«</a> ";
// …