PHP - Pagination Of Search Results
Good Evening,
I've been in a trial and error state for the past week trying to figure out how I can put on the pre-made pagination scripts I found on the web, but of no luck. I have just started programming like two weeks ago, and is still trying to understand logics and stuffs so I can get my desired output. So far, everything is doing well except for one - I am really having a hard time to incorporate pagination scripts with my code. To rank myself as a php programmer, I can say I am lower than one, and seemingly, what I want to achieve is an advanced code. Can anyone help me on what pagination code I should try to play with and incorporate with my code? Here's my code so far: <?PHP include("dbconnection.php"); //Include database connection to file $query = "SELECT * FROM records"; if(isset($_POST["btnSearch"])) { $query .= " WHERE last_name LIKE '%".$_POST["search"]."%' OR first_name LIKE '%".$_POST["search"]."%'OR territory LIKE '%".$_POST["search"]."%'OR job_title LIKE '%".$_POST["search"]."%'OR title LIKE '%".$_POST["search"]."%'OR employer LIKE '%".$_POST["search"]."%' ORDER BY territory ASC LIMIT 0,15" ; $result = mysql_query($query, $connection) or die(mysql_error()); } ?> <!-- Start of table --> <table width="760" border="0" align="center" cellpadding="0" cellspacing="0"> <td> <table width="760" border="0" cellpadding="0" cellspacing="0"> <!-- Table data containing the Asia Logo --> <td width="199" align="center" valign="top"> <a href="login.html"> <img src="asia.gif" alt="" width="152" height="58" border="0" /> </a> </td> <!-- Table data containing Home button --> <td width="176" align="right" valign="bottom"> <a href="main.php"> <img src="Home.jpg" width="104" height="20" border="0"/> </a> </td> <!-- Table data containing View Client button --> <td width="130" align="right" valign="bottom"> <img src="View.jpg" width="104" height="20" border="0"/> </td> <!-- Table data containing the Add Client button --> <td width="146" align="right" valign="bottom"> <a href="add_client.php"> <img src="Add.jpg" width="104" height="20" border="0"/> </a> </td> <!-- Blank table data --> <td width="109" align="right" valign="bottom"> </td> </table> <!-- Table design division and body--> <table width="760" border="0" cellpadding="0" cellspacing="0"> <td width="200" height="3" bgcolor="#1B1C78"> <img src="images/topspacerblue.gif" alt="" width="1" height="3" /></td> <td width="560" bgcolor="#0076CC"> <img src="images/topspacerlblue.gif" alt="" width="1" height="3" /></td> <tr> <td height="500" colspan="2" align="center" valign="top" bgcolor="#F3FAFE"> <!-- Page contents --> <!-- Search Query --> <br> <form name="form" action="view_client.php" method="post"> <table width="351" border="0"> <tr> <td width="137" align="left" valign="middle"> SEARCH RECORD: </td> <td width="144" align="center" valign="middle"> <input type="text" name="search" /> </td> <td width="56" align="left" valign="middle"> <input type="submit" name="btnSearch" value="Search" /> </td> </tr> </table> <br> <!-- End of search query--> <!-- Start of Search Results--> <table border="0" cellpadding="3" cellspacing="1" bordercolor="38619E" > <tr> <th width="80" align="center" bgcolor="#E0E8F3">Territory</th> <th width="330" align="center" bgcolor="#E0E8F3">Employer</th> <th width="160" align="center" bgcolor="#E0E8F3">Name</th> <th width="80" align="center" valign="middle" bgcolor="#E0E8F3"> </th> </tr> <?php if($result) { for($i=0; $i<mysql_num_rows($result); $i++) { $id = trim(mysql_result($result, $i, "id")); $territory = trim(mysql_result($result, $i, "territory")); $employer = trim(mysql_result($result, $i, "employer")); $first_name = trim(mysql_result($result, $i, "first_name")); $last_name = trim(mysql_result($result, $i, "last_name")); echo "<tr>"; echo "<td>".$territory."</td>"; echo "<td>".$employer."</td>"; echo "<td>".$last_name.", ".$first_name."</td>"; echo "<td><a href='edit_client.php?id=".$id."'>edit</a> | <a href='delete_client.php?id=".$id."'>delete</a></td>"; echo "</tr>"; } } ?> </table> </form> <!-- End of page --> </td> </tr> </table> </td> <tr> <td height="38"> <table width="760" border="0" cellpadding="0" cellspacing="0"> <td width="200" height="35" align="center" bgcolor="#1B1C78" class=white> <a href="disclaimer.html"> <font color="#FFFFFF">Legal Disclaimer</font> </a> </td> <td width="560" align="center" bgcolor="#0076CC"> Copyright © 2006 - 2010 Asia. All rights reserved. </td> </table></td> </tr> </table> Thank you very much, and I am looking forward for your responses. Thanks! Similar TutorialsHi All, I have a pagination script that works correctly when a user clicks on a category heading, however when I am using it to try an display search results it does not take into account the set of records to display per page, it just shows all results. <?php echo '<h3>Search Results</h3><br />'; $query = "SELECT count(*) from merchants WHERE name LIKE '%$_GET[q]%' OR short like '%$_GET[q]%' OR full like '%$_GET[q]%' OR keywords like '%$_GET[q]%'"; $row=mysql_fetch_assoc(mysql_query($query)); $total_records = $row['count(*)']; $records_per_page = 5; $total_pages = ceil($total_records / $records_per_page); $page = intval($p); if ($page < 1 || $page > $total_pages) $page = 1; $offset = ($page - 1) * $records_per_page; $limit = " LIMIT $offset, $records_per_page"; $query = mysql_query("SELECT * FROM merchants WHERE name LIKE '%$_GET[q]%' OR short like '%$_GET[q]%' OR full like '%$_GET[q]%' OR keywords like '%$_GET[q]%' ORDER BY m_id DESC") ; echo mysql_error() ; while($row = mysql_fetch_assoc($query)){ $name = $row['name']; $short = $row['short']; $per = $row['percent']; $m_id = $row['m_id']; ?> <div id="cbbox"> <a href="viewm.php?m_id=<?php echo $m_id;?>"> <div class="cbname"> <?php echo $name;?> - Up to <?php echo $per ;?>% Cashback Available </div> <div class="cbimage"> <img src="pimage/<?php echo $name;?>.gif" height="50px" width="100px" /> </div> <div class="cbshort"> <?php echo $short;?> </div> </a> <div class="cbtweet"> <a href="http://twitter.com/home/?status=Get up to <?php echo $per;?> percent Cashback on purchase from <?php echo $name;?> http://goo.gl/PLkp"><img src="images/cbtweet.png" width="90" height="50" alt="Tweet This" /></a> </div></div> <br /><br /> <?php } if($total_records > 5) { for ($i = 1; $i <= $total_pages; $i++) { echo "<a title='page $i p=$i'>Page $i - </a>"; } } ?> </div> if I echo out $total_records it displays the correct amount (7 in the case I am looking at) Any ideas? Hi Everyone,
I have a question about pagination. I have this code that I would like to incorporate into my php file.
This is said code that will be incorporated:
try { // Find out how many items are in the table $totalItems = $databaseHandle->query(' select count(*) from tableName ')->fetchColumn(); // Set how many items per page to display $limit = 10; // find how many pages are needed $totalPages = ceil($totalItems / $limit); // Find out which page we are on $currentPage = min($totalPages, 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); // "back" link $prevlink = ($page > 1) ? '<a href="?page=1" title="First page">«</a> <a href="?page=' . ($currentPage - 1) . '" title="Previous page">‹</a>' : '<span class="disabled">«</span> <span class="disabled">‹</span>'; // "forward" link $nextlink = ($page < $pages) ? '<a href="?page=' . ($page + 1) . '" title="Next page">›</a> <a href="?page=' . $totalPages . '" title="Last page">»</a>' : '<span class="disabled">›</span> <span class="disabled">»</span>'; // Display the paging information echo '<div id="paging"><p>', $prevlink, ' Page ', $currentPage, ' of ', $totalPages, ' pages, displaying ', $start, '-', $end, ' of ', $totalItems, ' results ', $nextlink, ' </p></div>'; // Get the results. Paged query $stmt = $databaseHandle->prepare(' select * from tableName order by name limit :limit offset :offset '); // Bind the query params $stmt->bindParam(':limit', $limit, PDO:: PARAM_INT); $stmt->bindParam(':offset', $offset, PDO:: PARAM_INT); $stmt->execute(); // Results? if ($stmt->rowCount() > 0) { $stmt->setFetchMode(PDO::FETCH_ASSOC); $iterator = new IteratorIterator($stmt); // Display the results foreach ($iterator as $row) { echo '<p>', $row['name'], '</p>'; } } else { echo '<p>No results could be displayed.</p>'; } } catch (Exception $e) { echo '<p>', $e->getMessage(), '</p>'; }and this is what is in my php file: <html> <head></head> <body> <?php if (!isset($_POST['q'])) { ?> <img src="/wvb-logo-slogen.png" border="0" /> <h2>Search</h2> <form method="post" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>"> <input type="text" name="q" size="30" /> </form> <?php } else { ?> <img src="/wvb-logo-slogen.png" border="0" /> <h2>Search Results</h2> <?php try { // create object // $swish = new Swish('/usr/local/apache/htdocs/swish/index.swish-e'); $swish = new Swish('/var/www/html/pdf2/index.swish-e'); // get and run query from command-line $queryStr = htmlentities($_POST['q']); $result = $swish->query($queryStr); ?> Found <?php echo $result->hits; ?> match(es) for '<?php echo $queryStr; ?>'. <?php // iterate over result set // print details for each match while($r = $result->nextResult()) { ?> <p> <?php echo $r->swishreccount; ?> <strong> <a href="<?php echo '/pdf2', ltrim($r->swishdocpath, '.') ; ?>"> <?php echo $r->swishdocpath; ?> </a> </strong> (sco <?php echo $r->swishrank; ?>) <br/> <?php echo $r->swishdocpath; ?><br /> <?php $file = '/var/www/html/active_colist.csv'; $fh = fopen($file, 'r'); $companies = array(); $row = fgetcsv($fh, 1024); // ignore header while ($row = fgetcsv($fh, 1024)) { $companies[$row[0]] = array('company' => $row[1], 'country' => $row[3]); //changed line } fclose($fh); //Split a filename by . $filenames = explode(".", $r->swishdocpath); //get 3 chars from $filenames to $country $wvb_number = substr($filenames[1],1,12); $country = substr($filenames[1],1,3); echo 'Country: '.$companies[$wvb_number]['country']."<br />"; //echo 'Country Name: '.$country."<br />"; //$filenames[2] = explode(".", $r->swishdocpath); $year = substr($filenames[2],0,4); echo 'Year: '.$year."<br />"; //$filenames = explode(".", $r->swishdocpath); //$wvb_number = substr($filenames[1],1,12); echo 'WVB Number: '.$wvb_number."<br />"; echo 'Company Name: '.$companies[$wvb_number]['company']; //echo 'Country: '.$companies[$wvb_number]['country']; ?> </p> <?php } } catch (Exception $e) { die('ERROR: ' . $e->getMessage()); } } ?> </body> </html>My question is what would be the best way incorporate this into my php file so that I am able to display a limit number link by page so that not all of the results are listed on the same page? If that is even possible. Need help to correct my cording! I want to limited search results by 5 items on one page.
Don't know how correctly to add limit: "limit $page1,5".
When I add it: $sql = "SELECT * FROM data GROUP BY city ORDER BY city limit $page1,5";
it doesn't limit searching result by pages.
Attached Files
search3.php 1.67KB
5 downloads HI, Please forgive my inexperience I am new to php and any help is most apreciated. I have a database called liveproj and a table named olde_history. Within the table, Project history is stored. Each project has a unique number ie 10383 etc. I am trying to display the results for an individual project once the project has been selected. The structure of the table is as such: $sql = 'CREATE TABLE IF NOT EXISTS `liveproj`.`olde_history` ( `History_Id` int(6) NOT NULL AUTO_INCREMENT, `History_Project_Id` varchar(10) NOT NULL, `History_Department_Id` varchar(25) NOT NULL, `History_By` varchar(25) DEFAULT NULL, `History_Contact` varchar(25) DEFAULT NULL, `History_Date` varchar(10) NOT NULL, `History_Description` varchar(500) DEFAULT NULL, `History_Action_Owner` varchar(25) DEFAULT NULL, `History_Status_Id` varchar(10) DEFAULT NULL, `History_Action_Date` varchar(10) DEFAULT NULL, `History_Action_Description` varchar(500) DEFAULT NULL, `History_Date_Resolved` varchar(10) DEFAULT NULL, `History_Email` varchar(150) DEFAULT NULL, `History_Minutes` varchar(150) DEFAULT NULL, `History_Visit` varchar(150) DEFAULT NULL, PRIMARY KEY (`History_Id`) )'; A snippet of the table structure I can View all information based on all projects and this works fine althoughh I only wish to display the relevent info for a selected project. The error code I get is as follows: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-10,10' at line 1 My code is: Code: [Select] <!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>Live Project List</title> <link href="../css/Style.css" rel="stylesheet" type="text/css" /> <style type="text/css"></style> </head> <body id="body"> <div align="center" id="Section">Project History List <div id="apDiv1"> <form id="form1" name="form1" method="post" action=""> <input type="text" name="Search" id="Search" size="20" /> <img src="../Images/search.png" width="24" height="24" align="middle" /> </form> </div> </div> <table class="hovertable"> <tr> <th width="10%">Date:</th> <th width="10%">By:</th> <th width="30%">History Description:</th> <th width="5%">Action Status:</th> <th width="5%">Action Owner:</th> <th width="10%">Action Rqd Date</th> <th width="10%">Action Description:</th> <th width="10%">Date Resolved:</th> <th width="5%">View:</th> <th width="5%">Edit:</th> </tr> <?php ############################################################################### # Start of pagination script ############################################################################### IF (ISSET($_GET['pageno'])) { $pageno = $_GET['pageno']; } ELSE { $pageno = 1; } // if ############################################################################### # 2. Identify how many database rows are available ############################################################################### # This code will count how many rows will satisfy the current query. session_start(); include "../scripts/connect.php"; include "../scripts/Inc/db_lp.php"; //$disc = $_SESSION['Disc']; $quote='"'; $projno2 = $_SESSION['Project']; $projno = "$quote$projno2$quote"; $query = "SELECT count(*) FROM `liveproj` . `olde_history` WHERE `History_Id` = '$projno'"; //$query = "SELECT count(*) FROM `liveproj` . `olde_history` WHERE `History_Id` <> ''"; //WORKING LINE $result = mysql_query($query) or die(mysql_error()); $query_data = MYSQL_FETCH_ROW($result); $numrows = $query_data[0]; PRINT "NUMROWS: $numrows<br>"; ############################################################################### # 3. Calculate number of $lastpage ############################################################################### # This code uses the values in $rows_per_page and $numrows in order to identify the number of the last page. $rows_per_page = 10; ######## Set the ammount of rows you wish to display per page ######### $lastpage = CEIL($numrows/$rows_per_page); ############################################################################### # 4. Ensure that $pageno is within range ############################################################################### # This code checks that the value of $pageno is an integer between 1 and $lastpage. $pageno = (int)$pageno; IF ($pageno < 1) { $pageno = 1; } ELSEIF ($pageno > $lastpage) { $pageno = $lastpage; } // if ############################################################################### # 5. Construct LIMIT clause ############################################################################### # This code will construct the LIMIT clause for the sql SELECT statement. $limit = 'LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page; ############################################################################### # 6. Issue the database query ############################################################################### # Now we can issue the database query and process the result. $query = "SELECT * FROM `liveproj` . `olde_history` $limit"; $result = mysql_query($query) or die(mysql_error()); #... process contents of $result ... WHILE ($row = MYSQL_FETCH_ARRAY($result)) { echo '<tr onmouseover="this.style.backgroundColor=\'#CCCCCC\';" onmouseout="this.style.backgroundColor=\'#ffffff\';"><td width="10%">'; echo $row["History_Date"]; echo "</td>"; echo '<td width="10%" >'; echo $row["History_By"]; echo "</td>"; echo '<td width="30%">'; echo "" . substr($row['History_Description'],0,20) . ".....[Select View To Read More]" ; //echo $row["History_Description"]; echo "</td>"; echo '<td width="5%">'; echo $row["History_Status_Id"]; echo "</td>"; echo '<td width="5%">'; echo $row["History_Action_Owner"]; echo "</td>"; echo '<td width="10%">'; echo $row["History_Action_Date"]; echo "</td>"; echo '<td width="10%">'; //echo $row["History_Action_Description"]; echo "" . substr($row['History_Action_Description'],0,20) . ".....[Select View To Read More]" ; echo "</td>"; echo '<td width="10%">'; echo $row["History_Date_Resolved"]; echo "</td>"; echo '<td width="5%">'; echo "<div class=form>"; echo '<form id="form" name="form" method="post" action="Doc_History_Desc.php" onSubmit="return confirm('; echo '">'; echo '<input type="hidden" name="histid" value="'; echo $row["History_Id"]; echo '"><input type="image"SRC="../Images/Icons/List-View.png" Height="22" Width="22" value="View" alt="submit" class="hidebutton" name="B1">'; //echo '"><input type="submit" value="View" name="B1">'; echo "</form>"; echo "</td>"; echo '<td width="5%">'; echo "<div class=form>"; echo '<form id="form" name="form" method="post" action=".php" onSubmit="return confirm('; echo '">'; echo '<input type="hidden" name="histid" value="'; echo $row["History_Id"]; echo '"><input type="image"SRC="../Images/Icons/List-Edit.png" Height="22" Width="22" value="View" alt="submit" class="hidebutton" name="B1">'; //echo '"><input type="submit" value="View" name="B1">'; echo "</form>"; echo "</td>"; echo "</tr>"; } ?> </table> <p><br /> <br /> </p> <?php ############################################################################### # 7. Construct pagination hyperlinks ############################################################################### # Finally we must construct the hyperlinks which will allow the user to select # other pages. We will start with the links for any previous pages. echo '<div align="center" id="SectionEnd">'; IF ($pageno == 1) { echo "<font size='1' color='#FFFFFF'>FIRST | PREV</font>"; } ELSE { echo " <a href='{$_SERVER['PHP_SELF']}?pageno=1'>FIRST</a>"; $prevpage = $pageno-1; echo " <a href='{$_SERVER['PHP_SELF']}?pageno=$prevpage'>PREV</a>"; } // if # Next we inform the user of his current position in the sequence of available pages. echo " <font size='1' color='#FFFFFF'>( Page $pageno of $lastpage )</font> "; # This code will provide the links for any following pages. IF ($pageno == $lastpage) { echo "<font size='1' color='#FFFFFF'>NEXT | LAST</font>"; } ELSE { $nextpage = $pageno+1; echo " <a href='{$_SERVER['PHP_SELF']}?pageno=$nextpage'>NEXT</a>"; echo " <a href='{$_SERVER['PHP_SELF']}?pageno=$lastpage'>LAST</a>"; } // if echo'<br/>'; echo'<br/>'; echo'</div>'; ############################################################################### # End of pagination script ############################################################################### ?> </body> </html> Thankyou in advance. Hello, I'm developing a website that asks the user to submit a keyword for a search. The results should display matches for this keyword, but also show matches for related keywords (in order of relevenace!). I'm planning on building up a library of which search terms users use in the same sessions (e.g. if someone searches for "it jobs" and "php jobs", I'll know the terms are correlated), and I'll also measure the click-through rates of the items on the results list. I've been spending all weekend trying to map out the design for this but it's proving incredibly complicated and I think the solution is likely to be on the internet somewhere already?! Please could someone point me in the right direction if you've come accross this problem before? Thanks a million, Stu I would like to know what is the best method (the most intelligent and comfortable for users) to paginate a result table with PHP/MySQL? Provided I have a result set of 100 pages. Method 1: <select> <option>1</option> .... </select> Method 2: Link on Page 1, 2, 3 ... 100 If there is any algorithm with PHP for automated these displays, please demonstrate it. I want visitors to be able to sort the results on my Browse Documentaries page by popularity, date, and type. The only way I know how to do this is to create a separate page for each sorting arrangement and provide a link to each page. Is there any way of doing it on a single page?
I am guessing that I can do things like that with Javascript or jQuery. Is that correct?
Hey Guys, In this portion of my code I have tried to implement pagination, as the results try to display a page with over 100 mp3's with flash players on teh page, and of course the page just dies. However my attempt at pagination isnt actually working. can anyone help this noob? <? // how many rows to show per page $rowsPerPage = 20; // by default we show first page $pageNum = 1; // if $_GET['page'] defined, use it as page number if(isset($_GET['page'])) { $pageNum = $_GET['page']; } // counting the offset $offset = ($pageNum - 1) * $rowsPerPage; $query = " SELECT val FROM ax_music " . " LIMIT $offset, $rowsPerPage"; $result = mysql_query($query) or die('Error, query failed'); // print the random numbers while($row = mysql_fetch_array($result)) { echo $row['val'] . '<br>'; } $row2 = mysql_query("SELECT * FROM ax_music ORDER BY 'sort' ASC"); while($row = mysql_fetch_array($row2)){ ?> <tr> <td><?=$row[title];?></td> <td> <embed src= "musicplayer2.swf" quality="high" width="300" height="52" allowScriptAccess="always" wmode="transparent" type="application/x-shockwave-flash" flashvars= "valid_sample_rate=true&external_url=./music/<?=$row[mp3];?>" pluginspage="http://www.macromedia.com/go/getflashplayer"> </embed> </td> <td> <? if($row[visible] == 0){ echo "<strong>Not Playlisted</strong><br /> <a href=\"index.php?page=musicplayer&showid=$row[id]\">Add To Playlist</a>"; }else{ echo "<strong>Playlisted</strong><br /> <a href=\"index.php?page=musicplayer&hideid=$row[id]\">Remove From Playlist</a>"; } ?> </td> <td><a href="index.php?page=musicplayer&deleteid=<?=$row[id];?>"><strong>Delete</strong></a></td> <td><a href="./music/<?=$row[mp3];?>"><strong>Download</strong></a></td> </tr> <? } ?> </table> i have built pages that paginate with 10 rows per page (some pages show more but for the moment i want to focus on this particular page)
//Define Some Options for Pagination $num_rec_per_page=10; if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; }; $start_from = ($page-1) * $num_rec_per_page; $results = mysql_query("SELECT * FROM `ecmt_memberlist` WHERE toonCategory='Capital' AND oldMember = 0 ORDER BY CONCAT(MainToon, Name) LIMIT $start_from, $num_rec_per_page") or die(mysql_error()); $results_array = array(); while ($row = mysql_fetch_array($results)) { $results_array[$row['characterID']] = $row; }The above sets the variables for the pagination and below the results are echo with 10 rows per page then i show the pagination links: <?php $sql = "SELECT * FROM `ecmt_memberlist` WHERE toonCategory='Capital' AND oldMember = 0 ORDER BY CONCAT(MainToon, Name)"; $rs_result = mysql_query($sql); //run the query $total_records = mysql_num_rows($rs_result); //count number of records $total_pages = ceil($total_records / $num_rec_per_page); ?> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center"><div style="width:100%; text-align:center;"> <ul class="pagination"> <li class="selected"> <?php echo "<a href='capitalmember.php?page=1'>".'«'."</a> ";?> </li> <? for ($i=1; $i<=$total_pages; $i++) { echo "<li><a href='capitalmember.php?page=".$i."'>".$i."</a></li> "; }; ?> <li class="selected"> <? echo "<a href='capitalmember.php?page=$total_pages'>".'»'."</a> "; // Goto last page ?></li> </ul></div> <?php $pageNr = $page; // Get Current Page Number $from = $pageNr * $rowsPerPage; // 3 * 10 = 30 // 3 * 10 = 30 $to = $from + $rowsPerPage; // 30 + 10 = 40 echo $pageNr; /* Result: From page 30 to 40 */ ?></td> </tr> </table>this works great and shows me 10 results per page, what i need to work out and work on next is: echo the number of results above the records (for example: "showing records 1 to 10" and then on page 2 "showing records 11 to 21" and page 3 "showing records 22 to 32" how can i work out the maths for this echo? i was thinking along the lines of; <?php $pageNr = $page; // Gets Current Page Number $from = $pageNr * $rowsPerPage; // 3 * 10 = 30 $to = $from + $rowsPerPage; // 30 + 10 = 40 // Now Show Results echo $from; // Echo from echo $to // Echo to ?>but i'm still working on this.. then i need to look at shortening the amount of page links on the page if for example i have 500 records it shows me links 1 to 50 and eats up the page.... Appreciate any help and light onto my problems. Many thanks Edited by jacko_162, 11 January 2015 - 05:43 PM. Hi experts, need some assistance please. I have a search code that works great and posts the information just the way it should but the problem is when I try to go to the next page it loads an empty page even though there is more to show. The next page link seems to be correct it just is not working. Here is my code, will someone please look at it and give some advice? Thank you in advance. Code: [Select] elseif ((select($page) == 'city')){ echo '<div class="city_search"> <h1>Search by State</h1> <form method="post" action="index.php?content=locations§ion=city_search"> State: <select name="id">'; echo '<option value="" selected="selected" disabled="disabled">Select a State</option>'; $result = mysql_query("SELECT * FROM state") or die(mysql_error()); while($row = mysql_fetch_array( $result )) { echo '<option value="'.$row['id'].'">'.$row['state'].'</option>'; } echo '</select><input type="submit" name="search" value="Search"></form>'; echo '</div>'; } elseif ((select($page) == 'city_search')){ // $id = $_POST['id']; // $state_id = $_POST['state_id']; if(isset($_POST['search'])){ $id = $_POST['id']; $state_id = $_POST['state_id']; echo $state_id; echo '<center>'; $per_page = 20; $pages_query = mysql_query("SELECT COUNT(id) AS tot FROM city WHERE state_id='$id'"); $pages = ceil(mysql_result($pages_query, 0) / $per_page); $page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1; $start = ($page -1) * $per_page; $query = mysql_query("select * from city WHERE state_id='$id' LIMIT $start, $per_page"); echo '<div class="pag"> <a href="index.php?content=locations§ion=city_add">Add City</a><br><br>'; $totalres = mysql_result(mysql_query("SELECT COUNT(id) AS tot FROM city where state_id='$id'"),0); echo "Number of Cities Found:<font color=\"red\"><b> ".$totalres. "</b></font><br><br>"; if ($pages >= 1 && $page <=$pages) { for ($x=1; $x<= $pages; $x++) { echo ($x == $page) ? '<strong><a href="index.php?content=locations§ion=city_search&state_id='.$id.'&page='.$x.'">'.$x.'</a></strong> | ' : '<a href="index.php?content=locations§ion=city_search&state_id='.$id.'&page='.$x.'">'.$x.'</a> | '; ; } } echo '</div>'; echo '<div class="city_cont"> <div class="city_cols"> <div class="list_id">ID</div> <div class="list_name">Country</div> <div class="list_name">State</div> <div class="list_name">City</div> <div class="list_edit">Edit</div> <div class="list_del">Delete</div> </div>'; while ($row = mysql_fetch_array($query)) { $id = $row['id']; $country_id = $row['country_id']; $state_id = $row['state_id']; $city = $row['city']; echo '<div class="city_cols"> <div class="list_id">' .$row['id'] .'</div>'; echo '<div class="name">'; $sql1 = mysql_query("SELECT * from country WHERE id='$country_id'"); $row = mysql_fetch_array( $sql1 ); echo $row['country']; echo '</div>'; echo '<div class="name">'; $sql2 = mysql_query("SELECT * from state WHERE id='$state_id'"); $row = mysql_fetch_array( $sql2 ); echo $row['state']; echo '</div>'; echo ' <div class="name">' .$city . '</div> <div class="edit"><a href="index.php?content=locations§ion=city_edit&id='.$id.'"><img src="images/edit.png" border="0"></a></div> <div class="delete"><a href="index.php?content=locations§ion=city_delete&id='.$id.'"><img src="images/delete.png" height="16" width="16" border="0"></a></div></div>'; } print_r($_POST); if ($pages >= 1 && $page <=$pages) { for ($x=1; $x<= $pages; $x++) { echo ($x == $page) ? '<strong><a href="index.php?content=locations§ion=city_search&state_id='.$state_id.'&page='.$x.'">'.$x.'</a></strong> | ' : '<a href="index.php?content=locations§ion=city_search&state_id='.$state_id.'&page='.$x.'">'.$x.'</a> | '; ; } } echo '</div></center>'; } } So basically, what happens here now is that the search query and the pagination now somehow works with each other. Each time I search for a key word, it displays the information perfectly, with pagination. However, even if the keyword I looked for has only 2 information, a second page is available for click, and when I try to click, it leads me to a page of blank information. Similarly, if I search for an information that should display huge amount of data, it displays pagination, but displays no information if I click on the second page. What could the reason be behind this? Immediate response is very much appreciated. Thanks! <link href="add_client.css" rel="stylesheet" type="text/css"> <?PHP include("dbconnection.php"); //database connection $query = "SELECT * FROM records"; ?> <!-- Start of table --> <table width="760" border="0" align="center" cellpadding="0" cellspacing="0"> <td> <table width="760" border="0" cellpadding="0" cellspacing="0"> <!-- Table data containing the Logo --> <td width="199" align="center" valign="top"> <a href="login.html"> <img src="asia.gif" alt="" width="152" height="58" border="0" /> </a> </td> <!-- Table data containing Home button --> <td width="176" align="right" valign="bottom"> <a href="main.php"> <img src="Home.jpg" width="104" height="20" border="0"/> </a> </td> <!-- Table data containing View Client button --> <td width="130" align="right" valign="bottom"> <img src="View.jpg" width="104" height="20" border="0"/> </td> <!-- Table data containing the Add Client button --> <td width="146" align="right" valign="bottom"> <a href="add_client.php"> <img src="Add.jpg" width="104" height="20" border="0"/> </a> </td> <!-- Blank table data --> <td width="109" align="right" valign="bottom"> </td> </table> <!-- Table design division and body--> <table width="760" border="0" cellpadding="0" cellspacing="0"> <td width="200" height="3" bgcolor="#1B1C78"> <img src="images/topspacerblue.gif" alt="" width="1" height="3" /></td> <td width="560" bgcolor="#0076CC"> <img src="images/topspacerlblue.gif" alt="" width="1" height="3" /></td> <tr> <td height="500" colspan="2" align="center" valign="top" bgcolor="#F3FAFE"> <!-- Page contents --> <!-- Search Query --> <br> <form name="form" action="view_client.php" method="post"> <table width="351" border="0"> <tr> <td width="137" align="left" valign="middle"> SEARCH RECORD: </td> <td width="144" align="center" valign="middle"> <input type="text" name="search" /> </td> <td width="56" align="left" valign="middle"> <input type="submit" name="btnSearch" value="Search" /> </td> </tr> </table> <br> <!-- End of search query--> <!-- Start of Search Results--> <table border="0" cellpadding="3" cellspacing="1" bordercolor="38619E" > <tr> <th width="80" align="center" bgcolor="#E0E8F3">Territory</th> <th width="330" align="center" bgcolor="#E0E8F3">Employer</th> <th width="160" align="center" bgcolor="#E0E8F3">Name</th> <th width="80" align="center" valign="middle" bgcolor="#E0E8F3"> </th> </tr> <?php //max displayed per page $per_page = 15; //get start variable $start = $_GET['start']; //count records $record_count = mysql_num_rows(mysql_query("SELECT * FROM records")); //count max pages $max_pages = $record_count / $per_page; //may come out as decimal if (!$start) $start = 0; //display data via search query if(isset($_POST["btnSearch"])) { $get = mysql_query("SELECT * FROM records WHERE last_name LIKE '%".$_POST["search"]."%' OR first_name LIKE '%".$_POST["search"]."%'OR territory LIKE '%".$_POST["search"]."%'OR job_title LIKE '%".$_POST["search"]."%'OR title LIKE '%".$_POST["search"]."%'OR employer LIKE '%".$_POST["search"]."%' ORDER BY territory ASC LIMIT $start, $per_page"); while ($row = mysql_fetch_assoc($get)) // get data { $id = trim($row['id']); $territory = trim($row['territory']); $employer = trim($row['employer']); $last_name = trim($row['last_name']); $first_name = trim($row['first_name']); echo "<td>".$territory."</td>"; echo "<td>".$employer."</td>"; echo "<td>".$last_name.", ".$first_name."</td>"; echo "<td><a href='edit_client.php?id=".$id."'>edit</a> | <a href='delete_client.php?id=".$id."'>delete</a></td>"; echo "<tr>"; } //setup prev and next variables $prev = $start - $per_page; $next = $start + $per_page; //show prev button if (!($start<=0)) echo "<a href='view_client.php?start=$prev'>Prev</a> "; //show page numbers //set variable for first page $i=1; for ($x=0;$x<$record_count;$x=$x+$per_page) { if ($start!=$x) echo " <a href='view_client.php?start=$x'>$i</a> "; else echo " <a href='view_client.php?start=$x'><b>$i</b></a> "; $i++; } //show next button if (!($start>=$record_count-$per_page)) echo " <a href='view_client.php?start=$next'>Next</a>"; } ?> </table> </form> <!-- End of page --> </td> </tr> </table> </td> <tr> <td height="38"> <table width="760" border="0" cellpadding="0" cellspacing="0"> <td width="200" height="35" align="center" bgcolor="#1B1C78" class=white> <a href="disclaimer.html"> <font color="#FFFFFF">Legal Disclaimer</font> </a> </td> <td width="560" align="center" bgcolor="#0076CC"> Copyright © 2006 - 2010 Limited. All rights reserved. </td> </table></td> </tr> </table> I've got a page with pagination set up, but I can't figure out where I went wrong with the links at the bottom. When I do a search, it generates the proper number of links, but clicking on the links goes to a page with a whole row of 20 links at the bottom and no results on the page. (my search should show 3 pages with 2 records on each page) I've looked through the tutorial here and one in a book on pagination. Not seeing what's wrong. I'd narrow this down if I knew where it was causing the problem. pagination links are at the very bottom of the code. Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html><head> <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"><title>search.html</title></head> <body> <center> <p>The results of your search:</p> <br> </center> require ('databaseconnect.php'); $select = mysql_select_db($db, $con); if(!$select){ die(mysql_error()); } $display = 2; if (isset($_GET['np'])) { $num_pages = $_GET['np']; } else { $data = "SELECT COUNT(*) FROM descriptors LEFT JOIN plantae ON (descriptors.plant_id = plantae.plant_name) WHERE `leaf_shape` LIKE '%$select1%' AND `leaf_venation` LIKE '%$select3%' AND `leaf_margin` LIKE '%$select4%'"; $result = mysql_query ($data); if (!$result) { die("Oops, my query failed. The query is: <br>$data<br>The error is:<br>".mysql_error()); } $row = mysql_fetch_array($result, MYSQL_NUM); // row 41 $num_records = $row[0]; if ($num_records > $display) { $num_pages = ceil ($num_records/$display); } else { $num_pages = 1; } } if (isset($_GET['s'])) { $start = $_GET['s']; } else { $start = 0; } if(isset($_POST[submitted])) { // Now collect all info into $item variable $shape = $_POST['select1']; $color = $_POST['select2']; $vein = $_POST['select3']; $margin = $_POST['select4']; // This will take all info from database where row tutorial is $item and collects it into $data variable row 55 $data = mysql_query("SELECT `descriptors`.* ,`plantae`.* FROM `descriptors` LEFT JOIN `plantae` ON (`descriptors`.`plant_id` = `plantae`.`plant_name`) WHERE `leaf_shape` LIKE '%$select1%' AND `leaf_venation` LIKE '%$select3%' AND `leaf_margin` LIKE '%$select4%' ORDER BY `plantae`.`scientific_name` ASC LIMIT $start, $display"); //chs added this in... row 72 echo '<table align="center" cellspacing="0" cellpading-"5"> <tr> <td align="left"><b></b></td> <td align="left"><b></b></td> <td align="left"><b>Leaf margin</b></td> <td align="left"><b>Leaf venation</b></td> </tr> '; // This creates a loop which will repeat itself until there are no more rows to select from the database. We getting the field names and storing them in the $row variable. This makes it easier to echo each field. while($row = mysql_fetch_array($data)){ echo '<tr> <td align="left"> <a href="link.php">View plant</a> </td> <td align="left"> <a href="link.php">unknown link</a> </td> <td align="left">' . $row['scientific_name'] . '</td> <td align="left">' . $row['common_name'] . '</td> <td align="left">' . $row['leaf_shape'] . '</td> </tr>'; } echo '</table>'; } if ($num_pages > 1) { echo '<br /><p>'; $current_page = ($start/$display) + 1; // row 100 if ($current_page != 1) { echo '<a href="leafsearch2a.php?s=' . ($start - $display) . '&np=;' . $num_pages . '">Previous</a> '; } for ($i = 1; $i <= $num_pages; $i++) { if($i != $current_page) { echo '<a href="leafsearch2a.php?s=' . (($display * ($i - 1))) . '$np=' . $num_pages . '">' . $i . '</a>'; } else { echo $i . ' '; } } if ($current_page != $num_pages) { echo '<a href="leafsearch2a.php?s=' . ($start + $display) . '$np=' . " " . $num_pages . '"> Next</a>'; } } ?> </body></html> Hi, my page is currently up at brewhas.org/transactions.php. When I retrieve a set of results > the defined # per page (such as entering 'WI' for last name), I see the first page correctly, and see the links to next pages, but when I go to the next page there are no results displayed. Same for p.3, etc. So I've looked around enough to know that I need to pass a variable to the subsequent pages, either via a session variable or the URL. I have 2 fields input on the form, as well as a limit and offset. My questions are 1) do I need to pass all 4 and if so then should I use a session variable so the URL does not get too long, and 2) can anyone provide any help with setting session variables and including them to be passed? I'm a newbie and have grabbed some code where I can but this is where i'm stuck. thanks in advance. Code: [Select] <?php include 'config.php'; include 'opendb.php'; $rows_per_page = 20; //Get the values from the text boxes $fnamesearch = $_POST["fnamesearch"]; $lnamesearch = $_POST["lnamesearch"]; //These trim and convert the name fields to upper case. $fnamesearch=strtoupper($fnamesearch); $lnamesearch=strtoupper($lnamesearch); $fnamesearch=trim($fnamesearch); $lnamesearch=trim($lnamesearch); // Count how many rows are coming back for the query //This checks to see if there are at least 2 chars in the last name. if (strlen($lnamesearch)<2) { echo "<p class='style7'>Please enter at least 2 letters of the last name.</p>"; exit; } else //sets the query to get the number of rows { $query = "SELECT COUNT(*) FROM BKL_TRANSACTIONS WHERE((PLAYER_LNAME LIKE '$lnamesearch%')& (PLAYER_FNAME LIKE '$fnamesearch%'))"; } $result = mysql_query($query) or die ("Could not execute the query"); //executes the get count query $query_data = mysql_fetch_row($result); $numrows = $query_data[0]; echo "count: ".$numrows; $lastpage = ceil($numrows/$rows_per_page); //determines how many pages based on rows divided by rows per page echo "pages: ".$lastpage; // Get required page number. If not present, default to 1. if (isset($_GET['pageno']) && is_numeric($_GET['pageno'])) {$pageno = $_GET['pageno']; } else {$pageno = 1; } //Checks that the value of $pageno is an integer between 1 and $lastpage. $pageno = (int)$pageno; if ($pageno > $lastpage) {$pageno = $lastpage; } if ($pageno < 1) {$pageno = 1; } //constructs OFFSET for the sql SELECT statement $offset = ($pageno - 1) * $rows_per_page; //This checks to see if there are at least 2 chars in the last name. if (strlen($lnamesearch)<2) { echo "<p class='style7'>Please enter at least 2 letters of the last name.</p>"; exit; } else //sets the query to get the number of rows { $query = "SELECT * FROM BKL_TRANSACTIONS WHERE((PLAYER_LNAME LIKE '$lnamesearch%')& (PLAYER_FNAME LIKE '$fnamesearch%')) LIMIT $offset, $rows_per_page"; } $result = mysql_query($query) or die ("Could not execute the query"); //executes the query //Count the number of results $numrows=mysql_num_rows($result); echo "<p class='style7'>Your search: "".$fnamesearch." ".$lnamesearch."" returned <b>".$numrows."</b> results.</p>"; if ($numrows == 0) //if no matches, don't display the table exit; else //build the table and insert rows { echo "<table border=1 cellspacing=0 cellpadding=1 width='77%' align=left bordercolor=#666666>"; echo "<tr bgcolor=#cccc99 class='style5'><th width='10%' class='style5'>Date</th>"; echo "<th width='10%' class='style5'>Action</th>"; echo "<th width='12%' class='style5'>From</th>"; echo "<th width='12%' class='style5'>To</th>"; echo "<th width='5%' class='style5'>Pos</th>"; echo "<th width='18%' class='style5'>Name</th>"; echo "<th width='5%' class='style5'>Round</th></tr>"; while ($row = mysql_fetch_array($result)) { echo "<tr><td width='10%' class='style6'>".$row['TRANS_DT']."</td>"; echo "<td width='10%' class='style6'>".$row['TRANS_ACTION']."</td>"; echo "<td width='12%' class='style6'>".$row['FROM_OWNER']."</td>"; echo "<td width='12%' class='style6'>".$row['TO_OWNER']."</td>"; echo "<td width='5%' class='style6'>".$row['POSITION']."</td>"; echo "<td width='18%' class='style6'>".$row['PLAYER_FNAME']." ".$row['PLAYER_LNAME']."</td>"; echo "<td width='5%' class='style6'>".$row['DRAFT_RND']."</td></tr>"; } /****** build the pagination links ******/ // if not on page 1, don't show back links if ($pageno > 1) { // show << link to go back to page 1 echo " <a href='{$_SERVER['PHP_SELF']}?pageno=1'><<</a> "; // get previous page num $prevpage = $pageno - 1; // show < link to go back to 1 page echo " <a href='{$_SERVER['PHP_SELF']}?pageno=$prevpage'><</a> "; } // range of num links to show $range = 3; // loop to show links to range of pages around current page for ($x = ($pageno - $range); $x < (($pageno + $range) + 1); $x++) { // if it's a valid page number... if (($x > 0) && ($x <= $lastpage)) { // if we're on current page... if ($x == $pageno) { // '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']}?pageno=$x'>$x</a> "; } // end else } // end if } // if not on last page, show forward and last page links if ($pageno != $lastpage) { // get next page $nextpage = $pageno + 1; // echo forward link for next page echo " <a href='{$_SERVER['PHP_SELF']}?pageno=$nextpage'>></a> "; // echo forward link for lastpage echo " <a href='{$_SERVER['PHP_SELF']}?pageno=$lastpage'>>></a> "; } // end if /****** end build pagination links ******/ echo "</table>"; } mysql_free_result($result); //release the result set from the table mysql_close($conn); //close the connection to the db ?> MOD EDIT: [code] . . . [/code] tags added. I have more than 1000 records in my database and while displaying i use Pagination with search criteria. Actually When i give search criteria, its displays defined number of records from database, defined in the same file thru pagination. It shows 2,3,4... number with links. But when i click on 2nd page , it goes to 2nd page but again we need to provide search criteria.
I wan this to display without search criteria.
My code is like this
<?php if(isset($_GET['page'])){ $page=$_GET['page']; } else { $page=1; } $start_page=($page-1)*20; if(isset($_POST['search'])) { $stud_id=$_POST['stud_id']; $stud_name=$_POST['stud_name']; $class=$_POST['class']; $section=$_POST['section']; $session=$_POST['session']; if(isset($_POST['search']) && ($_POST['stud_id']!='')) { $sql="select * from student where enroll_no LIKE '".$stud_id."%' "; } elseif(isset($_POST['search']) && ($_POST['stud_name']!='')) { $sql="select * from student where stud_name LIKE '".$stud_name."%' "; } elseif(isset($_POST['search']) && ($_POST['class']!='') && ($_POST['section']!='')) { $sql="select * from student where class LIKE '".$class."%' AND section LIKE '".$section."%' "; } elseif(isset($_POST['search']) && ($_POST['class']!=='')) { echo "Please select section along with class"; } elseif(isset($_POST['search'])) { $sql="select * from student limit $start_page,20"; } } $query=mysql_query($sql); ?> <div class="container"> <div class="row-fluid"> <div class="span12"> <div class="w-box"> <div class="w-box-header"> <h4>Student List</h4> </div> <div class="w-box-content"> <form method="post" action="" > <div class="formSep"><input type="text" name="stud_id" id="stud_id" value="" placeholder="Enroll No" /> <input type="text" name="stud_name" id="stud_name" value="" placeholder="Student Name"/> <select name="class" id="class"> <option value=""> CLASS </option> <option value="Nursery">Nursery</option> <option value="LKG">LKG</option> <option value="UKG">UKG</option> <option value="I">I</option> <option value="II">II</option> <option value="III">III</option> <option value="IV">IV</option> <option value="V">V</option> <option value="VI">VI</option> <option value="VII">VII</option> <option value="VIII">VIII</option> <option value="IX">IX</option> <option value="X">X</option> <option value="XI">XI</option> <option value="XII">XII</option> </select> <select name="section" id="section"><option value=""> SECTION </option> <option value="A">A</option> <option value="B">B</option> <option value="C">C</option> <option value="D">D</option> </select> <input type="submit" name="search" id="search" value="Search" class="btn btn-info" /> </div> </form> </div> </div> <div class="w-box w-box-blue"> <div class="w-box-header"> <h4>Student List</h4> </div> <div class="w-box-content"> <?php $count=mysql_num_rows($query); if($count==0) { echo "<h2>SORRY NONE OF THE RECORD FOUND IN TABLE</h2>"; } else { echo "<table id='dt_hScroll' class='table table-striped'>"; echo "<thead><tr><th>Enroll No</th><th>Student Name</th><th>Photo</th><th>Class</th><th>Class Teacher</th><th>Section</th><th>Emergency Contact</th></tr> </thead>"; $i=0; while($row=mysql_fetch_array($query)) { if($i == 1) { echo '<tr class="EvenTableRows">'; $i=0; } else { echo '<tr class="OddTableRows">'; $i = 1; } ?> <td><?php echo $row['enroll_no']; ?></td> <td><a href="edit_student.php?enroll_no=<?php echo $row['enroll_no']; ?>"><?php echo $row['stud_name']; ?></a></td> <td><img src="<?php echo '../'.$row['stud_photo']; ?>" width="50px" height="50px" /></td> <td><?php echo $row['class']; ?></td> <td> <?php } } ?> </tbody></table> </div> </div> <?php $sql1="select COUNT(id) from student"; $rs_result = mysql_query($sql1); $row1 = mysql_fetch_row($rs_result); $total_records = $row1[0]; $total_pages = ceil($total_records / 20); if ($page > $total_pages) { // set current page to last page $page = $total_pages; } // end if // if current page is less than first page... if ($page < 1) { // set current page to first page $page = 1; } // end if $range=4; echo "<div style='float:left; width:200px;text-align:center; margin-left:40%;'>"; // echo "<a href='view_student.php?page=".$i."'>".$i."</a> "; if ($page > 1) { // show << link to go back to page 1 echo " <a href='{$_SERVER['PHP_SELF']}?page=1'>First</a> "; // get previous page num $prevpage = $page - 1; // show < link to go back to 1 page echo " <a href='{$_SERVER['PHP_SELF']}?page=$prevpage'>Previous</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 " [<b>$x</b>] "; // if not current page... } else { // make it a link echo " <a href='{$_SERVER['PHP_SELF']}?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 $nextpage = $page + 1; // echo forward link for next page echo " <a href='{$_SERVER['PHP_SELF']}?page=$nextpage'>Next</a> "; // echo forward link for lastpage echo " <a href='{$_SERVER['PHP_SELF']}?page=$total_pages'>Last</a> "; } // end if echo "</div>"; ?>how can i make it , please suggest 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
I have a website I am attempting to display searchable results in 25-row pages. The database has over 30k rows in it. All text nothing fancy, 3 columns, ID Title and Artist. Basically a songlist. With “The Code That Works”, when I load index.php, I get ALL 30k+ rows displayed, even with the limits defined. With the code that doesn’t work, I can’t get the search function to populate results. Here’s a copy of recent errors in error.log with “The Code That Works” [31-Dec-2019 22:36:11 UTC] PHP Warning: mysqli_query() expects at least 2 parameters, 1 given in /home/musicso1/karaoke.musicsoundlife.com/index.php on line 31 [31-Dec-2019 22:36:11 UTC] PHP Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in /home/musicso1/karaoke.musicsoundlife.com/index.php on line 31 [31-Dec-2019 22:36:11 UTC] PHP Warning: Use of undefined constant num - assumed 'num' (this will throw an Error in a future version of PHP) in /home/musicso1/karaoke.musicsoundlife.com/index.php on line 32 [31-Dec-2019 22:36:11 UTC] PHP Notice: Undefined index: page in /home/musicso1/karaoke.musicsoundlife.com/index.php on line 37 Here’s the code that works: <?php $localhost = ""; $username = "rsearch"; $password = ""; $dbname = "ke"; $con = new mysqli($localhost, $username, $password, $dbname); if( $con->connect_error){ die('Error: Connection' . $con->connect_error); } $sql = "SELECT * FROM `TABLE 1`"; if( isset($_GET['search']) ){ $name = mysqli_real_escape_string($con, htmlspecialchars($_GET['search'])); $sql = "SELECT * FROM `TABLE 1` WHERE (`Title` LIKE '%$name%') OR (`Artist` LIKE '%$name%') LIMIT 25"; } $result = $con->query($sql) or die('Could Not Search Database' . $con->error); ?> <!DOCTYPE HTML> <html> <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="title" content="Catalog"> <meta name="description" content=""> <meta name="keywords" content=""> <meta name="robots" content="index, follow"> <meta name="language" content="English"> <meta name="revisit-after" content="15 days"> <meta name="author" content=""> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" /> <link rel="stylesheet" href="main.css" /> <link rel="stylesheet" href="bootstrap.min.css"> <noscript><link rel="stylesheet" href="noscript.css" /></noscript> <script type="text/javascript"> function mousehandler(e) { var myevent = (isNS) ? e : event; var eventbutton = (isNS) ? myevent.which : myevent.button; if ((eventbutton == 2) || (eventbutton == 3)) return false; } document.oncontextmenu = mischandler; document.onmousedown = mousehandler; document.onmouseup = mousehandler; function disableCtrlKeyCombination(e) { var forbiddenKeys = new Array("a", "s", "c", "x", "u"); var key; var isCtrl; if (window.event) { key = window.event.keyCode; //IE if (window.event.ctrlKey) isCtrl = true; else isCtrl = false; } else { key = e.which; //firefox if (e.ctrlKey) isCtrl = true; else isCtrl = false; } if (isCtrl) { for (i = 0; i < forbiddenKeys.length; i++) { //case-insensitive comparation if (forbiddenKeys[i].toLowerCase() == String.fromCharCode(key).toLowerCase()) { return false; } } } return true; } </script> </head> <body oncontextmenu="return false" class="is-preload"> <div id="wrapper"> <nav id="nav"></nav> <div id="main"> <article id="contact" class="panel"> <header> <h2>Search Catalog</h2> <p>Updated as of 12/31/2019</p> </header> <div class="row"> <div class="container"> <form action="" method="GET"> <input type="text" placeholder="Search by Song Title or Artist" name="search"> <input type="submit" value="Search" name="btn" class="btn btn-sm btn-primary"> </form> <hr /> <h2>Search Results</h2> <table class="table table-striped table-bordered"> <tr> <th style='width:50px;'><strong>Title</strong></th> <th style='width:150px;'><strong>Artist</strong></th> </tr> <?php while($row = $result->fetch_assoc()){ ?> <tr> <th><?php echo $row['Title']; ?></th> <th><?php echo $row['Artist']; ?></th> </tr> <?php } ?> </table> <table class="table table-striped table-bordered"> <thead> <h2> Catalog</h2> </thead> <tbody> <?php if (isset($_GET['page_no']) && $_GET['page_no']!="") { $page_no = $_GET['page_no']; } else { $page_no = 1; } $total_records_per_page = 15; $offset = ($page_no-1) * $total_records_per_page; $previous_page = $page_no - 1; $next_page = $page_no + 1; $adjacents = "2"; $result_count = mysqli_query($con,"SELECT COUNT(*) As total_records FROM `TABLE 1`"); $total_records = mysqli_fetch_array($result_count); $total_records = $total_records['total_records']; $total_no_of_pages = ceil($total_records / $total_records_per_page); $second_last = $total_no_of_pages - 1; // total page minus 1 $result = mysqli_query($con,"SELECT * FROM `TABLE 1` LIMIT $offset, $total_records_per_page"); while($row = mysqli_fetch_array($result)){ echo "<tr> <th>".$row['Title']."</th> <th>".$row['Artist']."</th> </tr>"; } mysqli_close($con); ?> </tbody> </table> <div style='padding: 10px 20px 0px; border-top: dotted 1px #CCC;'> <strong>Page <?php echo $page_no." of ".$total_no_of_pages; ?></strong> </div> <ul class="pagination"> <?php // if($page_no > 1){ echo "<li><a href='?page_no=1'>First Page</a></li>"; } ?> <li <?php if($page_no <= 1){ echo "class='disabled'"; } ?>> <a <?php if($page_no > 1){ echo "href='?page_no=$previous_page'"; } ?>>Previous</a> <?php if($page_no >= $total_no_of_pages){ echo "class='disabled'"; } ?> <a <?php if($page_no < $total_no_of_pages) { echo "href='?page_no=$next_page'"; } ?>>Next</a> <?php if($page_no < $total_no_of_pages){ echo "<a href='?page_no=$total_no_of_pages'>Last ››</a>"; } ?> </li> </ul> <form action="mail.php" method="post"> <div id="Request"> <div class="row"> <div class="col-12-medium"> <input type="text" name="name" placeholder="Enter Your Name" /> </div> <div class="col-12-medium"> <input type="text" name="title" placeholder="Enter Song Title(s)" /> </div> <div class="col-12-medium"> <input type="text" name="artist" placeholder="Enter Artist Name(s)" /> </div> <div class="col-12-medium"> <input type="text" name="key" placeholder="Key Changes? +/-, 1-8" /> </div> <div class="col-12-medium"> <input type="submit" value="Send Message" ><input type="reset" value="Clear All" /> </div> </div> </div> </form> </div> </div> </article> </div> <div id="footer"> <ul class="copyright"> <li>© SLE Inc.</li><li>Design: <a href="">SLE</a></li><li>License<a href="License.txt">.txt</a></li> </ul> < nav id="nav"> </nav> </div> </div> </body> </html> This is the code I am trying to use to add pagination into my result set also, however, for some reason it consistently rells me that $result isn’t defined or that Mysqli_fetch_arrays are not defined, when I feel like they are but maybe Im just missing it again? <?php $localhost = ""; $username = "rsearch"; $password = ""; $dbname = "ke"; $con = new mysqli($localhost, $username, $password, $dbname); if( $con->connect_error){ die('Error: Connection' . $con->connect_error); } $tbl_name="`Table 1`"; $adjacents = 3; if( isset($_GET['search']) ){ $name = mysqli_real_escape_string($con, htmlspecialchars($_GET['search'])); $query = "SELECT COUNT(*) as num FROM $tbl_name WHERE (`Title` LIKE '%$name%') OR (`Artist` LIKE '%$name%')"; $total_pages = mysqli_fetch_array(mysqli_query($query)); $total_pages = $total_pages[num]; $targetpage = "index.php"; $limit = 25; $page = $_GET['page']; if($page) $start = ($page - 1) * $limit; else $start = 0; $sql = "SELECT `Artist` FROM $tbl_name LIMIT $start, $limit"; $result = $con->query($sql) or die('Could Not Search Database' . $con->error); if ($page == 0) $page = 1; $prev = $page - 1; $next = $page + 1; $lastpage = ceil($total_pages/$limit); $lpm1 = $lastpage - 1; $pagination = ""; if($lastpage > 1) { $pagination .= "<div class=\"pagination\">"; if ($page > 1) $pagination.= "<a href=\"$targetpage?page=$prev\"> previous</a>"; else $pagination.= "<span class=\"disabled\"> previous</span>"; if ($lastpage < 7 + ($adjacents * 2)) { 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)) { 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>"; } 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>"; } 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>"; } } } if ($page < $counter - 1) $pagination.= "<a href=\"$targetpage?page=$next\">next </a>"; else $pagination.= "<span class=\"disabled\">next </span>"; $pagination.= "</div>\n"; } } ?> <!DOCTYPE HTML> <html> <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="title" content="Catalog"> <meta name="description" content=""> <meta name="keywords" content=""> <meta name="robots" content="index, follow"> <meta name="language" content="English"> <meta name="revisit-after" content="15 days"> <meta name="author" content=""> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" /> <link rel="stylesheet" href="main.css" /> <link rel="stylesheet" href="bootstrap.min.css"> <noscript><link rel="stylesheet" href="noscript.css" /></noscript> <script type="text/javascript"> function mousehandler(e) { var myevent = (isNS) ? e : event; var eventbutton = (isNS) ? myevent.which : myevent.button; if ((eventbutton == 2) || (eventbutton == 3)) return false; } document.oncontextmenu = mischandler; document.onmousedown = mousehandler; document.onmouseup = mousehandler; function disableCtrlKeyCombination(e) { var forbiddenKeys = new Array("a", "s", "c", "x", "u"); var key; var isCtrl; if (window.event) { key = window.event.keyCode; //IE if (window.event.ctrlKey) isCtrl = true; else isCtrl = false; } else { key = e.which; //firefox if (e.ctrlKey) isCtrl = true; else isCtrl = false; } if (isCtrl) { for (i = 0; i < forbiddenKeys.length; i++) { if (forbiddenKeys[i].toLowerCase() == String.fromCharCode(key).toLowerCase()) { return false; } } } return true; } </script> </head> <body oncontextmenu="return false" class="is-preload"> <div id="wrapper"> <nav id="nav"> </nav> <div id="main"> <article id="contact" class="panel"> <header> <h2>Search Catalog</h2> <p>Updated as of 12/31/2019</p> </header> <div class="row"> <div class="container"> <form action="" method="GET"> <input type="text" placeholder="Search by Song Title or Artist" name="search"> <input type="submit" value="Search" name="btn" class="btn btn-sm btn-primary"> </form> <hr /> <h2>Search Results</h2> <table class="table table-striped table-bordered"> <tr> <th style='width:50px;'><strong>Title</strong></th> <th style='width:150px;'><strong>Artist</strong></th> </tr> <?php while($row = mysqli_fetch_array($result)){ echo "<tr> <th>".$row['Title']."</th> <th>".$row['Artist']."</th> </tr>"; ?> <?php } ?> <?=$pagination?> </table> <form action="mail.php" method="post"> <div id="Request"> <div class="row"> <div class="col-12-medium"> <input type="text" name="name" placeholder="Enter Your Name" /> </div> <div class="col-12-medium"> <input type="text" name="title" placeholder="Enter Song Title(s)" /> </div> <div class="col-12-medium"> <input type="text" name="artist" placeholder="Enter Artist Name(s)" /> </div> <div class="col-12-medium"> <input type="text" name="key" placeholder="Key Changes? +/-, 1-8" /> </div> <div class="col-12-medium"> <input type="submit" value="Send Message" ><input type="reset" value="Clear All" /> </div> </div> </div> </form> </div> </div> </article> </div> <div id="footer"> <ul class="copyright"> <li>© SLE Inc.</li><li>Design: <a href="">SLE</a></li><li>License<a href="License.txt">.txt</a></li> </ul> <nav id="nav"> </nav> </div> </div> </body> </html> Can I get a hand in figuring this out? I keep modifying those lines around but they aren’t fixing so maybe I’m just dumb? Edited January 1, 2020 by PsychoThis website has been great so far. Whenever I post a question, I get answer within few minutes. I have another question today related to PHP pagination. My search page basically allows users to view users others users in a specific country. Basically, there is are two html drop downs on the search page. First one allows you to select gender (male or female) and other one allows you to select country. After the search button is pressed, it displays all the usernames of males in that country. my search page's url looks something like: Code: [Select] http://localhost/search.php?gender=Male&country=Canada&searchbutton=Search[/b] I want to add pagination to this script. the search form has method=GET and 3 input options. one is gender and the other one is country and the last one is pageNum which is hidden. how can i add pagination to this??? Greetings All! New to PHP, and trying to learn as much as I can as quickly as I can for a client. I have been following some of Tutorials i understand most of it, but I still don't understand a few of the functions. Anyways, here is my problem. I am trying to combined the two tutorials (Pagination and Search Internal) but I seem to have myself in a loop... Code is as follows: Code: [Select] <?php $connect = mysql_connect("localhost","root","~~~~"); $db = mysql_select_db("~~~"); $button = $_GET['submit']; $search = $_GET['search']; if ($button) { if (strlen($search)<=0) echo "Please enter a keyword"; else { //explode our search terms $search_exploded = explode(" ",$search); foreach($search_exploded as $search_each) { //construct query $x++; if ($x==1) $construct .= "keywords LIKE '%$search_each%' OR vid_state LIKE '%$search_each%' OR users LIKE '%$search_each%' OR title LIKE '%$search_each%'"; else $construct .= " OR keywords LIKE '%$search_each%' OR vid_state LIKE '%$search_each%' OR users LIKE '%$search_each%' OR title LIKE '%$search_each%'"; } //eco out construct $construct = "SELECT * FROM video_url WHERE $construct"; $run = mysql_query($construct); $foundnum = mysql_num_rows($run); //max display per page $per_page = 3; //get start variable $start = $_GET['start']; //count records $record_count = $foundnum; //count max pages $max_pages = $record_count / $per_page; //may come out as decimal $pagenumbers = intval($max_pages) + 1; if (!$start) $start = 0; //setup previous and next variables $prev = $start - $per_page; $next = $start + $per_page; //show prev button if (!($start<=0)) echo "<a href='searchvideos.php?start=$prev'><img src='../images/texts/previous.png' border='0'></a> "; //show next button if (!($start>=$record_count-$per_page)) echo " <a href='searchvideos.php?start=$next'><img src='../images/texts/next.png' border='0'></a>"; //set variable for first page $i=1; for ($y=0;$y<$record_count;$y=$y+$per_page) { if($start!=$y) echo " <a href='searchvideos.php?start=$y'><span class='searchtext'>$i</span></a>"; else echo " <a href='searchvideos.php?start=$y'><span class='searchtext'> <font size='+1'><b>$i</b></font></span></a>"; $i++; } //show page numbers echo " / <font color='#FF6600' size='-1'>$pagenumbers</font> </td> <td align='right' width='50%'> <form action='../pages/searchvideos.php' method='get'> <span class='searchtext'>Search Videos</span> <input name='search' type='text' value='by Keywords, Title, Name, or State' size='35' /><input type='submit' name='submit' value='search' /> </form> </td> </tr> </table> </div> <br /><br /><div class='videotitle'><span class='createtext'> Videos </span></div> <br /><br />"; if ($foundnum==0) echo "No results found."; else { echo "$foundnum results found!<br><br>"; $query = mysql_query("SELECT * FROM video_url ORDER BY RAND() LIMIT $start, $per_page"); while($row = mysql_fetch_array($query)) //while ($numrows = mysql_fetch_assoc($run)) { $title = $row['title']; $url = $row['url']; $state = $row['vid_state']; $users = $row['users']; echo " <table bgcolor='#191919' cellpadding='0' cellspacing='0' background='../images/videobgs.png' align='center'> <tr> <td width='10px'></td> <td width='440px' height='370px' rowspan='6'> $url </td> <td width='340px' align='left'> <span class='createtext'>$title</span><hr /> $users<br /> $state </td> <td width='5px'></td> </tr> <tr><td> </td></tr> <tr><td> </td></tr> </table><br />"; } } } } ?> I know my code is dirty, and I have a lot to learn, and that I should probably be doing this a different way, but please try to correct the way I have it. Anyways..first page loads great, the search works great, the pagination works as it should (correct pages, correct page numbers, etc.). However, once I click on the "next" or the next "number" the next page is blank because the very first if statement throws a kink in my code... if ($button) - when continuing to the next page, a "$button" is not pressed and therefore doesn't continue the code, leaving the page blank. Any clues on how to fix this? I have tried combining the two in many different ways, this is the best i got so far... Thanks in advance, Phantaz i need some help.....im using a basic form with pagination, but it does not seem to be working for some reason it displays the username i search for the first time but when i click on the next button i get no more results even though i have like 30 more results left in the database ........... any help would be appriciated thanks in advance Here is the code i am using <?php include ('connect.php'); ?> <?php echo"<h3>Please enter your search Username</h3> <form action='search.php?find' method='post'> <input name='username' size='40' maxlength='32'/> <input type='submit' value='Submit' /> </form>"; ?> <hr width="800"> <?php if (isset($_GET["find"])) { $username = ($_POST["username"]); $per_page =5; $start = @$_GET['start']; $record_count = mysql_num_rows(mysql_query("SELECT * FROM register WHERE username LIKE '%$username%' ORDER BY username")); $max_pages = $record_count / $per_page; if(!$start) $start = 0; $query = mysql_query("SELECT * FROM register WHERE username LIKE '%$username%'ORDER BY username LIMIT $start, $per_page "); $exist = mysql_num_rows($query); if($exist=='0') { echo "No match found"; } else { echo "Your matches for: <b>$username</b><br><br>"; while($currow = mysql_fetch_array($query)) { $username = ($currow['username']); echo"</td> </tr> </table>"; ?> <?php echo" <a href='../mysite/$username'>$username</a><br>" ; } } ?> <?php $prev = $start - $per_page; $next = $start + $per_page; echo"<br>"; if(!($start<=0)) echo "<a href='{$_SERVER['PHP_SELF']}?start=$prev'>Prev</a> "; $i=1; for($x=0;$x<$record_count;$x=$x+$per_page) { if($start!=$x) echo "<a href='{$_SERVER['PHP_SELF']}?start= $x'>$i</a> "; else echo "<a href='{$_SERVER['PHP_SELF']}?start= $x'>$i</a> "; $i++; } if(!($start>=$record_count-$per_page)) echo "<a href='{$_SERVER['PHP_SELF']}?start=$next'>Next</a>"; echo" $next"; echo"<br><br>"; } ?> </div> </body> </html> <?php include ('footer.php'); ?> |