PHP - Pagination On Search Database Do Not Work Help !!!!
I found this nice search database script on line but the pagination does not work can someone tell me what is wrong with it ???? so i can work with it !!!
here is the full code : Code: [Select] <?php // Get the search variable from URL $var = @$_GET['q'] ; $trimmed = trim($var); //trim whitespace from the stored variable // rows to return $limit=10; // check for an empty string and display a message. if ($trimmed == "") { echo "<p>Please enter a search...</p>"; exit; } // check for a search parameter if (!isset($var)) { echo "<p>We dont seem to have a search parameter!</p>"; exit; } //connect to your database ** EDIT REQUIRED HERE ** mysql_connect("localhost","username","password"); //(host, username, password) //specify database ** EDIT REQUIRED HERE ** mysql_select_db("database") or die("Unable to select database"); //select which database we're using // Build SQL Query $query = "select * from the_table where 1st_field like \"%$trimmed%\" order by 1st_field"; // EDIT HERE and specify your table and field names for the SQL query $numresults=mysql_query($query); $numrows=mysql_num_rows($numresults); // If we have no results, offer a google search as an alternative if ($numrows == 0) { echo "<h4>Results</h4>"; echo "<p>Sorry, your search: "" . $trimmed . "" returned zero results</p>"; echo "<p><a href=\"http://www.google.com/search?q=" . $trimmed . "\" target=\"_blank\" title=\"Look up " . $trimmed . " on Google\">Click here</a> to try the search on google</p>"; } // next determine if s has been passed to script, if not use 0 if (empty($s)) { $s=0; } // get results $query .= " limit $s,$limit"; $result = mysql_query($query) or die("Couldn't execute query"); // display what the person searched for echo "<p>You searched for: "" . $var . ""</p>"; // begin to show results set echo "Results"; $count = 1 + $s ; // now you can display the results returned while ($row= mysql_fetch_array($result)) { $title = $row["1st_field"]; echo "$count.) $title" ; $count++ ; } $currPage = (($s/$limit) + 1); //break before paging echo "<br />"; // next we need to do the links to other results if ($s>=1) { // bypass PREV link if s is 0 $prevs=($s-$limit); print " <a href=\"$PHP_SELF?s=$prevs&q=$var\"><< Prev 10</a>  "; } // calculate number of pages needing links $pages=intval($numrows/$limit); // $pages now contains int of pages needed unless there is a remainder from division if ($numrows%$limit) { // has remainder so add one page $pages++; } // check to see if last page if (!((($s+$limit)/$limit)==$pages) && $pages!=1) { // not last page so give NEXT link $news=$s+$limit; echo " <a href=\"$PHP_SELF?s=$news&q=$var\">Next 10 >></a>"; } $a = $s + ($limit) ; if ($a > $numrows) { $a = $numrows ; } $b = $s + 1 ; echo "<p>Showing results $b to $a of $numrows</p>"; ?> Similar TutorialsHi 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 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'); ?> 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 This 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 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! 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 PsychoHi 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? when i filter a search it shows 1st page but cannot show contents on 2nd page. i have the following code: <? include_once "connect.php"; if(trim($_REQUEST['searchkeyword'])!="") { $searchkeyword=$_REQUEST['searchkeyword']; $searchkeyword1=str_replace(".", "", $searchkeyword); } if($_REQUEST['stype']!="" && $_REQUEST['start']=="" && trim($_REQUEST['searchkeyword'])!="") { $qry="INSERT INTO search_history set search_type='".$_REQUEST['stype']."', search_text='".$_REQUEST['searchkeyword']."', search_date=now(), result_url='course_listing.php?searchkeyword=".$_REQUEST['searchkeyword']."'"; mysql_query($qry); $_GET['stype']=""; } $PVR_SectionID="2"; $extQry=""; $extQry2=""; if(isset($_REQUEST['searchkeyword'])) { $extQry.=" and (department like '%".$_REQUEST['searchkeyword']."%' or course_title like '%".$searchkeyword1."%' or course_title like '%".$_REQUEST['searchkeyword']."%' or course_desc like '%".$_REQUEST['searchkeyword']."%')"; $extQry2=" and (name like '%".$_REQUEST['searchkeyword']."%' or contact_name like '%".$_REQUEST['searchkeyword']."%' or country like '%".$_REQUEST['searchkeyword']."%' or city like '%".$_REQUEST['searchkeyword']."%' or description like '%".$_REQUEST['searchkeyword']."%')"; } if(isset($_REQUEST['subject'])) { $extQry.=" and sub_id in ("; $cnt=0; foreach($_REQUEST['subject'] as $k=>$v) { $cnt++; if($cnt>1) { $extQry.=",".$v; } else { $extQry.=$v; } } $extQry.=") "; } if(isset($_REQUEST['region'])) { $extQry.=" and uni_id in (SELECT id from institution where is_active='1' and reg_id in("; $extQry2.=" and reg_id in("; $cnt=0; foreach($_REQUEST['region'] as $k=>$v) { $cnt++; if($cnt>1) { $extQry.=",".$v; $extQry2.=",".$v; } else { $extQry.=$v; $extQry2.=$v; } } $extQry.=") ) "; $extQry2.=")"; } if(isset($_REQUEST['studymode'])) { $extQry.=" and id in ( SELECT course_id from course_qdm where mode in ("; $cnt=0; foreach($_REQUEST['studymode'] as $k=>$v) { $cnt++; if($cnt>1) { $extQry.=",'".$v."'"; } else { $extQry.="'".$v."'"; } } $extQry.=") ) "; } if(isset($_REQUEST['institution'])) { $extQry.=" and uni_id='".$_REQUEST['institution']."'"; } $courseQry="SELECT * FROM course where is_active='1' $extQry "; $crsRes=mysql_query($courseQry); $totCourse=mysql_affected_rows(); $pgLimit=10; $shFrom=intval($_REQUEST['start'])+1; $shTo= $shFrom + $pgLimit - 1; if($shTo>$totCourse) $shTo=$totCourse; $CRSresult=$prs_pageing->number_pageing22($courseQry,$pgLimit,10,'N','Y'); $courseQry="SELECT * FROM institution where is_active='1' $extQry2"; $instRes=mysql_query($courseQry); $totInstitution=mysql_affected_rows(); ?> <!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" /> <? getMeta("4") ;?> <?php include("head_script.php"); ?> <script src="../../../../DOCUME~1/Farhan/LOCALS~1/Temp/Scripts/cforms.js" type="text/javascript"></script> <script src="../../../../DOCUME~1/Farhan/LOCALS~1/Temp/SpryAssets/SpryAccordion.js" type="text/javascript"></script> <script type="text/javascript"> <!-- function MM_preloadImages() { //v3.0 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array(); var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++) if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}} } //--> </script> <link href="../../../../DOCUME~1/Farhan/LOCALS~1/Temp/SpryAssets/SpryAccordion.css" rel="stylesheet" type="text/css" /> </head> <body> <table width="950" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td><? include_once "header.php"; ?></td> </tr> <tr> <td><table width="950" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="753" height="32"><div id="track_2"><a href="../../../../DOCUME~1/Farhan/LOCALS~1/Temp/index.php" style="padding-left:0px;"><img src="../../../../DOCUME~1/Farhan/LOCALS~1/Temp/images/btn_home.gif" /></a><a href="../../../../DOCUME~1/Farhan/LOCALS~1/Temp/course_search.php">Find courses and research</a><span>Search Results</span></div></td> <td width="10" rowspan="2"> </td> <td width="187" rowspan="2" align="center" valign="top" bgcolor="#f9f9f9"><? include_once "banners_block.php"; ?></td> </tr> <tr> <td valign="top" id="contents"> <h1>you have <?=$totCourse;?> Course Search Result</h1> <? include "course_filter.php"; ?> <? if($CRSresult[1]!="") { ?> <div> <h2>Showing <?=$shFrom;?>-<?=$shTo;?></h2></div> <? while($CRSrow=mysql_fetch_array($CRSresult[0])) { ?> <div class="mix"> <a href="<?=course_details_URL($CRSrow['id']);?>"><b><?=stripslashes($CRSrow['course_title']);?></b></a> <? $quaRes=mysql_query("SELECT qualification from course_qdm where course_id='".$CRSrow['id']."'"); if(mysql_affected_rows()>0) { $cnt=0; $qArr=array(); while($quaRow=mysql_fetch_array($quaRes)) { if(!array_key_exists($quaRow['qualification'],$qArr)) { $cnt++; if($cnt>1) { echo " / ".stripslashes($quaRow['qualification']); } else { echo stripslashes($quaRow['qualification']); } $qArr[$quaRow['qualification']]=1; } } } ?> <a href="<?=university_prof_details_URL($CRSrow['uni_id']);?>" ><strong><?=stripslashes(GetValue("institution","name","id",$CRSrow['uni_id']));?></strong></a> - <?=stripslashes($CRSrow['department']);?> <br /> <span><?=substr(strip_tags(stripslashes($CRSrow['course_desc'])),0,100);?>...</span> <a href="<?=course_details_URL($CRSrow['id']);?>"><strong>read more</strong></a> </div> <? } ?> <?php $sub_get = $_GET['subject']; $s_pass = $sub_get[0]; ?> <?php /*?><div class="link_large"><a href="all_course.php?q=<?=base64_encode($extQry);?>">More Courses</a></div><?php */?> <? } ?> <div> <?=$CRSresult[1];?> </div> </td> </tr> </table></td> </tr> <tr> <td><? include_once "bookmark.php"; ?></td> </tr> <tr> <td><? include_once "footer.php"; ?></td> </tr> </table> </body> </html> Hi, I'm very new to PHP and have been working on a small project that is a search engine connected to a mysql database. I can't seem to display the results from the search across multiple pages, when I click the Next button it just brings me to a blank page with no content except for my search form on top. I have a feeling that my problem lies in how I'm passing variables from one page to another as I realize that the URL of page 2 doesn't have the users search anymore. What do I need to change to get multiple pages working? Code: [Select] <?php if(isset($_GET['submit'])){ if(isset($_GET['name'])){ if(preg_match("/^[ a-zA-Z0-9]+/", $_GET['name'])){ $name=$_GET['name']; // Connect to database $db=mysql_connect("localhost", "root", "1234") or die ('Cannot connect: ' . mysql_error()); // Select database $mydb=mysql_select_db("mydb"); // Check page num, if no page num set to 1 if(isset($_GET['pagenum'])){ $pagenum = $_GET['pagenum']; } else{ $pagenum = 1; } // Query the database table $sql="SELECT id, ProductName, Price FROM testdb WHERE ProductName LIKE '%" . $name ."%'"; // Run query $result=mysql_query($sql); // Check to see if any results were found, if not, tell user $resultnum = mysql_num_rows($result); // Number of results per page $page_rows = 4; // Page number of previous page $last = ceil($resultnum/$page_rows); // Make sure page number isn't below 1 or above maximum if($pagenum < 1){ $pagenum = 1; } elseif($pagenum > $last){ $pagenum = $last; } // Set range to display in query $max = 'limit ' .($pagenum - 1) * $page_rows .',' .$page_rows; $sql2 = "SELECT id, ProductName, Price FROM testdb WHERE ProductName LIKE '%" . $name ."%' $max"; $data_p = mysql_query($sql2); if($resultnum == 0){ echo "<p class='p1'>No results found for query: " . $name . "</p>"; } else{ echo "<table class='sortable'>"; echo "<thead>"; echo "<tr>"; echo "<th>" . "Model Number" . "</th>"; echo "<th>" . "Product" . "</th>"; echo "<th>" . "Price" . "</th>"; echo "</tr>"; echo "</thead>"; // Loop through results $bg = '#9D9D9D'; while($row=mysql_fetch_array($data_p)){ $bg = ($bg=='#9D9D9D' ? '#C7C7C7' : '#9D9D9D'); $ProductName=$row['ProductName']; $Price=$row['Price']; $ID=$row['id']; // Display results of array echo "<tr bgcolor='" .$bg . "'>"; echo "<td width='30%', align='center'>" . " " . "</td>"; echo "<td width='60%', align='center'>" . "<a href=\"search.php?id=$ID\">" . $ProductName . "</a></td>"; echo "<td width='10%', align='center'>" . $Price . "</td>\n"; echo "</tr>"; echo "<tr><td></td></tr>"; } echo "</table>"; echo "<p>"; 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> "; } 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> "; } } } else{ echo "<p class='p2'>Please enter a query.</p>"; } } } ?> The search form looks like this... Code: [Select] <form method="get" action="search.php" id="searchform"> <input type="text" name="name" size = "42"> <input type="submit" name="submit" value="Search" STYLE="font-family: Arial, Helvetica, sans-serif; font-weight: bold;"> </form> Thanks. i have an issue in plain php when i filter my search result for specific search it shows 1st page but can not give results on 2nd page i am sending both the files includes: course_listing.php course_filter.php 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. 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. Hello, I adapted the pagination script from the tutorial (great instruction and detail) from this site and it works perfectly. However, I added a search engine to it and it works like it should. The problem comes in with the following SQL query: Code: [Select] $sql = "SELECT COUNT(*) FROM qa"; If i modify it to fit my query, the number at the bottom of the page disappears and the > >> links go to blank pages. Also all queried rows show on one page and doesn't stop at ten. How do i modify my pagination script with a search engine so people can query their results without 'breaking' the pagination script?? I'm using the PHP Freaks pagination tutorial. Till now the pagination function works very great, except on pages where I use GET in the URL. When I use the pagination navigation links on a profile page like this: domain.com/profile.php?user=konopkov then the URL becomes to this: domain.com/profile.php?current_page=2 And the profile won't show up anymore. So my question is how can I achieve it so the pagination navigation links will still work even with URL's which use GET? Here's an example of the pagination links section: // echo forward link for next page echo " <a href='{$_SERVER['PHP_SELF']}?current_page=$next_page'>></a> "; // echo forward link for last page echo " <a href='{$_SERVER['PHP_SELF']}?current_page=$total_pages'>>></a> "; Thank you. |