hello i want to list contents as 10 contents per page
this is source code for each content
<?
while ($arama=mysql_fetch_array($arama_sonuc)) {
?>
<h4><?=$arama[baslik]?></h4>
<div class="article box">
<div class="article-desc-oku">
<p class="info">Yayınlanma: <strong><?=$arama[eklemetarihi]?></strong><br />
Yazan: <strong>Ronnie C. Lynwood</strong><br /><?=$arama[tiklanma]?> kez okunmuş.<br />
<?php rating_form("$arama[id]"); ?>
</p>
</div>
<?=$arama[spot]?>
</div> <!-- /article -->
I think you should better use a paging class rather than creating your own. This will save a lot of time of yours in next projects too. Your current problem will also be solved. Check this out.
Download Location
It looks like you are using MySQL: You can build a query using the SQL LIMIT command.
For example:
SELECT * FROM myTable LIMIT 5, 10
Will tell MySQL to return only the first ten elements after the 5th row. You can use a parameter on the query string to build an appropriate SQL query to "ask" the database which "page" you want to see.
Here http://php.about.com/od/phpwithmysql/ss/php_pagination.htm you can find a complete code example on pagination. It's also explained very well.
Sorry but I can't offer more just by seeing a snipped of code ...
i used codes below to make pagination
<?
if (isset($_GET['sayfa'])) {
$pageno = $_GET['sayfa'];
} else {
$pageno = 1;
} // if
$query = mysql_query("SELECT count(id) FROM yazilar");
$query_data = mysql_fetch_row($query);
$numrows = $query_data[0];
$rows_per_page = 10;
$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;
$query = mysql_query("SELECT * FROM yazilar $limit");
if ($pageno == 1) {
echo " İLK ÖNCEKİ ";
} else {
echo " <a href='{$_SERVER['PHP_SELF']}?sayfa=1'>İLK</a> ";
$prevpage = $pageno-1;
echo " <a href='{$_SERVER['PHP_SELF']}?sayfa=$prevpage'>ÖNCEKİ</a> ";
} // if
echo " ( Sayfa $pageno ) ";
if ($pageno == $lastpage) {
echo " SONRAKİ SON ";
} else {
$nextpage = $pageno+1;
echo " <a href='{$_SERVER['PHP_SELF']}?sayfa=$nextpage'>İLERİ</a> ";
echo " <a href='{$_SERVER['PHP_SELF']}?sayfa=$lastpage'>SON</a> ";
} // if
?>
Let me suggest some existing PHP solutions
Zend_Paginator, loosely coupled can be used stand alone without the whole framework.
If you want to build your own flavour I recommand the SPL countable and Iterator classes.
Related
I am trying to filter details using a-z list, which I can do successfully.
But the problem I am facing is that when I want to display the result along with some pagination, it doesn't do exactly what I want it to do.
Here is my code:
<?php
session_start();
//what page are we currently on
if(!isset($_GET['page'])){
$page=1;
}
else {
$page=(int)$_GET['page'];
}
//select how many records to show per page
$limit=16;
//count how many rows
$total=$conn->query("SELECT COUNT(*) FROM `movie`")->fetchColumn();
//how many pages will be there
$pages=ceil($total/$limit);
if($page<1){
$page=1;//forcing page to be 1 if it is less then 1
}
else if($page>$pages){
$page=$pages;
}
//calculate the offset
$offset=($page-1)*$limit;
if(isset($_GET['word'])){
$qname=$_GET['word'];
}
else {
$qname='a';
}
$sql=$conn->prepare("SELECT * FROM `movie` WHERE `title` LIKE '$qname%' ORDER BY `movie_id` LIMIT $limit OFFSET $offset");
$sql->execute();
$sql->rowCount();
while($row=$sql->fetch(PDO::FETCH_ASSOC)){
$title=$row['title'];
$poster=$row['poster'];
echo '<li><a href="#">
<img src="'.$poster.'" />
<h2><strong>Watch '.$title.' Online</strong></h2>
</a>
</li>';
}
?>
Then somewhere in my html i have this pagination
<?php
$prev=$page-1;
$next=$page+1;
$previous="";
$nextr="";
if($page>1){
$previous='<li>«</span>';
}
if($page<$pages){
$nextr='<li>»</span>';
}
$numbers="";
if($pages>1){
for($i = max(1, $page - 5); $i <= min($page + 5, $pages); $i++){
if($i==$page){
$numbers.='<li><a class="active" href="?page='.$i.'">'.$i.'</a></span></li>';
}
else {
$numbers.='<li>'.$i.'</span></li>';
}
}
}
echo $previous;
echo $numbers;
echo $nextr;
?>
And my html :-
<div class="result"><h2>Browse By Words :- A | B</h2></div>
So when I click on link-a it displays the result and the url is like a-z.php?word=a and then when i try to paginate the url changes to a-z.php?page=2
So, how can I paginate the result after fetching it from the db?
I am looking for a way without ajax.
I have a mysql database and use a multi variable search page, find.php, to input variables. The results come out correctly (count is correct and so is page 1 of the results) but when I try and go to the next page I get an error :: Undefined index: term1 line 60 ::Undefined index: term2 line 61 and so on.
Search2.php is as set below:
<?php
include "db.inc.php";
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * 15;
$term1 = $_POST['term1'];
$term2 = $_POST['term2'];
$term3 = $_POST['term3'];
$term4 = $_POST['term4'];
$sql ="SELECT * FROM cdrequests WHERE pname LIKE '%$term1%' AND date LIKE '%$term2%' AND date LIKE '%$term3%' AND dept LIKE '%$term4%' LIMIT $start_from, 15";
$rs_result = mysql_query ($sql);
$num_rows = mysql_num_rows($rs_result);
$query = mysql_query("SELECT * FROM cdrequests WHERE pname LIKE '%$term1%' AND date LIKE '%$term2%' AND date LIKE '%$term3%' AND dept LIKE '%$term4%'");
$number=mysql_num_rows($query);
print "<font size=\"5\" color=white><b>CD Requests</b></font> </P>";
?>
pagination structure
<?php
$sql = "SELECT COUNT(id) FROM cdrequests WHERE pname LIKE '%$term1%' AND date LIKE '%$term2%' AND date LIKE '%$term3%' AND dept LIKE '%$term4%'";
$rs_result = mysql_query($sql);
$row = mysql_fetch_row($rs_result);
$total_records = $row[0];
$total_pages = ceil($total_records / 15);
/****** build the pagination links ******/
// range of num links to show
$range = 3;
// if not on page 1, don't show back links
if ($page > 1) {
// show << link to go back to page 1
echo " <a href='search2.php?page=1'><b>First</b></a> ";
// get previous page num
$prev = $page - 1;
// show < link to go back to 1 page
echo " <a href='search2.php?page=$prev'><b>«</b></a> ";
} // end if
// loop to show links to range of pages around current page
for ($x = ($page - $range); $x < (($page + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $total_pages)) {
// if we're on current page...
if ($x == $page) {
// 'highlight' it but don't make a link
echo " <font size='5' color=yellow><b> $x </b></font> ";
// if not current page...
} else {
// make it a link
echo " <a href='search2.php?page=$x'>$x</a> ";
} // end else
} // end if
} // end for
// if not on last page, show forward and last page links
if ($page != $total_pages) {
// get next page
$next = $page + 1;
// echo forward link for next page
echo " <a href='search2.php?page=$next'><b>»</b></a> ";
// echo forward link for lastpage
echo " <a href='search2.php?page=$total_pages'><b>Last</b></a> ";
} // end if
/****** end build pagination links ******/
echo '</table>';
?>
Somehow going to page 2 fails to carry over proper info of variable term 1, term2 etc.
Any idea/help appreciated
Your page links do not pass term1, term2, etc. back to the server. Also if you are going to pass them in the link then you need to check $_REQUEST['term1'], $_REQUEST['term2'], etc. to cover both GET and POST requests.
The code of the links should be like this:
echo " <a href='search2.php?page=$next".
"&term1=".urlencode($term1).
"&term2=".urlencode($term2).
"&term3=".urlencode($term3).
"&term4=".urlencode($term4)"'><b>»</b></a> ";
If you have too many parameters to pass to the server then you should probably consider sending POST requests when clicking on the links using JavaScript.
I've come across a problem - but any help would be appreciated.
When I query the database using the results posted from a form, the pagination works initially i.e. for the first 10 records but when I click on the 2 hyperlink of the pagination for the second page of results it loses the $_POST variable and returns to the full data set.
What is the best way of keeping these variables available for the second (and further) pages?
thanks for reply:
still i have a problem, can any one help me please , the below is my complete php file
thanks in advance
<html>
<head>
<link rel="stylesheet" type="text/css"
href="design.css">
</head>
<body>
<?php
include("header.php");
?>
<center>
<div id="content" class="frm">
<a href='admin.php' style='float:left'>Back!</a>
<h2>Search Result</h2>
<br><br>
<?php
include("../config.inc");
$find=$_GET['find'];
// get page no and set it to page variable, if no page is selected so asign first page bydefualt
if (isset($_GET["page"])){
$page = $_GET["page"];
}
else {
$page=1;
}
// count all record in this table then divide it on 10 in order to find the last page----- every page has 10 record display
$sql = "SELECT COUNT(*) FROM tt where TTT='$find' ";
$rs_result = mysql_query($sql);
$row = mysql_fetch_row($rs_result);
$total_records = $row[0];
$total_pages = ceil($total_records / 2);
// this line check that page no must be in integer format
$page = (int)$page;
if ($page > $total_pages) {
$page = $total_pages;
} // if
if ($page < 1) {
$page= 1;
} // if
$start_from = ($page-1) * 2;
$q=mysql_query("select * from tt where TTT='$find' order by ID limit $start_from,2");
$c=mysql_query("select count(*) from tt where TTT='$find'");
echo "<center>".mysql_result($c,0)."Filtered</center>";
echo "<center>";
echo "<table border='2' bgcolor=#CCCCCC>
<tr>
<th>TTT</th>
<th>Enroll Date</th>
<th>Gradution Date</th>
<th>ID</th>
</tr>";
while($row=mysql_fetch_array($q))
{
echo "<tr>";
echo "<td>".$row['TTT']."</td>";
echo "<td>".$row['Enroll_Date']."</td>";
echo "<td>".$row['Graduation_Date']."</td>";
echo "<td>".$row['ID']."</td>";
}
echo "</table>";
echo "<center>";
// paginatio start here
if ($page== 1) {
echo " << < ";
} else {
echo " <a href='{$_SERVER['PHP_SELF']}?page=1'><<</a> ";
$prevpage = $page-1;
echo " <a href='{$_SERVER['PHP_SELF']}?page=$prevpage'><</a> ";
} // if
echo " ( Page [$page] of [$total_pages] ) ";
if ($page == $total_pages) {
echo " > >> ";
} else {
$nextpage = $page+1;
echo " <a href='{$_SERVER['PHP_SELF']}?page=$nextpage'>></a> ";
$lastpage=$total_pages;
echo " <a href='{$_SERVER['PHP_SELF']}?page=$lastpage'>>></a> ";
} // if
?>
</div>
</center>
<?php
include("footer.php");
?>
</body>
</html>
The best practice says to not use POST method if your query doesn't alter the state of your system. For example, in your case I wouldn't submit a POST request but I'd use GET.
That way your pagination links should preserve your query parameters.
Don't use POST in the first place. POST is for sending data to be acted on. GET is for sending data that describes what you want to read. If you are paginating, then you are reading things.
Then make sure your links contain all the data you need to describe what it is you want the second (or third or etc) page to contain.
Its usefull to get a pre-written pagination class if you are inexperienced making one yourself. (if not ignore this awnser)
You could use something like this
http://www.catchmyfame.com/2011/10/23/php-pagination-class-updated-version-2/
I had search through many websites and tried the different ways provided online, but it cant seen to work. It does not load the information when I click next, last, first, previous. It only loads the first page's result. Please help! Thank you in advance.
function retrieveName($fieldName)
{
$i=1;
if(isset($_GET[$fieldName]))
{
mysql_connect("localhost", "root") or die(mysql_error());
mysql_select_db("intern") or die(mysql_error());
//This checks to see if there is a page number. If not, it will set it to page 1
if (!(isset($pagenum)))
{
$pagenum = 1;
}
//Here we count the number of results
$intern = $_GET[$fieldName];
$data = mysql_query("SELECT p.`internName`, p.`internNRIC`, c.`internSchName` FROM `personaldetails` p, `currentinstitution` c WHERE c.`internNRIC`= p.`internNRIC` AND p.`internName` like '%$intern%' || p.`internNRIC` like '%$intern%' || c.`internSchName` like '%$intern%' GROUP BY p.internNRIC") or die(mysql_error());
$rows = mysql_num_rows($data);
//This is the number of results displayed per page
$page_rows = 1;
//This tells us the page number of our last page
$last = ceil($rows/$page_rows);
//this makes sure the page number isn't below one, or more than our maximum pages
if ($pagenum < 1)
{
$pagenum = 1;
}
elseif ($pagenum > $last)
{
$pagenum = $last;
}
//This sets the range to display in our query
$max = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
PRODUCTION. //This is your query again, the same one... the only difference is we add $max into it
$data_p = mysql_query("SELECT p.`internName`, p.`internNRIC`, c.`internSchName` FROM `personaldetails` p, `currentinstitution` c WHERE c.`internNRIC`= p.`internNRIC` AND p.`internName` like '%$intern%' || p.`internNRIC` like '%$intern%' || c.`internSchName` like '%$intern%' GROUP BY p.internNRIC $max ") or die(mysql_error());
//This is where you display your query results
while($row = mysql_fetch_array( $data_p ))
{
echo $i. ".";
echo " NRIC : ".$row['internNRIC'] ."";
echo "</br><br/>";
echo " Name : ". $row['internName'] . " Name of School :" . $row['internSchName'];
echo "</br><br/>";
$i++;
}
echo "<p>";
// This shows the user what page they are on, and the total number of pages
echo " --Page $pagenum of $last-- <p>";
// First we check if we are on page one. If we are then we don't need a link to the previous page or the first page so we do nothing. If we aren't then we generate links to the first page, and to the previous page.
if ($pagenum == 1)
{
}
else
{
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=1&searchIntern=$intern'> <<-First</a> ";
echo "---Interns Search---";
$previous = $pagenum-1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$previous&searchIntern=$intern'> <-Previous</a> ";
}
//This does the same as above, only checking if we are on the last page, and then generating the Next and Last links
if ($pagenum == $last)
{
}
else
{
$next = $pagenum+1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$next&searchIntern=$intern'>Next -></a> ";
echo "---Interns Search---";
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$last&searchIntern=$intern'>Last ->></a> ";
}
}else echo "Please enter your search.";
}
Not 100% about this, but it looks like you're using a local variable for $pagenum when you want to use either a parameter (good idea) or a global variable such as $_GET['pagenum']. You're also leaving yourself open to SQL injection. Use mysql_real_escape_string on all variables which need to be used in queries (like $intern).
As #cwallenpoole says, it looks like $pagenum is scoped outside of the function, and I'm guessing the function is written assuming that register_globals is on, which is generally a very bad thing. I've seen this cause plenty of issues when moving an old (inherited) site to a new server.
To fix that specific problem, replace:
if (!(isset($pagenum)))
{
$pagenum = 1;
}
with this:
$pagenum = isset($_REQUEST['pagenum']) ?
(int)$_REQUEST['pagenum'] :
1;
This sets $pagenum to the request's pagenum value, and defaults to 1 if the page number isn't in the request. It also casts the value to an int which should at least stop one injection attack vector. The rest of the function is another matter...
I am not a well-versed programmer so i don't want to use a complicated pagination. Is there an alternative to using a pagination like in my queries can i limit them to say 20 results and then if their are more than 20 results i can show a "next" button and then that button will further load the next results??
I only want "next" to show if there are 20> results? Any help will be appreciated. Thanks.
Code:
$query="SELECT * FROM actresses where actress_id = '$actressid' and production_full_name LIKE '%$q%'";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
echo "";
$i=0;
while ($i < $num) {
$1=mysql_result($result,$i,"production_full_name");
$2=mysql_result($result,$i,"production_id");
$3=mysql_result($result,$i,"actress");
echo "<br><div id=linkcontain><a id=slink href=$data/actress.php?id=$2>$3</a><div id=production>$1</div></div>";
echo "";
$i++;
}
You could add a limit to your query.
$lower_limit = $results_per_page * $page_number;
$upper_limit = $lower_limit + $results_per_page
..and production_full_name LIKE '%$q%' LIMIT $lower_limit, $upper_limit
Then make a conditional "next page" link
if ($upper_limit > 20) echo 'Next;
You can find many examples searching on google.
http://www.php-mysql-tutorial.com/wikis/php-tutorial/paging-using-php.aspx for example.
You only have to edit $rowsPerPage for amount of results, and if you want further edit on what to get from the DB, the $query.
Includes are not necessary, though.
edit: note the implication of using a $_GET that will have influence on the DB query. You have to be careful to not allow dangerous values in it (mysql injection). In the example of the webpage, it uses ceil, so I believe that it will output 0 for a non numeric value, which is safer.
You can use the PEAR packages.
They are much easier to use similar to the frameworks.
But before you use them you need to check whether the PEAR works on your server or not.
If you are using it locally then there are steps to install the PEAR packages on your local machine. For more instructions to install PEAR.
Click here to view the installation steps.
Once you have installed the PEAR package please follow the instruction to configure the PAGER class.http://www.codediesel.com/php/simple-pagination-in-php/
J
Something like that:
$data = mysql_query("SELECT * FROM `table`");
$total_data = mysql_num_rows($data);
$step = 30;
$from = $_GET['p'];
$data = mysql_query("SELECT * FROM `table` LIMIT '.$from.','.$step.'"
And creating links:
$p=1;
for ($j = 0 ; $j <= $total_data+$step; $j+=$step)
{
echo ' '.$p.' ';
$p++;
} ?>
Not tested.
If your query is set up as
"SELECT SQL_CALC_FOUND_ROWS * FROM actresses where actress_id = '$actressid' and production_full_name LIKE '%$q%' LIMIT ".($page*$lpage).",".$lpage
... the next statement can be SELECT FOUND_ROWS() to get the actual number of results.
Don't forget to put mysql_real_escape_string() on those variables.
NEVER use SELECT * with mysql_num_rows; if it's a big table, it will waste a LOT of time.
What you can do is fetch a COUNT(*) of how many rows are in your set of data. Then decide how many items you want per page. $numberOfRows / $itemsPerPage gives you the number of pages. In MySQL, to limit results you use LIMIT X, Y X is the beginning of the range, and Y is the number of items you want to fetch. So to fetch all the items on a page, your query would be LIMIT ($currentPage * $itemsPerPage), $itemsPerPage Then it's up to you, depending on how you want to format your pagination, to write the view logic. Just go from back to front: if the current page is 1, then the previous button is disabled. If the page is not 1, then the current page number is the number of pages from the beginning. If the total number of pages is bigger than the current page, then count from the current page, until the last page (unless you want to cut off the page count at some point)
I use the following method to assist in creating a list of pages, no matter what direction. I could plug in 5 for the current page, and 0 as the goal page, and it would return a list of 5 pages for me to iterate through, in order.
/*
* Generates a list of pages based on the current page to the goal page number
*/
function generatePageList($currentPage, $goal) {
$span = $goal - $currentPage;
$step = abs($span) / $span;
$list = array();
for($x = $currentPage; $x !== $goal;) {
// We want to add the step at the beginning of the loop, instead of
// at the end
// Fixes bug when there are only two pages
$x += $step;
$list[] = $x;
}
return $list;
}
This is more easy way to create pagination of a data
<?php
require_once 'db_connect.php';
$limit = 20;
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $limit;
$sql = "SELECT * FROM employee ORDER BY id ASC LIMIT $start_from, $limit";
$rs_result = mysqli_query($con, $sql);
?>
<table class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Salary</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($rs_result)) {?>
<tr>
<td><?php echo $row["employee_name"]; ?></td>
<td><?php echo $row["employee_salary"]; ?></td>
<td><?php echo $row["employee_age"]; ?></td>
</tr>
<?php
};
?>
</tbody>
</table>
<?php
$sql = "SELECT COUNT(id) FROM employee";
$rs_result = mysqli_query($con, $sql);
$row = mysqli_fetch_row($rs_result);
$total_records = $row[0];
$total_pages = ceil($total_records / $limit);
$pagLink = "<nav><ul class='pagination'>";
for ($i=1; $i<=$total_pages; $i++){
$pagLink .= "<li><a href='index.php?page=".$i."'>".$i."</a></li>";
};
echo $pagLink . "</ul></nav>";
?>
<script type="text/javascript">
$(document).ready(function(){
$('.pagination').pagination({
items: <?php echo $total_records;?>,
itemsOnPage: <?php echo $limit;?>,
cssStyle: 'light-theme',
currentPage : <?php echo $page;?>,
hrefTextPrefix : 'index.php?page='
});
});
</script>