PHP - Php Pagination Problem!
Hi guys,
well I'm trying to formulate pagination view of my results from a Mysql query in my database. The thing is that the query is not known beforehand, since the user of the database can enter several search terms in text fields of the webpage (text_search.php) and when he hits the "Submit" button, the new page (retrieve_text.php) looks about which text fields have been filled and appends the values in the mysql query like this: Code: [Select] $text_query = ...... WHERE [user-defined conditions] Everything is OK until now. But I wanted to show the results more clear to the user, since it can have e.g 600 results so it's not so good to view them in a loooooooooong page. So I tried to paginate them. Now comes the problem: the first page looks Ok, and brings only 25 results, which I want to be the limit of results to show per page. BUT, when I click on the "Next button", I see nothing. The reason? In pages 2,3...N, the $text_query is empty since there are no values submitted through the $_POST variable..., So, in the 1st page, if I print the SQL query I have something like that: Code: [Select] SELECT DISTINCT protein.protein_id, protein.protein_name FROM protein LEFT JOIN protein_reference ON protein_reference.prot_ref_protein_id = protein.protein_id LEFT JOIN reference ON reference.reference_id = protein_reference.prot_ref_reference_id LEFT JOIN families ON protein.protein_families_id = families.families_id WHERE protein.protein_name LIKE '%protein%' ORDER BY protein.protein_id LIMIT 0, 25 while in the 2nd page for example I get: Code: [Select] SELECT DISTINCT protein.protein_id, protein.protein_name, protein.protein_seq_len, protein.protein_organism, protein_ncbi FROM protein LEFT JOIN protein_reference ON protein_reference.prot_ref_protein_id = protein.protein_id LEFT JOIN reference ON reference.reference_id = protein_reference.prot_ref_reference_id LEFT JOIN families ON protein.protein_families_id = families.families_id WHERE ORDER BY protein.protein_id LIMIT 25, 25 The reason is, as I wrote before, that the where clause in the sql statement is written on-the-fly so the sql search is dynamic and not static. If it was static, like Code: [Select] SELECT * from protein WHERE name LIKE '%protein%'; things would be straight-forward. What can I do? Should/Could I somehow "send" the sql query from page to page? I suppose this is BAD practice, but I don't really know how to proceed... Similar TutorialsHello everyone, I have an ecommerce website and I'm trying to add pagination, but I'm stuck. I'm sure this will be an easy fix for someone with more experience than me. The first page works fine, but I get an error when I click on Next. I'm at a loss as to why. Can someone please help...? The page that gives an error: http://www.hopefloatsdesign.co.za/shopping/list.php?category=clothing&subcategory=hats Here is my code: // Connect to the MySQL database include "storescripts/connect_to_mysql.php"; $sql = mysql_query("SELECT * FROM products WHERE subcategory='$subcategory'"); // Adam's Pagination Logic $nr = mysql_num_rows($sql); // Get total of Num rows from the database query if (isset($_GET['pn'])) { // Get pn from URL vars if it is present $pn = preg_replace('#[^0-9]#i', '', $_GET['pn']); // filter everything but numbers } else { // If the pn URL variable is not present force it to be value of page number 1 $pn = 1; } //This is where we set how many database items to show on each page $itemsPerPage = 6; // Get the value of the last page in the pagination result set $lastPage = ceil($nr / $itemsPerPage); // Be sure URL variable $pn(page number) is no lower than page 1 and no higher than $lastpage if ($pn < 1) { // If it is less than 1 $pn = 1; // force if to be 1 } else if ($pn > $lastPage) { // if it is greater than $lastpage $pn = $lastPage; // force it to be $lastpage's value } // This creates the numbers to click in between the next and back buttons // This section is explained well in the video that accompanies this script $centerPages = ""; $sub1 = $pn - 1; $sub2 = $pn - 2; $add1 = $pn + 1; $add2 = $pn + 2; if ($pn == 1) { $centerPages .= ' <span class="pagNumActive">' . $pn . '</span> '; $centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> '; } else if ($pn == $lastPage) { $centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> '; $centerPages .= ' <span class="pagNumActive">' . $pn . '</span> '; } else if ($pn > 2 && $pn < ($lastPage - 1)) { $centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a> '; $centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> '; $centerPages .= ' <span class="pagNumActive">' . $pn . '</span> '; $centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> '; $centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a> '; } else if ($pn > 1 && $pn < $lastPage) { $centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> '; $centerPages .= ' <span class="pagNumActive">' . $pn . '</span> '; $centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> '; } // This line sets the "LIMIT" range $limit = 'LIMIT ' .($pn - 1) * $itemsPerPage .',' .$itemsPerPage; // Now we are going to run the same query as above but this time add $limit onto the end of the SQL syntax // $sql2 is what we will use to fuel our while loop statement below $sql2 = mysql_query("SELECT * FROM products WHERE subcategory='$subcategory' $limit"); // END Adam's Pagination Logic // Adam's Pagination Display Setup $paginationDisplay = ""; // Initialize the pagination output variable // This code runs only if the last page variable is not equal to 1 if ($lastPage != "1"){ // This shows the user what page they are on, and the total number of pages $paginationDisplay .= 'Page <strong>' . $pn . '</strong> of ' . $lastPage. ' '; // If we are not on page 1 we can place the Back button if ($pn != 1) { $previous = $pn - 1; $paginationDisplay .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $previous . '"> Back</a> '; } // Lay in the clickable numbers display here between the Back and Next links $paginationDisplay .= '<span class="paginationNumbers">' . $centerPages . '</span>'; // If we are not on the very last page we can place the Next button if ($pn != $lastPage) { $nextPage = $pn + 1; $paginationDisplay .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $nextPage . '"> Next</a> '; } } // END Adam's Pagination Display Setup $dynamicList = ""; $productCount = mysql_num_rows($sql); // count the output amount if ($productCount > 0) { // get all the product details while($row = mysql_fetch_array($sql2)){ $id = $row["id"]; $product_name = $row["product_name"]; $price = $row["price"]; $details = $row["details"]; $category = $row["category"]; $subcategory = $row["subcategory"]; $date_added = strftime("%b %d, %Y", strtotime($row["date_added"])); $dynamicList .= '<table style="float: left;" width="50%" border="0" cellspacing="0" cellpadding="6"> <tr> <td width="17%" valign="top"><a href="product.php?id=' . $id . '"><img style="border:#666 1px solid;" src="inventory_images/' . $id . '.jpg" alt="' . $product_name . '" width="77" height="102" border="1" /></a></td> <td width="83%" valign="top">' . $product_name . '<br /> R' . $price . '<br /> <a href="product.php?id=' . $id . '">View Product Details</a></td> </tr> </table>'; } } } else { $dynamicList = "We have no products listed in our store yet"; } ?> These are my divs: <div class="box3"> <h3><?php echo $category; ?> | <?php echo $subcategory; ?></h3> <br /> <?php echo $dynamicList; ?><br /> </div> <div class="box2"> <?php echo $paginationDisplay; ?><br /> <br /> <h3>Total Items: <?php echo $nr; ?></h3> </div> I don't understand why this is happening. I use the same exact code (but different mysql table) and the pagination works fine. Here's the code: Code: [Select] ..... <body id="set-database"> <div class="wrapper"> <?php include("navigation.php"); ?> <div class="full"> <?php $make = $_POST["sel1"]; $model = $_POST["sel2"]; echo "$make - $model"; if ( $make == "--MAKES--" ) { echo "<div class=\"red\">Please select a Make</div>"; } else { echo "<center><font color=\"#3333FF\">$make</font> - <font color=\"#3333FF\">$model</font></center><br />"; $mysql_host = -- $mysql_database= -- $mysql_user = -- $mysql_password = -- $conn = mysql_connect("$mysql_host","$mysql_user","$mysql_password") or trigger_error("SQL", E_USER_ERROR); $db = mysql_select_db("$mysql_database",$conn) or trigger_error("SQL", E_USER_ERROR); // find out how many rows are in the table $sql = "SELECT COUNT(*) FROM ACTIVE WHERE MODEL='$model'"; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); $r = mysql_fetch_row($result); $numrows = $r[0]; // number of rows to show per page $rowsperpage = 5; // find out total pages $totalpages = ceil($numrows / $rowsperpage); // get the current page or set a default if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) { // cast var as int $currentpage = (int) $_GET['currentpage']; } else { // default page num $currentpage = 1; } // end if // if current page is greater than total pages... if ($currentpage > $totalpages) { // set current page to last page $currentpage = $totalpages; } // end if // if current page is less than first page... if ($currentpage < 1) { // set current page to first page $currentpage = 1; } // end if // the offset of the list, based on current page $offset = ($currentpage - 1) * $rowsperpage; $sql = "SELECT * FROM ACTIVE WHERE MODEL='$model' ORDER BY INDEX_ID DESC LIMIT $offset, $rowsperpage"; $result = mysql_query($sql, $conn) or die('Error: ' . mysql_error()); echo " <table width=100% align=center border=1 class=\"mod\"><tr> <td align=center bgcolor=#00FFFF><b>Rating</b></td> <td align=center bgcolor=#00FFFF><b>Title</b></td> <td align=center bgcolor=#00FFFF><b>Make/Model</b></td> <td align=center bgcolor=#00FFFF><b>Type</b></td> <td align=center bgcolor=#00FFFF><b>Difficulty</b></td> <td align=center bgcolor=#00FFFF><b>Comments</b></td> <td align=center bgcolor=#00FFFF><b>Views</b></td> </tr>"; while ($row = mysql_fetch_assoc($result)) { { // Begin while $title = $row["TITLE"]; $type = $row["TYPE"]; $difficulty = $row["DIFFICULTY"]; $comments = $row["COMMENT_TOTAL"]; $id = $row['INDEX_ID']; $rating = $row["RATING_AVERAGE"]; $make = $row["MAKE"]; $model = $row["MODEL"]; $views = $row["HITS"]; echo " <tr> <td><div class=\"\">$rating/10</div></td> <td><div class=\"\"><a href=\"mod.php?id=$id\">$title</a></div></td> <td><div class=\"\">$make - $model</div></td> <td><div class=\"\">$type</div></td> <td><div class=\"\">$difficulty</div></td> <td><div class=\"\">$comments</div></td> <td><div class=\"\">$views</div></td> </tr>"; } } echo "</table><br />"; /****** build the pagination links ******/ echo "<center>"; // range of num links to show $range = 3; echo "<i>Page: </i>"; // if not on page 1, don't show back links if ($currentpage > 1) { // get previous page num $prevpage = $currentpage - 1; // show < link to go back to 1 page echo " <a stylehref='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'>Previous</a> - "; } // end if // loop to show links to range of pages around current page for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) { // if it's a valid page number... if (($x > 0) && ($x <= $totalpages)) { // if we're on current page... if ($x == $currentpage) { // 'highlight' it but don't make a link echo " <b>$x</b> "; // if not current page... } else { // make it a link echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> "; } // end else } // end if } // end for // if not on last page, show forward and last page links if ($currentpage != $totalpages) { // get next page $nextpage = $currentpage + 1; // echo forward link for next page echo " - <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>Next</a> "; } // end if /****** end build pagination links ******/ mysql_close($conn); } echo "$pagination</center>"; ?> <br /> <FORM><INPUT TYPE="button" class="btn" VALUE="Back" onClick="history.go(-1);return true;"> </FORM> </div> <?php include("footer.html"); ?> When I click the link for the next page and goes to it, there is nothing in the table (so the information isn't there). So the links and everything bring you the correct page, but that page doesn't have any of the information. Like I said, I use the same exact code except it pulls different information and that works no problem. Thanks! Hi guys, I'm having a little problem with a pagination code i'm using. Its for an image gallery, and I want to show the total amount of pictures in a set, and then the current picture displayed. I've got the total number, however its the current photo that i'm stuck on. Its linked into a mysql database, with two tables, one for the categories and the other for the photos. Category 1: Image ID 1, 2, 3 etc Category 2: Image ID 4, 5, 6 etc Now, my code works fine if they are all in order like this, but obviously images are deleted and replaced. so it could turn out like this: Category 1: Image ID 1, 2, 5, 8 etc Here is the code: $result = mysql_query("SELECT COUNT(photo_id) FROM gallery_photos WHERE photo_category='".addslashes($cid)."' GROUP BY photo_category ") or die(mysql_error()); list($num_rows)=mysql_fetch_array($result); mysql_free_result( $result ); $counting = mysql_query("SELECT photo_id FROM gallery_photos WHERE photo_category='".addslashes($cid)."' "); $counter="1"; while($row = mysql_fetch_array($counting)) { $id = $row['photo_id']; if($id == $pid) { if ($counter <= "9") { echo "0"; echo $counter; } else { echo $counter; } } else { $counter++; } } } echo "/"; if ($num_rows <= "9"){ echo "0"; echo $num_rows; } else { echo $num_rows; } } Any help would be hugely helpful as i'm really stuck on this! Thanks Edd Hello there, Please have a look on the below given code: Code: [Select] <?php function renderform($wardno, $demandno, $name) { include_once $_SERVER['DOCUMENT_ROOT'].'/header.php'; include_once $_SERVER['DOCUMENT_ROOT'].'/config/config.php'; include_once $_SERVER['DOCUMENT_ROOT'].'/functions/functions.php'; include_once $_SERVER['DOCUMENT_ROOT'].'/functions/connect-db.php'; extract($GLOBALS); ?> <link rel=stylesheet HREF="/css/sp.css" type="text/css" media="screen"> <div id="content"> <div id="labelopt"></div> <h2>okMZokj ukxfjdksa dh lwph</h2> <div id="dp-sp"> <form name="spsearchform" action="" method="post"> <table border="1"> <tr> <td id="labelmust" width="10%">fM- dz- %</td> <td><input class="english" type="text" size="15%" name="demandno" maxlength="40" value="<?php echo $demandno; ?>" /></td> <td id="labelmust" width="10%">okMZ dz- %</td> <td><input class="english" size="20%" type="text" size="15%" name="wardno" maxlength="3" value="<?php echo $wardno; ?>"/></td> <td id="labelmust" width="10%">uke %</td> <td><input class="hindi" size="30%" type="text" name="name" maxlength="100" value="<?php echo $name; ?>"/></td> <td><input type="submit" value="Search" name="btnsearch" /></td> </tr> </table> </form> <table border="1" cellpadding="2px"> <tr> <td id="labelcenter">okMZ dz-</td> <td id="labelcenter">fMeka.M dzekad</td> <td id="labelcenter">uke</td> <td id="labelcenter">irk</td> <td id="labelcenter">Hkqxrku</td> <td id="labelcenter">fu;kstu</td> <td id="labelcenter">feVk;sa</td> </tr> <?php if ($demandno == '' && $wardno == '' && $name == '') // all empty. { $result = mysql_query("SELECT * FROM sform order by wardno, id, demandno") or die(mysql_error()); } if ($demandno != '' && $wardno != '' && $name != '') // all full. { $result = mysql_query("SELECT * FROM sform where demandno='$demandno' and wardno='$wardno' and (name like '%$name%') order by wardno, id, demandno") or die(mysql_error()); } if ($demandno != '' && $wardno == '' && $name == '') // demand full else empty. { $result = mysql_query("SELECT * FROM sform where demandno='$demandno' order by wardno, id, demandno") or die(mysql_error()); } if ($demandno != '' && $wardno != '' && $name == '') // demand and ward full else empty. { $result = mysql_query("SELECT * FROM sform where demandno='$demandno' and wardno='$wardno' order by wardno, id, demandno") or die(mysql_error()); } if ($demandno == '' && $wardno != '' && $name == '') // ward full else empty. { $result = mysql_query("SELECT * FROM sform where wardno='$wardno' order by wardno, id, demandno") or die(mysql_error()); } if ($demandno == '' && $wardno != '' && $name != '') // ward and name full else empty. { $result = mysql_query("SELECT * FROM sform where wardno='$wardno' and (name like '%$name%') order by wardno, id, demandno") or die(mysql_error()); } if ($demandno == '' && $wardno == '' && $name != '') // name full else empty. { $result = mysql_query("SELECT * FROM sform where (name like '%$name%') order by wardno, id, demandno") or die(mysql_error()); } if ($demandno != '' && $wardno == '' && $name != '') // demand and name full else empty. { $result = mysql_query("SELECT * FROM sform where demandno='$demandno' and (name like '%$name%') order by wardno, id, demandno") or die(mysql_error()); } $perpage = 20; $totalresults = mysql_num_rows($result); $totalpages = ceil($totalresults / $perpage); if (isset($_GET['page']) && is_numeric($_GET['page'])) { $showpage=$_GET['page']; if ($showpage > 0 && $showpage <= $totalpages) { $start = ($showpage - 1) * $perpage; $end = $start + $perpage; } else { // error - show first set of results $start = 0; $end = $perpage; } } else { // if page isn't set, show first set of results $start = 0; $end = $perpage; } echo "<div id='labelmust'><blink>dqy ukxfjd% $totalresults</blink></div><div id='labelmust'></div>"; echo "<div align='center' style='margin-right: 10px; color: darkgreen;'>"; for ($i = 1; $i <= $totalpages; $i++) { echo "<a href='splist.php?page=$i'>$i</a> "; } echo "</div>"; if ($totalresults > 0) { for($i=$start; $i<=$end; $i++) { if ($i == $totalresults) { break; } echo "<tr>"; echo '<td width="10%"><center>' . mysql_result($result, $i, 'wardno') . '</center></td>'; echo '<td width="10%" id=\'labelenglish\'><center>' . mysql_result($result, $i, 'demandno') . '</center></td>'; echo '<td width="30%">' . mysql_result($result, $i, 'name') . '</td>'; echo '<td width="30%">' . mysql_result($result, $i, 'address') . '</td>'; echo '<td><center><a href="sppayment.php?demandno=' . mysql_result($result, $i, 'demandno') . '">Hkqxrku</center></a></td>'; echo '<td><center><a href="spedit.php?demandno=' . mysql_result($result, $i, 'demandno') . '">cnysa</center></a></td>'; echo '<td><center><a href="spdelete.php?demandno=' . mysql_result($result, $i, 'demandno') . '">feVk;sa</center></a></td>'; echo "</tr>"; } } else { echo "<tr>"; echo "<td colspan='7' align='center'><blink><strong>lwph miyC/k ugha gS A</strong></blink></td>"; echo "</tr>"; } ?> </tr> </table> </div> <?php echo "<div align='center' style='margin-right: 10px; color: darkgreen;'>"; for ($i = 1; $i <= $totalpages; $i++) { echo "<a href='splist.php?page=$i'>$i</a> "; } echo "</div>"; ?> <div id="menu"> <table> <tr> <td> <input type="button" name="btnprint" value="Print" /> <input type="button" value="New" name="btnnew" onclick="location.href='spnew.php';" /> <input type="button" value="Back" name="btnspback" onclick="location.href='../sp.php';" /> </td> </tr> </table> </div> </div> <?php include_once $_SERVER['DOCUMENT_ROOT'].'/footer.php'; } include_once $_SERVER['DOCUMENT_ROOT'].'/functions/connect-db.php'; include_once $_SERVER['DOCUMENT_ROOT'].'/functions/functions.php'; if(isset($_POST['btnsearch'])) { $demandno = mysql_real_escape_string(htmlspecialchars($_POST['demandno'])); $wardno = mysql_real_escape_string(htmlspecialchars($_POST['wardno'])); $name = mysql_real_escape_string(htmlspecialchars($_POST['name'])); renderform($demandno, $wardno, $name); } else { renderform('', '', ''); } ?> In the above code the pagination is working perfectly. After entering any value in the textboxes and pressing the search button also gives me the correct results with pagination. The problem occurs when we press the page links after any search. It shows the complete results again, rather than changing pages in the current search. Please help... I have included the php file I'm using. It is currently working on the internet, but doesn't work local. I'm not sure why. The last 2 lines of code call for the pagination and a footer of which neither show up on my local system. Any help would be appreciated. This is the script working on my site on the internet. http://vetstuf.com/jewelry/jewelry3_1.php <?php include 'form_j.php'; $tbl_name="images"; $search=$_POST["search"]; $con = mysql_connect("localhost", "root", "1910") or die ('Error connecting to mysql'); mysql_select_db("test") or die(mysql_error()); $query = "SELECT * FROM $tbl_name"; $result = mysql_query($query) or die("There was a problem with the SQL query: " . mysql_error()); if($result && mysql_num_rows($result) > 0) //Place code to connect to your DB here. // How many adjacent pages should be shown on each side? $adjacents = 2; /* First get total number of rows in data table. If you have a WHERE clause in your query, make sure you mirror it here. */ $query = "SELECT COUNT(*) as num FROM $tbl_name"; $total_pages = mysql_fetch_array(mysql_query($query)); $total_pages = $total_pages[num]; /* Setup vars for query. */ $targetpage = "image_test_2.php"; //your file name (the name of this file) $limit = 4; //how many items to show per page $page = $_GET['page']; if($page) $start = ($page - 1) * $limit; //first item to display on this page else $start = 0; //if no page var is given, set start to 0 /* Get data. */ $sql = "SELECT * FROM $tbl_name LIMIT $start, $limit"; $result = mysql_query($sql); /* Setup page vars for display. */ if ($page == 0) $page = 1; //if no page var is given, default to 1. $prev = $page - 1; //previous page is page - 1 $next = $page + 1; //next page is page + 1 $lastpage = ceil($total_pages/$limit); //lastpage is = total pages / items per page, rounded up. $lpm1 = $lastpage - 1; //last page minus 1 /* Now we apply our rules and draw the pagination object. We're actually saving the code to a variable in case we want to draw it more than once. */ $pagination = ""; if($lastpage > 1) { $pagination .= "<div class=\"pagination\">"; //previous button if ($page > 1) $pagination.= "<a href=\"$targetpage?page=$prev\">previous</a>"; else $pagination.= "<span class=\"disabled\">previous</span>"; //pages if ($lastpage < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up { for ($counter = 1; $counter <= $lastpage; $counter++) { if ($counter == $page) $pagination.= "<span class=\"current\">$counter</span>"; else $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>"; } } elseif($lastpage > 5 + ($adjacents * 2)) //enough pages to hide some { //close to beginning; only hide later pages if($page < 1 + ($adjacents * 2)) { for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++) { if ($counter == $page) $pagination.= "<span class=\"current\">$counter</span>"; else $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>"; } $pagination.= "..."; $pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1</a>"; $pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage</a>"; } //in middle; hide some front and some back elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)) { $pagination.= "<a href=\"$targetpage?page=1\">1</a>"; $pagination.= "<a href=\"$targetpage?page=2\">2</a>"; $pagination.= "..."; for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++) { if ($counter == $page) $pagination.= "<span class=\"current\">$counter</span>"; else $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>"; } $pagination.= "..."; $pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1</a>"; $pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage</a>"; } //close to end; only hide early pages else { $pagination.= "<a href=\"$targetpage?page=1\">1</a>"; $pagination.= "<a href=\"$targetpage?page=2\">2</a>"; $pagination.= "..."; for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++) { if ($counter == $page) $pagination.= "<span class=\"current\">$counter</span>"; else $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>"; } } } //next button if ($page < $counter - 1) $pagination.= "<a href=\"$targetpage?page=$next\">next</a>"; else $pagination.= "<span class=\"disabled\">next</span>"; $pagination.= "</div>\n"; } ?> <?php { $i = 0; $max_columns = 2; echo "<br>"; while($row = mysql_fetch_array($result)) { // make the variables easy to deal with extract($row); // open row if counter is zero if($i == 0) echo "<tr>"; echo "<td>"; ?> <div> <a id="thumb1" href="images/<?php echo $image; ?>" class="highslide" onclick="return hs.expand(this)"> <img src="images/<?php echo $image; ?>" title="Click to enlarge" width = "300"/></a> <div class="highslide-caption"><?php echo $id; ?> <?php echo $caption; ?></div> <?php echo "</td>"; // increment counter - if counter = max columns, reset counter and close row if(++$i == $max_columns) { echo "</tr>"; $i=0; } // end if } // end while } // end if results // clean up table - makes your code valid! if($i > 0) { for($j=$i; $j<$max_columns;$j++) echo "<td> </td>"; echo "</tr>"; } mysql_close($con); ?> </table> </body> </html></br> <?=$pagination?> <? require 'footer_j.php';?> The problem is this: When I upload more images, it will create more pages. That works fine, however, It seems when an image get bumped to a new page, it doesn't create a link to that said page. For example, In my Nature/Animals category, I have 5 images in there in total. It should create three pages and links to each page. It created the pages, but only shows "Previous 1 2." There isn't a Next button to page three at all. I have it set to show 2 images per page. So now I need to figure out how to get it right... This is my paging class Code: [Select] class paging { public function getPages($pages, $cid, $page_count) { global $db, $SK, $plang, $getURL; $this->pages = $pages; $this->cid = $cid; $this->page_count = $page_count; if(!isset($_GET['section'])) { $page = 1; } else { $page = $_GET['section']; } $prev = $page - 1; $next = $page + 1; $this->render = ''; if($prev > 0){ $this->render .= "<a href='{$getURL['site_url']}index/category/{$this->cid}/$prev'>Previous</a> "; } if($this->pages > 1){ if($pages >= 1 && $page <= $this->pages){ for($x=1; $x<=$this->pages; $x++) { $this->render .= " <a href='{$getURL['site_url']}index/category/{$this->cid}/$x'>$x</a> "; } } } if($page < ceil($this->pages/$this->page_count)){ $this->render .= "<a href='{$getURL['site_url']}index/category/{$this->cid}/$next'>Next </a> "; } return $this->render; } public function pageCount($table, $pid, $field, $page_count) { global $db; $this->pid = $pid; $this->field = $field; $this->page_limit = $page_count; $this->count_query = $db->getCount("SELECT * FROM $table WHERE `$this->field`=$this->pid"); $this->round_cr = ceil($this->count_query) / $this->page_limit; return $this->round_cr; } } And the bit of code that displays the images. Code: [Select] public function photoView(){ global $db, $SK, $plang, $PG; $photoid = (int) $_GET['id']; $field = 'catid'; $page_count = 2; $section = (isset($_GET['section']) AND (int)$_GET['section'] > 0) ? (int)$_GET['section'] : 1; if($section) { $page_start = ($section - 1) * $page_count; } else { $page_start = 0; } $start = $PG->pageCount('photos', $photoid, $field, $page_count); if(!empty($photoid)) { $photo_query = $db->query("SELECT * FROM photos WHERE catid='$photoid' ORDER BY `id` DESC LIMIT $page_start, $page_count"); $photo_result = $db->get(); if(count($photo_result) == '') { $this->render .= "No Images to display"; } else { $columns = $this->setresult[0]['colsnum']; $colnum = 2; $this->render .= $SK->photoHeader(); foreach ($photo_result as $pkey => $pvalue) { if($colnum < $columns) { if($colnum == 0){ $this->render .= "<tr>"; } $this->render .= $SK->photoRow($pvalue); } else { $colnum = 0; $this->render .= $SK->photoRow2($pvalue); } $colnum++; } $this->render .= $SK->photoFooter(); $this->render .= "<div style=\"text-align: center;font-weight: bold;\">" . $PG->getPages($start, $pvalue['catid'], $page_count) . "</div>"; } } else { $this->render = "Error: You have chosen the wrong path"; } return $this->render; } You can go to my Nature and Animals category at my site to see the problem Here. You will see the links, but once you go to page 2 there isn't a page three. If you change the 2 to a 3 in the address bar , you will see another image. Like this. You will see that the page links one and two disappear and leaves the previous link... So any idea on what the problem is? I need help -____- Hi, I new to php and I'm having problem with pagination. the problem is If I clicked next link or last page or any page link, it goes back to the home page and I've used PHP_SELF to establish the link. All I know something is wrong in my pagination link. May be there is pre defined value for PHP_SELF to be recorgnized or certain value is missing in my pagination link. Here is my code Code: [Select] include("conn.php"); if(($_POST["orga_name"]) && empty($_POST["title"])) { $sql = "select * from client_info where Name LIKE '%".$_POST["orga_name"]."%'"; $result = mysql_query($sql); $r = mysql_num_rows($result); include("form_search.php"); if ($r == 0 ){ echo "No records found"; } else { //pagination inaanzia hapa // how many rows to show per page $rowsPerPage = 5; // by default we show first page $pageNum = 1; // if $_GET['page'] defined, use it as page number if(isset($_GET['page'])) { $pageNum = $_GET['page']; } // how many pages we have when using paging $maxPage = ceil($r/$rowsPerPage); $offset = ($pageNum - 1) * $rowsPerPage; //pagination inaishia hapa $sql = "select * from client_info where Name LIKE '%".$_POST["orga_name"]."%' LIMIT $offset,$rowsPerPage"; $result = mysql_query($sql); //echo $r; echo "<table>"; echo "<tr><td class='title'>"."Name"."</td><td> </td><td class='title'>"."Box No"."</td><td> </td><td class='title'>"."Town/City"."<td></td><td> </td><td class='title'>"."Phone Number"."</td><td> </td><td class='title'>"."Email"."</td><td> </td><td class='title'>"."Website"."</td><td> </td></tr>"; $i=1; while($row=mysql_fetch_array($result)) { $name = $row["Name"]; $address = $row["POBoxNo"]; $town = $row["TownCity"]; $phonenumber = $row["OfficePhoneNumber"]; $email = $row["Email"]; $web = $row["Web"]; if($i%2){ echo "<tr><td class='odd'>"."<br>".$name."<br>"." "."</td><td> </td><td class='odd'>".$address."</td><td> </td><td class='odd'>".$town."<td></td><td> </td><td class='odd'>".$phonenumber."</td><td> </td><td class='odd'>".$email."</td><td> </td><td class='odd'>".$web."</td></tr>"; } else{ echo "<tr><td class='even'>"."<br>".$name."<br>"." "."</td><td> </td><td class='even'>".$address."</td><td> </td><td class='even'>".$town."<td></td><td> </td><td class='even'>".$phonenumber."</td><td> </td><td class='even'>".$email."</td><td> </td><td class='even'>".$web."</td></tr>"; } $i++; } echo "</table>"; // print the link to access each page $self = htmlentities($_SERVER['PHP_SELF']); $nav = ''; for($page = 1; $page <= $maxPage; $page++) { if ($page == $pageNum) { $nav .= " $page "; // no need to create a link to current page } else { $nav .= " <a href=\"$self?page=$page\">$page</a> "; } } // creating previous and next link if ($pageNum > 1) { $page = $pageNum - 1; $prev = " <a href=\"$self?page=$page\">[Prev]</a> "; $first = " <a href=\"$self?page=1\">[First Page]</a> "; } else { $prev = ' '; // we're on page one, don't print previous link $first = ' '; // nor the first page link } if ($pageNum < $maxPage) { $page = $pageNum + 1; $next = " <a href=\"$self?page=$page\">[Next]</a> "; $last = " <a href=\"$self?page=$maxPage\">[Last Page]</a> "; } else { $next = ' '; // we're on the last page, don't print next link $last = ' '; // nor the last page link } //echo $nav . "<br />"; echo $next . " " . $prev ; //"<br />"; echo $first . " " . $last; } Any help will be highly appreciated. MOD EDIT: [code] . . . [/code] BBCode tags added. Hmm i can't figure this out... Below you see my code. I have 8 results from the query and i have the pegination set to max 2 values. It has 8 result so it devides them into 4 pages. But all the results are on the first page so the second third and fourth page are empty. Why is that? <?php if (isset($_POST['model_zoeken'])) { $con = mysql_connect("localhost","admin",""); if (!$con) { die('Could not connect: ' . mysql_error()); } if (!(isset($pagenum))) { $pagenum = 1; } mysql_select_db("produkten", $con); $data = mysql_query("SELECT * FROM eigenschappen") or die(mysql_error()); $rows = mysql_num_rows($qry); $page_rows = 2; $last = ceil($rows/$page_rows); if ($pagenum < 1) { $pagenum = 1; } elseif ($pagenum > $last) { $pagenum = $last; } $max = 'limit ' .($pagenum - 1) * $page_rows .',' .$page_rows; $data_p = mysql_query("SELECT * FROM eigenschappen $max") or die(mysql_error()); $qry = "SELECT * FROM eigenschappen WHERE 1=1"; if (isset($_POST['prod_name']) && trim($_POST['prod_name']) != "") { $qry .= " AND prod_name='" . mysql_real_escape_string($_POST['prod_name']). "'"; } "'"; } $result = mysql_query($qry) or die(mysql_error()); $teller = 0; $rijen = 0; echo '<table border="0"><tr>'; while($row = mysql_fetch_array($result)) { echo' <td width="160" align="center"> <a href="'.$row['website'].'"></a><img src="'.$row['prod_img'].'"> </td> <td width="165" valign="top"><br /><br />Name: '.$row['prod_name'].'<br/><br/>Website: <a href="'.$row['website'].'" target="_blank">'.$row['website_naam'].'</a> </td>' ; $teller = $teller + 1; $rijen = $rijen + 1; if ($teller == 3 || $rijen == 3){ echo "</tr><tr>"; $rijen = 0; $teller = 0; } } echo '</tr></table>'; echo '<br />'; echo " --Page $pagenum of $last-- <p>"; if ($pagenum == 1) { } else { echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=1'> <<-First</a> "; echo " "; $previous = $pagenum-1; echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$previous'> <-Previous</a> "; } echo " ---- "; if ($pagenum == $last) { } else { $next = $pagenum+1; echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$next'>Next -></a> "; echo " "; echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$last'>Last ->></a> "; } } ?> Hi there Im trying to add a search feature to my pagination but with some googling and searching have had no luck and have also had no luck trying myself this is what i have so far Form Code: [Select] <form action="publist.php" method="post"> Search: <input type="text" name="search"> By: <select name="by"> <option value="name" selected="selected">Name</option> <option value="town">Town</option> <option value="county" >County</option> </select> Results Per Page: <select name="perpage"> <option value="10" selected="selected">10</option> <option value="25">25</option> <option value="50" >50</option> </select> <input type="hidden" name="hidden"> <input type="submit" value="Search"> </form> Related code: if(isset($_POST['hidden'])){ $by = $_POST['by']; $search = $_POST['search']; $sql = "SELECT * FROM table WHERE approved = 'Yes' AND '. $by .' = '. $search .' LIMIT $offset, $rowsperpage"; }else{ $sql = "SELECT * FROM table WHERE approved = 'Yes' LIMIT $offset, $rowsperpage"; } $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); while ($list = mysql_fetch_assoc($result)) { echo' <table width="700" border="1"> <tr> <td colspan="3">'. $list['name'] .'</td> </tr> <tr> <td height="24">Town: '. $list['town'] .'</td> <td>County: '. $list['county'] .'</td> <td>Postcode: '. $list['postcode'] .'</td> </tr> <tr> <td>Contact Number: '. $list['phone'] .'</td> <td>Email: '. $list['pubemail'] .'</td> <td><a href="info.php?id='. $list['ID'] .'">More Information</a></td> </tr> </table><br>'; } But when i try the search it comes out blank, Any help would be great Thanks, Blink359 If a LIMIT on rows is set by the dropdown, the Pagination links do not reflect this. For example, if you had 100 rows showing 25 records per page, the pagination should show 4 pages, whereas if there were 10 records per page it should show 10 pages. At the moment, the pagination shows 4 pages (which is correct for the page default of 25 records) but if someone chooses to show 10 records per page, it still only shows the 4 pages in the pagination links and if you click one it takes you the relevant page, ignoring the user selected LIMIT. If a user selects 5 records per page in the dropdown and then clicks page 2 in the pagination it shows records 26-50 when it should really show records 6-10. On the flip side, without selecting a number of rows in the dropdown, if you click on page 2 it shows records 26-50 and if you then choose 5 in the dropdown it does show the first 5 from that page (ie 26-30). So they do sort of work together but I would really like the pagination to alter depending on the number of rows selected. I hope that has not confused everyone too much but below is the code that I am using, in full as everything is related it seems. I have commented it as best I can to try to clear things up but if it would be better for me to break it down into the relevant bits then just shout! There are two sets of pagination on there, top and bottom, and the top one is after the Code: [Select] // TOP PAGINATIONcomment and the form for the dropdown is after Code: [Select] // LIMIT ROWS DROPDOWN If anyone can explain how I can get this to work properly, or whether it is even possible, I would be extremely grateful! Thanks in advance Steve Code: [Select] <?php require_once('../../Connections/Test.php'); ?> <?php // Make a MySQL Connection mysql_select_db($database_Test, $Test); // How many rows to show per page $rowsPerPage = 25; // Show the first page by default $pageNum = 1; // if $_GET['page'] defined, use it as page number if(isset($_GET['page'])) { $pageNum = $_GET['page']; } // Counting the offset to show the right records per page $offset = ($pageNum - 1) * $rowsPerPage; // Retrieve all the data from the seasons table $query = "SELECT *, DATE_FORMAT(`season_start`,' %D %M %Y') AS startdate, DATE_FORMAT(`season_end`,'%D %M %Y') AS enddate FROM seasons "; $query .= ( isset($_POST['records_per_page']) && intval($_POST['records_per_page']) > 0 ) ? 'LIMIT ' .$offset.',' . (int) $_POST['records_per_page'] : 'LIMIT ' .$offset.',' . $rowsPerPage; $result = mysql_query( $query ) or die('Query: ' . $query . '<br>Produced error: ' . mysql_error() . '<br>'); //Query for the DECADES INDEX at the top $links = mysql_query("SELECT DISTINCT SUBSTRING(season_name,1,3) as letter FROM seasons ORDER BY 1") or die(mysql_error()); // PAGINATION // Find the number of records $page_query = "SELECT COUNT(season_name) AS numrows FROM seasons"; $page_result = mysql_query($page_query) or die('Error, query failed'); $page_row = mysql_fetch_array($page_result, MYSQL_ASSOC); $page_numrows = $page_row['numrows']; // Divide the number of records by records per page to get number of pages $maxPage = ceil($page_numrows/$rowsPerPage); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Season List</title> <link href="../../styles/databaseedit.css" rel="stylesheet" type="text/css" /> </head> <body> <div class="container"> <?php include("/homepages/46/d98455693/htdocs/Templates/database/header.html"); ?> <?php include("/homepages/46/d98455693/htdocs/Templates/database/left.html"); ?> <div class="content"> <h1> SEASON LIST</h1> <p>Filter by Decade<br /> <?php // DECADES LISTING AT TOP OF PAGE // Fetch the records of the DECADE $row while($linkrow = mysql_fetch_array($links)) { // Show links to DECADE queries and add "0's" to the result echo '<a href="seasonslistdecades.php?searchstring='; echo $linkrow['letter']. '">'.$linkrow['letter'].'0\'s</a> '; } ?> </p> <hr /> <?php // TOP PAGINATION // print the link to access each page $self = $_SERVER['PHP_SELF']; $nav = ''; for($page = 1; $page <= $maxPage; $page++) { if ($page == $pageNum) { $nav .= " $page "; // no need to create a link to current page } else { $nav .= " <a href=\"$self?page=$page\">$page</a> "; } } // creating previous and next link // plus the link to go straight to // the first and last page if ($pageNum > 1) { $page = $pageNum - 1; $prev = " <a href=\"$self?page=$page\"><a href=\"$self?page=$page\"><img src=\"../../images/icons/Prev.png\" height=\"20\" alt=\"Previous\" title=\"Previous Page\" /></a> "; $first = " <a href=\"$self?page=1\"><img src=\"../../images/icons/First.png\" height=\"20\" alt=\"First\" title=\"First Page\" /></a> "; } else { $prev = ' '; // we're on page one, don't print previous link $first = ' '; // nor the first page link } if ($pageNum < $maxPage) { $page = $pageNum + 1; $next = " <a href=\"$self?page=$page\"><img src=\"../../images/icons/Next.png\" height=\"20\" alt=\"Next\" title=\"Next Page\" /></a> "; $last = " <a href=\"$self?page=$maxPage\"><img src=\"../../images/icons/Last.png\" height=\"20\" alt=\"Last\" title=\"Last Page\" /></a> "; } else { $next = ' '; // we're on the last page, don't print next link $last = ' '; // nor the last page link } // print the navigation link echo $first . $prev . $nav . $next . $last;?> // LIMIT ROWS DROPDOWN <div class="drop_right" ><form action="" method="post" name="records_per_page" target="_self"> Number of Records per page <select name="records_per_page" id="records_per_page"> <option value="5">5</option> <option value="10">10</option> <option value="15">15</option> <option value="20">20</option> <option value="25">25</option> <option value="30">30</option> <option value="40">40</option> <option value="50">50</option> </select> <input type="submit" name="SUB" id="SUB" value="Submit" /> </form></div> <p> <?php // SEASONS LISTING // Show the Table Headers echo ' <table align="center" cellspacing="0" cellpadding="0"> <tr> <th>ID</th> <th>Name</th> <th>From</th> <th>To</th> <th>Edit</th> </tr> '; // Show the Season Data while($row = mysql_fetch_array($result)) { echo ' <tr> <td>'.$row['season_id'] .'</td> <td>'.$row['season_name'] .'</td> <td>'.$row['startdate'] .'</td> <td>'.$row['enddate'] .'</td> <td><img src="../../images/icons/Search.png" height="20" alt="View" /> <img src="../../images/icons/Edit.png" height="20" alt="Edit" /> <img src="../../images/icons/Close.png" height="20" alt="Delete" /></td> </tr> ' ; } echo '</table> '; // BOTTOM PAGINATION // print the link to access each page $self = $_SERVER['PHP_SELF']; $nav = ''; for($page = 1; $page <= $maxPage; $page++) { if ($page == $pageNum) { $nav .= " $page "; // no need to create a link to current page } else { $nav .= " <a href=\"$self?page=$page\">$page</a> "; } } // creating previous and next link // plus the link to go straight to // the first and last page if ($pageNum > 1) { $page = $pageNum - 1; $prev = " <a href=\"$self?page=$page\"><a href=\"$self?page=$page\"><img src=\"../../images/icons/Prev.png\" height=\"20\" alt=\"Previous\" title=\"Previous Page\" /></a> "; $first = " <a href=\"$self?page=1\"><img src=\"../../images/icons/First.png\" height=\"20\" alt=\"First\" title=\"First Page\" /></a> "; } else { $prev = ' '; // we're on page one, don't print previous link $first = ' '; // nor the first page link } if ($pageNum < $maxPage) { $page = $pageNum + 1; $next = " <a href=\"$self?page=$page\"><img src=\"../../images/icons/Next.png\" height=\"20\" alt=\"Next\" title=\"Next Page\" /></a> "; $last = " <a href=\"$self?page=$maxPage\"><img src=\"../../images/icons/Last.png\" height=\"20\" alt=\"Last\" title=\"Last Page\" /></a> "; } else { $next = ' '; // we're on the last page, don't print next link $last = ' '; // nor the last page link } // print the navigation link echo $first . $prev . $nav . $next . $last; ?> <br /> <p> </p> <!-- end .content --></div> <div class="footer"> <p>This .footer contains the declaration position:relative; to give Internet Explorer 6 hasLayout for the .footer and cause it to clear correctly. If you're not required to support IE6, you may remove it.</p> <!-- end .footer --></div> <!-- end .container --></div> </body> </html> Can somebody please help me sort this code out I have wirtten/got from a tutorial from phpfreaks - http://www.phpfreaks.com/tutorial/basic-pagination. The code correctly knows the number of pages needed in order to display the records from the database, but it displays all records on each page. I have 4 records and want 2 records to be shown on each page, but the code below displays all 4 records on both pages. Can someone please shed some light onto how I can display the first 2 records on the first page, and the second 2 records on the second page? code below: Code: [Select] <?php //Connect to the database $user="username"; $password="password"; $database="database"; $con = mysql_connect("localhost",$user,$password) or die ('Could not connect: ' . mysql_error()); mysql_select_db($database, $con) or die( "Unable to select database"); // Determine number of rows in database $query = mysql_query("SELECT * FROM vids"); $numrows=mysql_num_rows($query); // number of rows to show per page $rowsperpage = 2; // find out total pages $totalpages = ceil($numrows / $rowsperpage); // get the current page or set a default if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) { // cast var as int $currentpage = (int) $_GET['currentpage']; } else { $currentpage = 1; } // if current page is greater than total pages... if ($currentpage > $totalpages) { // set current page to last page $currentpage = $totalpages; } // end if // if current page is less than first page... if ($currentpage < 1) { // set current page to first page $currentpage = 1; } // the offset of the list, based on current page $offset = ($currentpage - 1) * $rowsperpage; // get the info from the db $result = mysql_query("SELECT * FROM vids"); while($row = mysql_fetch_array($result)) { $id = $row['id']; $url = $row['url']; $page_url = $row['page_url'];; $title = $row['title']; $desc = $row['desc']; $date_add = $row['date_add']; $date_rec = $row['date_rec']; $place = $row['place']; $altitude = $row['altitude']; $jump_no = $row['jump_no']; //Display video echo "<div class='sky_cont'> <div class='sky_vid'><a class='video' href=\"$url\"><img src='http://www.netlinksurveyors.co.uk/test/images/lgo.jpg' alt=\"$title\" Border='0' /></a></div> <p><h4><a href=\"$page_url\" target='_blank'>$title</a></h4>$desc</p> </div>"; } /****** build the pagination links ******/ // if not on page 1, don't show back links if ($currentpage > 1) { // show << link to go back to page 1 echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> "; // get previous page num $prevpage = $currentpage - 1; // show < link to go back to 1 page echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> "; } // range of num links to show $range = 3; // loop to show links to range of pages around current page for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) { // if it's a valid page number... if (($x > 0) && ($x <= $totalpages)) { // if we're on current page... if ($x == $currentpage) { // 'highlight' it but don't make a link echo " [<b>$x</b>] "; // if not current page... } else { // make it a link echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> "; } } } // if not on last page, show forward and last page links if ($currentpage != $totalpages) { // get next page $nextpage = $currentpage + 1; // echo forward link for next page echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> "; // echo forward link for lastpage echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> "; } // end if /****** end build pagination links ******/ ?> ok here is my problem... for example: i have 1000 files with 15 entrys each. but in the last one there is only 8 entrys. (i want to make a pagination) i want to display 15 entrys on each page. also how to calculate from which entry to which should it read. (i have another text file in which is the number of total entrys in all files together) for the first page it should read the first 8 and from thefirst file and the first 7 from the second file to get 15 displayed on the page. i was tryin now for some hours, but i just can't figure it out. :S and i know that i will think how stupid i'm after i will see how it should be done. :S Hi all, I am currently returning candidates from a database initially just by the highest candidate id to the lowest... i.e. newest candidates to oldest. I have introduced a sort feature which works just fine, the problem is I am displaying my results over a few pages using pagination. The problem arises once I sort my results and then try to click onto the next page of results. Basically it is just resetting the sort as the sort relies on a button being pressed, which obviously isn't happening when the user is trying to get the next page of results. I'm not sure exactly which section of code would be relevant to this so I have posted the whole script... additionally if you need to take a look at it in action you can do so he http://www.beta.teachingagencies.co.uk/search_jobseekers.php As I say I know the problem is that when the page is changed the value is lost, but I don't have a clue how to solve the problem! Any help or advice would be appreciated. Many thanks, Greens85 Hi all. So I was pretty proud of myself because for the first time ever, I actually figured out how to update the .htaccess file without asking for help. Here's what I added: Code: [Select] RewriteRule albums/(.*)/(.*)/(.*)/ albums.php?language=$1&searchindex=$2&searchparameterdata=$3 that worked to translate my links to: http://www.my domain.com/albums/en/music/beatles/ But then.. along came pagination and I'm stumped again. On clicking my next page, it now appends to the above url like such.. Code: [Select] beatles/?language=en&locale=us&page=2&searchindex=music&searchparameter=keywords&searchparameterdata=beatles& Is this something I can correct in my .htaccess.. keeping the format of my working url and still letting pagination work? Hi basically the category part of this script works but when i try the paginating part (next) it goes back to showing all of the categories so in other words i want it to stay on the same category when i click next. I tried passing the category through the url which ive kept in the code below and although the url does show the category im meant to be in, the code ignores it and shows the latest articles from all categories. I've been trying to figure this out for about 4 days and i dont really know where to even start since im completely new to php so thanks in advance for any help. Anyway heres the code: Code: [Select] <select name="sort_category"> <option disabled selected>Sort by Category</option> <option value="General">General</option> <option value="Music">Music</option> <option value="Funny">Funny</option> </select> <input type="submit" /> </form> <br> <?php include('admin/conf.php'); include('admin/functions.php'); if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) { $startrow = 0; } else { $startrow = (int)$_GET['startrow']; } if (isset($_REQUEST['sort_category'])) { $select_category = $_REQUEST['sort_category']; $connection = mysql_connect($host, $user, $pass) or die ('Unable to connect!'); mysql_select_db($db) or die ('Unable to select database!'); $sql = "SELECT id, title, content, photo, timestamp FROM approved WHERE category='$select_category' ORDER BY timestamp DESC LIMIT $startrow,2"; $result = mysql_query($sql) or die ("Error in query: $query. " . mysql_error()); if (mysql_num_rows($result) > 0) { while($row = mysql_fetch_object($result)) { ?> <img src="http://trunham.info/pictures/ <?php echo $row->photo;?>" width="100" height="100" border="1" align="left" /> <font size="+2" class="style1"><a style="text-decoration:none" class="articletext" href="article.php?id= <?php echo $row->id; ?>" ><?php echo $row->title; ?></a></font><br><br> <font class="articletext2"><?php echo substr($row->content,0,100) ;?>...</font> <?PHP echo '<a href="'.$_SERVER['PHP_SELF'].'?startrow='.($startrow+2).'category='.($select_category).'">Next</a>'; $prev = $startrow - 2; if ($prev >= 0) echo '<a href="'.$_SERVER['PHP_SELF'].'?startrow='.$prev.'">Previous</a>'; ?> I do have the closing curly brackets later on and after this i also have an else part which runs if no category is selected and this outputs the same results that im getting from the pagination but i took it out to see if it was the problem and the paginating still wasnt sticking to the category so i assume it isnt. Here it is anyway: Code: [Select] <?php } else { echo 'Latest Articles:<br><br>'; $connection = mysql_connect($host, $user, $pass) or die ('Unable to connect!'); mysql_select_db($db) or die ('Unable to select database!'); $query = "SELECT id, title, content, photo, timestamp FROM approved ORDER BY timestamp DESC LIMIT 0, 5"; $result = mysql_query($query) or die ("Error in query: $query. " . mysql_error()); if (mysql_num_rows($result) > 0) { while($row = mysql_fetch_object($result)) { ?> <img src="http://trunham.info/pictures/ <?php echo $row->photo;?>" width="100" height="100" border="1" align="left" /> <font size="+2" class="style1"><a style="text-decoration:none" class="articletext" href="article.php?id= <?php echo $row->id; ?>" ><?php echo $row->title; ?></a></font><br><br> <font class="articletext2"><?php echo substr($row->content,0,100) ;?>...</font> :shy: <?php } } } mysql_close($connection); ?> sorry if i haven't explained it very well. i dont really know what im doing So i have this page that pretty much displays all the members in the database, and its split into pages using a pagination php script. The problem is that i want the ID number displayed next to it, however the database record id jumps since some records have been deleted. So while there were a total of 1000 records 10 have been removed so instead of showing the accurate ID number of 995 on the last record it displays the number 1000 .... I've tried just assigning a number to each record using the following code... $get_members = "SELECT * FROM members ORDER BY ID ASC LIMIT $rowsperpage OFFSET $offset"; $run_mem_query = mysql_query($get_members) or die(mysql_error()); $club_id = 1; while($member = mysql_fetch_assoc($run_mem_query)){ ?> <li><strong><?php echo $club_id++ ;?>.</strong><?php echo $member['username'] ;?> - <span><?php echo $member['state'] ;?></span></li> <?php } The problem with that is that every time i click to go to the next page the number sequence refreshed back to 1 and starts over.... i've been trying to find a way around his, but can't....does anyone have any solutions to this??? Here's the script that controls the pagination <?php if ($totalpages > 1){ /*********** Start the pagination links ********/ echo "<p>"; // range of num links to show $range = 6; // if not on page 1, don't show back links if ($currentpage > 1) { // show << link to go back to page 1 echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'>First</a> "; // get previous page num $prevpage = $currentpage - 1; // show < link to go back to 1 page echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'>Previous</a> "; } // end if if($result > 0){ // loop to show links to range of pages around current page for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) { // if it's a valid page number... if (($x > 0) && ($x <= $totalpages)) { // if we're on current page... if ($x == $currentpage) { // 'highlight' it but don't make a link echo " <b>$x</b> "; // if not current page... } else { // make it a link echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> "; } // end else } // end if } // end for }else{ echo "<a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>1</a>"; } // if not on last page, show forward and last page links if ($currentpage != $totalpages) { // get next page $nextpage = $currentpage + 1; // echo forward link for next page echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'> Next </a> "; // echo forward link for lastpage echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'> Last </a> "; } // end if echo "</p>\n"; /****** end build pagination links ******/ } ?> The issue I am having is that everytime I click the next button, it takes me to the index page. My question is, how do I set up a proper search results link in "href="?page=1"
index.php
<form action="search" method="GET"> <input type="search" name="search" placeholder="Find products, services ..."> <input type="submit" name="submit" value=""> </form>search.php if(isset($_GET['submit']) && !empty($_GET['search'])) { $value = escape(trim(Input::get('search'))); try { // Find out how many items are in the table $q = DB::getInstance()->query("SELECT * FROM records WHERE MATCH(title) AGAINST('$value' IN BOOLEAN MODE)"); $total = $q->count(); // How many items to list per page $limit = 10; // How many pages will there be $pages = ceil($total / $limit); // What page are we currently on? $page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array( 'options' => array( 'default' => 1, 'min_range' => 1, ), ))); // Calculate the offset for the query $offset = ($page - 1) * $limit; // Some information to display to the user $start = $offset + 1; $end = min(($offset + $limit), $total); // Prepare the paged query $stmt = DB::getInstance()->query("SELECT users.*, records.* FROM records LEFT JOIN users ON records.user_id = users.user_id WHERE MATCH(title) AGAINST('$value' IN BOOLEAN MODE) ORDER BY relevance DESC LIMIT {$limit} OFFSET ".$offset); if($stmt->count()) { // Display the results foreach($stmt->results() as $row) { $date = escape($row->posted); $record_date = escape(Input::facebook_date_format($date)); $record_id = escape($row->record_id); $title = trim($row->title); $slug_title = $row->slug_title; $view_count = escape(intval(number_format($row->views + 1))); $username = escape($row->username); require 'snippets/record_widget.php'; } } else { ?><div class="message"><?php echo 'No records found.';?></div><?php } <?php // The "back" link $prevlink = ($page > 1) ? '<a href="?page=1" title="First page"><img src="images/left-page-arrow-end.png"/></a> <a href="?page=' . ($page - 1) . '" title="Previous page"><img src="images/left-page-arrow-start.png"/></a>' : '<span class="disabled"><img src="images/left-page-arrow-end-disabled.png"/></span> <span class="disabled"><img src="images/left-page-arrow-start-disabled.png"/></span>'; // The "forward" link $nextlink = ($page < $pages) ? '<a href="?page=' . ($page + 1) . '" title="Next page"><img src="images/right-page-arrow-start.png"/></a> <a href="?page=' . $pages . '" title="Last page"><img src="images/right-page-arrow-end.png"/></a>' : '<span class="disabled"><img src="images/right-page-arrow-start-disabled.png"/></span> <span class="disabled"><img src="images/right-page-arrow-end-disabled.png"/></a></span>'; // Display the paging information ?> <div class="pages"> <span class="pages-arrows"><?php echo $prevlink; ?></span> <span class="pages-numbers"><?php echo $page; ?> of <?php echo $pages; ?></span> <span class="pages-arrows"><?php echo $nextlink; ?></span> </div> } catch (Exception $e) { echo '<p>', $e->getMessage(), '</p>'; } } else { Redirect::to('index'); } Edited by man5, 20 August 2014 - 10:27 PM. This is my pagination with the number bar: Code: [Select] <?php $page = $_GET['page']; $category = $_GET['cat']; $your_db = @ new mysqli("$hostname","$username", "$password"); if (mysqli_connect_errno()) { echo 'ERROR!<br />'.mysqli_connect_errno() .' - Not connected : '.mysqli_connect_error().'<br />'; die; } else { $db_connect = $your_db->select_db("database"); if (!$db_connect) { echo 'Error!'; die; } } echo '<p>'; $query = "select distinct fldCategory from tablename order by fldCategory"; $result = $your_db->query($query); $number_of_records = $result->num_rows; for ($i = 0; $i < $number_of_records; $i++) { $row = $result->fetch_assoc(); echo '<a href="page_name.php?cat='.stripslashes($row['fldCategory']).'">'; echo stripslashes($row['fldCategory']); echo '</a> / '; } echo '</p>'; if ($category) { $query = "select fldID, fldTitle, fldCategory, fldIconMedium, fldLink from tablename where fldCategory = '$category' order by fldCategory"; } else { $query = "select fldID, fldTitle, fldCategory, fldIconMedium, fldLink from tablename order by fldCategory"; } $result = $your_db->query($query); $number_of_records = $result->num_rows; $num_pages = $number_of_records / 7; if (($number_of_records % 7) > 0 ) { $num_pages++; } if (strlen($page) == 0) { $page = 0; } else { $page = $page * 7; } echo '<table border="1">'; $row_num = 1; $result->data_seek($page); for ($i = $page; $i < $number_of_records; $i++) { if ($row_num <= 7) { echo '<tr>'; for ($col_num = 0; $col_num < 5; $col_num++) { $row = $result->fetch_assoc(); echo '<td>'; show_image(stripslashes($row['fldIconMedium']),stripslashes($row['fldTitle'])); echo '<br />'; echo '<a href="'.stripslashes($row['fldLink']).'" target="_blank">'; echo stripslashes($row['fldTitle']); echo '</a>'; echo '</td>'; } $row_num++; echo '</tr>'; } else { break; } } echo '</table>'; for ($j = 0; $j < $num_pages; $j++) { $page_link = $j + 1; echo '<a href="page_name.php?page='.$j.'&cat='.$category.'">'.$page_link.'</a> '; } echo ' '.$number_of_records; function show_image($image_name, $alt) { if (file_exists("path_to_images/$image_name")) { $dim_img = getimagesize('path_to_images/'.$image_name); echo '<img src="path_to_images/'.$image_name.'" alt = '.$alt.' border=0 align="bottom"'; echo 'width = '. $dim_img[0] .' height = ' .$dim_img[1] . ' />'; } else echo 'NO IMAGE'; } ?> To see it in action, here is the link to the 'skill games' section of the pagination script: http://netroxy.com/games2.php?cat=skills Ok here is the issue 1. As you can see, all the results displayed in the pagination script is correct, but what confuses me is the extra blank images that continue on in the table of the pagination table. I tried replacing the queries to see if the extra blank images would be removed like this: Code: [Select] $query = "select fldID, fldTitle, fldCategory, fldIconMedium, fldLink from tablename where fldCategory = '$category' and length(fldIconMedium) > 0 order by fldCategory"; } else { $query = "select fldID, fldTitle, fldCategory, fldIconMedium, fldLink where length(fldIconMedium) > 0 from tablename order by fldCategory"; So you see, I used 'length(fldIconMedium) > 0' making images less than 0 to see if the rest of the blank images would disappear from the cells in the table. This has not worked. Hence 'fldIconMedium' is the column for the images in the mysql database. Visit the link and you'll see the extra blank images through the results. This also applies when search for other game categories, blank images appear and I cant remove those extra blank images from the table. |