PHP - Making Pagination Work With Get In Url?
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. Similar TutorialsI 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>"; ?> Hello,
I have one search form and when I search something the result is whole records from the database not only the search term. Any help is appreciated. I will post only the part where is calculating the rows from db but if need I will post whole pagination script.
$searchTerm = trim($_POST['term']); $adjacents = 3; $sql1 = mysql_query("SELECT * FROM images ORDER BY id ASC"); $nr = mysql_num_rows($sql1); $limit = 6; $targetpage = "search.php"; $page = $_GET['page']; if($page) $start = ($page - 1) * $limit; else $start = 0; if ($page == 0) $page = 1; $prev = $page - 1; // $prev = $page - 1 $next = $page + 1; // $next = $page + 1 $lastpage = ceil($nr/$limit); //lastpage = total pages / items per page. $lpm1 = $lastpage - 1; $pagination = ""; .... .... // pagination ... ... // while loop for the results $sql = "SELECT id, name, caption FROM images WHERE caption LIKE '%".$searchTerm."%' ORDER BY id DESC LIMIT $start, $limit"; $result = mysql_query($sql); while($row = mysql_fetch_array($result)) { $output.= "<div class=\"container_image\">"; $output.= "<a href=\"/pic-".$row['id'].".html\"><img src=\"/upload/".$row['name']."\" width=\"210\" height=\"150\"/></a>"; $output.= "</div>"; } Edited by vinsb, 21 July 2014 - 06:58 AM. Here is a simple script which uses bitwise operations to determine whether or not a checkbox has been set. The problem is that if you use the $alpha array, the script doesn't produce the results you should expect. For example, if you set the last checkbox while using the $alpha array, all the checkboxes become set. I partially know why this happens as the PHP-Manual enlightened me: Quote From: http://www.php.net/manual/en/language.operators.bitwise.php Don't right shift for more than 32 bits on 32 bits systems. Don't left shift in case it results to number longer than 32 bits. I attempted to use the GMP_* functions but because those aren't part of the PHP-Standard-Library, I do not wish to rely on them. Is there any way to make these functions work for integers beyond 2^31? Here is a standalone script I'm using to make these tests. $alpha = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'); $delta = range('a', 'z'); function generate($array){ $n = count($array); $c = array(); for($i = 0; $i < $n; ++$i){ $c[bcpow(2, $i)] = $array[$i]; } return $c; } function set($array, $post){ $c = 0; foreach($array as $key => $val) if(isset($post['c'.$key])) $c |= $key; return $c; } function check($num, $category){ if($num & $category) return 'CHECKED'; return ''; } function checkboxes($array, $numval=0){ $i = 0; $form = ''; foreach($array as $key => $val){ $checked = check($numval, $key); $form .= '<input type="checkbox" '.$checked.' name="c'.$key.'" id="c'.$key.'">' . '<label for="c'.$key.'"> '.$val.'</label><br />'; ++$i; } return $form; } $array = generate($alpha); $num = 0; if(isset($_POST['action'])){ $num = set($array, $_POST); echo $num; } echo '<form action="y.php" method="post" style="width: 400px; border: 1px solid black;">'; echo checkboxes($array, $num); echo '<input type="submit" name="action" value="Set" />'; echo '</form>'; This one requires lots of up front information: I have a page, for this example that I will call page.php. It takes get parameters, and for this example I'll call the parameter "step". So I have a URL like this: page.php?step=1 This page has a form with an action of page.php?step=1. The code on the page validates the posting information. If the information is bad, it returns the user to page.php?step=1; if it is good, it takes the user to page.php?step=2 via header( "location:page.php?step=2" ). So redirection is done by relative path, not full URLs. This all works as expected. Now what I've done is set .htaccess to be HTTPS for this page, via this code: # Turn SSL on for payments RewriteCond %{HTTPS} off RewriteCond %{SCRIPT_FILENAME} \/page\.php [NC] RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L] This works (initially). However, once you try to post the form, it just redirects back to the step=1 version of the page. I really don't know how or why that would be. I'm not sure how else I can explain this or what other information you may have. But it's frustrating to not get a page working in HTTPS that works in HTTP. Very odd. Any suggestions? (I don't even really know the best location to figure out when/why it's redirecting back to the original page.) Hi.., I use below method to export data to excel. header('Content-type: application/ms-excel'); header('Content-Disposition: attachment; filename=abc.xls'); if I run the script from the server. (http://localhost/export.php) it is work. (pop-up window if i want save or open the file) but if i run the script from the client (http://192.168.1.5/export.php) it is not work. (nothing happen) any idea how to solve this? require_once 'includes/upload.class.php'; $upload = new uploads(); $details = $upload->getFileInformation($id); <?php echo $details['upload_desc']; ?> then here the class. require_once 'db.class.php'; class uploads extends database { private $uploadData; function uploadFile() { public function getFileInformation($id) { $this->uploadData = $this->readData("uploadfiles", "upload_id", $id); return $this->uploadData; } But it wont work! <?php require_once('upper.php'); // Connects to your Database require_once('database.php'); //This checks to see if there is a page number. If not, it will set it to page 1 if (!(isset($pagenum))) { $pagenum = 1; } //Here we count the number of results //Edit $data to be your query $query = "SELECT * FROM events"; $result = mysqli_query($dbc,$query) or die('Not'); $rows = mysqli_num_rows($result); //This is the number of results displayed per page $page_rows = 2; //This tells us the page number of our last page $last = ceil($rows/$page_rows); //this makes sure the page number isn't below one, or more than our maximum pages if ($pagenum < 1) { $pagenum = 1; } elseif ($pagenum > $last) { $pagenum = $last; } //This sets range that we will display in our query $max = 'limit ' .($pagenum - 1) * $page_rows .',' .$page_rows; //This is your query again, the same one... the only difference is we add $max into it $result = mysqli_query($dbc,"SELECT * FROM events $max") or die('Not'); //This is where you display your query results while($row = mysqli_fetch_array( $result)) { $Title=$row['Title']; $City=$row['City']; $Content=$row['Content']; //$Photo=$row['Photo']; $Date=$row['Date']; $EventId=$row['EventId']; $Photo=$row['Photo']; //echo $Photo; echo "<div><table border='0' cellspacing='0' cellpadding='0' width='389'> <tr> <td><img src='images/events_2.png' width='389' height='10'></td> </tr> <tr> <td background='images/events_2_bg.png'> <table border='0' cellspacing='0' width='359'> <tr> <td> <tr> <table width='100%' border='0' cellspacing='0' > <tr> <td rowspan='3'><img src='$Photo' width='80' height='60'></td> <td align='left' valign='top' width='180'>$City</td> <td align='left' valign='top'>$Date</td> </tr> <tr> <td colspan='3' align='left' valign='top'>$Title</td> </tr> <tr> <td colspan='2'><a href='KnowMore.php?EventId=".$row['EventId']."'>Know more </a> / <a href='EventParticipator.php?EventId=".$row['EventId']."'>click here to participate</a></td> </tr> </table> </tr> </tr> </table> </td> </tr> <tr> <td><img src='images/events_2_bottom.png' width='389' height='10' ></td> </tr> </table></div>"; } echo "<p>"; // This shows the user what page they are on, and the total number of pages echo " --Page $pagenum of $last-- <p>"; // First we check if we are on page one. If we are then we don't need a link to the previous page or the first page so we do nothing. If we aren't then we generate links to the first page, and to the previous page. if ($pagenum == 1) { } else { echo " <a href='{$_SERVER['pagination.php']}?pagenum=1'> <<-First</a> "; echo " "; $previous = $pagenum-1; echo " <a href='{$_SERVER['page_test.php']}?pagenum=$previous'> <-Previous</a> "; } echo $PHP_SELF; //just a spacer echo " ---- "; //This does the same as above, only checking if we are on the last page, and then generating the Next and Last links if ($pagenum == $last) { } else { $next = $pagenum+1; echo " <a href='{$_SERVER['page_test.php']}?pagenum=$next'>Next -></a> "; echo " "; echo " <a href='{$_SERVER['page_test.php']}?pagenum=$last'>Last ->></a> "; } require_once('lower.php'); ?> Quote Hi friends............ I want to paginate my page but it not works properly. It displays first 2 rows but on clicking "Next" nothing happens. It displays error also "Notice: Undefined variable: PHP_SELF in C:\wamp\www\NGOProject\Elite Brigade\pagination.php on line 112" and "Notice: Undefined index: page_test.php in C:\wamp\www\NGOProject\Elite Brigade\pagination.php on line 124"......... I don't know what to do?????? please help me anyone??????? i have some code which checks all of the posts in the database with the topic_id of $topic_id. what i want to do is like on many forums. On the topic list next to the name just show the pages like: Code: [Select] 1-2-3-4 and when there are more than 4 or so Code: [Select] 1-2....8-9 here is the code which gets the number of pages: $data = $db->query("SELECT * FROM ".DB_PREFIX."posts WHERE topic_id = '$topic_info->topic_id'"); $rows = mysql_num_rows($data); $page_rows = $posts_per_page; if ($rows > $page_rows) { $rowsArray = array($rows); } as you can see i have added it into an array but i dont know what to do from there. I guessed it would be something like a for statement but im not sure. Can anyone help? hi ive simple code. but i would need help how to do pagination. ive followed one tutorial and ive code.but i really dont know how to connect these.or if its even possible to connect. heres the index.php file Code: [Select] <?php include '_class/cms_class.php'; $obj = new modernCMS(); $obj->host = 'localhost'; $obj->username = 'root'; $obj->password = 'root'; $obj->db = 'modernCMS'; $obj->connect(); ?> <!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>Untitled Document</title> <link rel="stylesheet" href="style.css" type="text/css" media="screen" title="no title" charset="utf-8"> </head> <body> <div id="page-wrap"> <?php if(isset($_GET['id'])): $obj->get_content($_GET['id']); else: $obj->get_content(); endif; ?> </div> </body> </html> cms_class.php Code: [Select] <?php class modernCMS { var $host; var $username; var $password; var $db; function connect() { $con = mysql_connect($this->host, $this->username, $this->password) or die(mysql_error()); mysql_select_db($this->db, $con) or die(mysql_error()); } function get_content($id = '') { if($id != ""): $id = mysql_real_escape_string($id); $sql = "SELECT * FROM cms_content WHERE id = '$id'"; else: $sql = "SELECT * FROM cms_content ORDER BY id DESC"; endif; $res = mysql_query($sql) or die(mysql_error()); while($row = mysql_fetch_assoc($res)) { echo '<h1><a href="index.php?id=' . $row['id'] . '">' . $row['title'] . '</a></h1>'; echo '<p>' . $row['body'] . '</p>'; } } } ?> Heres the pagination code ihave Code: [Select] <?php include 'db.inc.php'; $per_page = 2; $pages_query = mysql_query("SELECT COUNT(`id`) FROM `cms_content`"); $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 `cms_content` LIMIT $start, $per_page"); while ($query_row = mysql_fetch_assoc($query)) { echo '<p>', $query_row['title'] ,'</p>'; echo '<p>', $query_row['body'] ,'</p>'; } if ($pages >=1 && $page <= $pages) { for ($x=1; $x<=$pages; $x++) { echo ($x == $page) ? '<strong><a href="?page=' .$x. '">' .$x. '</a></strong> ' : '<a href="?page=' .$x. '">' .$x. '</a> '; } } ?> thanks. Code: [Select] <?php $title="Search"; $metakeywords="search, find"; $metadescription="Search for your love!"; include ('header.php'); $getpage=clean_up($_GET['page']); $getpage = abs((int) ($getpage)); echo ' <table width="100%"><tr><td valign="top" class="content"> <form action="index.php?action=search" method="post"> <b>Seeking Gender</b> <select name="gender"> <option value="">Either</option> <option value="Male">Male</option> <option value="Female">Female</option> </select> <hr> <b>Smoke?</b> <select name="smoke"> <option value="">Doesn\'t matter</option> <option value="Yes">Yes</option> <option value="No">No</option> </select> <hr> <b>Drink?</b> <select name="drink"> <option value="">Doesn\'t matter</option> <option value="Yes">Yes</option> <option value="No">No</option> </select> <hr> <b>Body Type </b> <select name="bodytype"> <option value="">Doesn\'t matter</option> <option value="Slim / Slender">Slim / Slender</option> <option value="Athletic">Athletic</option> <option value="Average">Average</option> <option value="Some extra baggage">Some extra baggage</option> <option value="Body builder">Body builder</option> </select> </td><td valign="top" class="content"> <b>First Name</b> <input type="text" name="first" size="17"><br> <b>Last Name</b><input type="text" name="last" size="17"> <hr> <b>Sexual orientation</b> <select class="orientation" name="orientation"> <option value="">Any</option> <option value="Bi">Bi</option> <option value="Gay/Lesbian">Gay/Lesbian</option> <option value="Straight">Straight</option> </select> <hr> <b>Age Range</b> <select class="date" name="age_from">'; $years = range( 16, 100 ); foreach( $years as $v ) { echo "<option value=\"$v\">$v</option>\n"; } echo ' </select> to <select class="date" name="age_to">'; $yyears = range( 17, 100 ); foreach( $yyears as $v ) { echo "<option value=\"$v\">$v</option>\n"; } echo '</select> </td><td valign="top" class="content"> <b>Religion</b> <select name="religious"> <option value="">Any</option> <option value="Agnostic">Agnostic</option> <option value="Atheist">Atheist</option> <option value="Buddhist">Buddhist</option> <option value="Catholic">Catholic</option> <option value="Christian">Christian</option> <option value="Hindu">Hindu</option> <option value="Jewish">Jewish</option> <option value="Mormon">Mormon</option> <option value="Muslim">Muslim</option> <option value="Other">Other</option> <option value="Protestant">Protestant</option> <option value="Satanist">Satanist</option> <option value="Scientologist">Scientologist</option> <option value="Taoist">Taoist</option> <option value="Wiccan">Wiccan</option> </select> <hr> <b>Ethnicity</b> <select name="ethnicity"> <option value="">Any</option> <option value="Asian">Asian</option> <option value="Black / African descent">Black / African descent</option> <option value="East Indian">East Indian</option> <option value="Latino / Hispanic">Latino / Hispanic</option> <option value="Middle Eastern">Middle Eastern</option> <option value="Native American">Native American</option> <option value="Pacific Islander">Pacific Islander</option> <option value="White / Caucasian">White / Caucasian</option> <option value="Other">Other</option> </select> <hr> <b>Children</b> <select name="children"> <option value="">Doesn\'t matter</option> <option value="I don\'t want kids">I don\'t want kids</option> <option value="Love kids, but not for me">Love kids, but not for me</option> <option value="Undecided">Undecided</option> <option value="Someday">Someday</option> <option value="Expecting">Expecting</option> <option value="Proud parent">Proud parent</option> </select> <hr> <b>Education</b> <select name="education"> <option value="">Doesn\'t matter</option> <option value="High school">High school</option> <option value="Some college">Some college</option> <option value="In college">In college</option> <option value="College graduate">College graduate</option> <option value="Grad / professional school">Grad / professional school</option> <option value="Post grad">Post grad</option> </select> <br><input type="submit" name="submit" value="Search" /></form> </td></tr></table>'; if($_POST['submit'] || $_GET['page'] > "0"){ $first = clean_up($_POST['first']); $last = clean_up($_POST['last']); $smoke = clean_up($_POST['smoke']); $drink = clean_up($_POST['drink']); $gender = clean_up($_POST['gender']); $age_from = clean_up($_POST['age_from']); $age_to = clean_up($_POST['age_to']); $orientation = clean_up($_POST['orientation']); $religious = clean_up($_POST['religious']); $ethnicity = clean_up($_POST['ethnicity']); $bodytype = clean_up($_POST['bodytype']); $children = clean_up($_POST['children']); $education = clean_up($_POST['education']); if(!$_GET['page']){ if(!$first == ""){ setcookie("first", $first, time()+3600); } if(!$last == ""){ setcookie("last", $last, time()+3600); } if(!$smoke == ""){ setcookie("smoke", $smoke, time()+3600); } if(!$drink == ""){ setcookie("drink", $drink, time()+3600); } if(!$gender == ""){ setcookie("gender", $gender, time()+3600); } if(!$age_from == ""){ setcookie("age_from", "$age_from", time()+3600); } if(!$age_to == ""){ setcookie("age_to", "$age_to", time()+3600); } if(!$orientation == ""){ setcookie("orientation", $orientation, time()+3600); } if(!$religious == ""){ setcookie("religious", $religious, time()+3600); } if(!$ethnicity == ""){ setcookie("ethnicity", $ethnicity, time()+3600); } if(!$bodytype == ""){ setcookie("bodytype", $bodytype, time()+3600); } if(!$children == ""){ setcookie("children", $children, time()+3600); } if(!$education == ""){ setcookie("education", $education, time()+3600); } } $qquery = "SELECT `id`, `first`, `last`, `avatar`, `gender`, `about`, ( (DATE_FORMAT(CURDATE(),'%Y') - DATE_FORMAT(`bdate`, '%Y') ) - ( DATE_FORMAT(CURDATE(), '00-%m-%d') < DATE_FORMAT( `bdate`, '00-%m-%d')) ) AS age FROM `users` WHERE ( (DATE_FORMAT(CURDATE(),'%Y') - DATE_FORMAT(`bdate`, '%Y') ) - ( DATE_FORMAT(CURDATE(), '00-%m-%d') < DATE_FORMAT( `bdate`, '00-%m-%d')) ) BETWEEN $age_from AND $age_to"; // if any of the options that are stored in the `users` table are selected, add AND to the query string, //and store each needed part in an array, $users_criteria if( $gender != "" || $first != "" || $last != "" ) { $qquery .= ' AND '; $users_criteria = array(); if( !empty($gender) ) { $users_criteria[] = "`gender` = '$gender'"; } if( !empty($first) ) { $users_criteria[] = "`first` LIKE '%$first%'"; } if( !empty($last) ) { $users_criteria[] = "`last` LIKE '%$last%'"; } $qquery .= implode( ' AND ', $users_criteria ); // implode the array, separating each part with AND, and append to query string } // Same process as above, but for results that come from `questions` table if( $smoke != '' || $drink != '' || $orientation != '' || $religious != '' || $ethnicity != '' || $bodytype != '' ) { $qquery .= ' AND id IN( SELECT `userid` FROM `questions` WHERE '; $questions_criteria = array(); if( !empty($smoke) ) { $questions_criteria[] = "`smoke` = '$smoke'"; } if( !empty($drink) ) { $questions_criteria[] = "`drink` = '$drink'"; } if( !empty($orientation) ) { $questions_criteria[] = "`orientation` = '$orientation'"; } if( !empty($religious) ) { $questions_criteria[] = "`religious` = '$religious'"; } if( !empty($ethnicity) ) { $questions_criteria[] = "`ethnicity` = '$ethnicity'"; } if( !empty($bodytype) ) { $questions_criteria[] = "`body_type` = '$bodytype'"; } if( !empty($children) ) { $questions_criteria[] = "`children` = '$children'"; } if( !empty($education) ) { $questions_criteria[] = "`education` = '$education'"; } $qquery .= implode( ' AND ', $questions_criteria ); $qquery .= ' )'; } $total = mysql_num_rows(mysql_query($qquery)); $page_count = ceil($total / 2); $page = 1; if (isset($getpage) && $getpage >= 1 && $getpage <= $page_count) { $page = (int)$getpage; } $skip = ($page - 1) * 2; $query = "SELECT `id`, `first`, `last`, `avatar`, `gender`, `about`, ( (DATE_FORMAT(CURDATE(),'%Y') - DATE_FORMAT(`bdate`, '%Y') ) - ( DATE_FORMAT(CURDATE(), '00-%m-%d') < DATE_FORMAT( `bdate`, '00-%m-%d')) ) AS age FROM `users` WHERE ( (DATE_FORMAT(CURDATE(),'%Y') - DATE_FORMAT(`bdate`, '%Y') ) - ( DATE_FORMAT(CURDATE(), '00-%m-%d') < DATE_FORMAT( `bdate`, '00-%m-%d')) ) BETWEEN $age_from AND $age_to"; // if any of the options that are stored in the `users` table are selected, add AND to the query string, //and store each needed part in an array, $users_criteria if( $gender != "" || $first != "" || $last != "" ) { $query .= ' AND '; $users_criteria = array(); if( !empty($gender) ) { $users_criteria[] = "`gender` = '$gender'"; } if( !empty($first) ) { $users_criteria[] = "`first` LIKE '%$first%'"; } if( !empty($last) ) { $users_criteria[] = "`last` LIKE '%$last%'"; } $query .= implode( ' AND ', $users_criteria ); // implode the array, separating each part with AND, and append to query string } // Same process as above, but for results that come from `questions` table if( $smoke != '' || $drink != '' || $orientation != '' || $religious != '' || $ethnicity != '' || $bodytype != '' ) { $query .= ' AND id IN( SELECT `userid` FROM `questions` WHERE '; $questions_criteria = array(); if( !empty($smoke) ) { $questions_criteria[] = "`smoke` = '$smoke'"; } if( !empty($drink) ) { $questions_criteria[] = "`drink` = '$drink'"; } if( !empty($orientation) ) { $questions_criteria[] = "`orientation` = '$orientation'"; } if( !empty($religious) ) { $questions_criteria[] = "`religious` = '$religious'"; } if( !empty($ethnicity) ) { $questions_criteria[] = "`ethnicity` = '$ethnicity'"; } if( !empty($bodytype) ) { $questions_criteria[] = "`body_type` = '$bodytype'"; } if( !empty($children) ) { $questions_criteria[] = "`children` = '$children'"; } if( !empty($education) ) { $questions_criteria[] = "`education` = '$education'"; } $query .= implode( ' AND ', $questions_criteria ); $query .= ' LIMIT $skip, 2 )'; } echo "<table width='100%' align='center'>"; if( $result = mysql_query( $query ) ) { if( mysql_num_rows($result) > 0 ) { while( $rr3 = mysql_fetch_assoc($result) ) { $user=clean_up($rr3[id]); $first=clean_up($rr3[first]); $last=clean_up($rr3[last]); $avatar=clean_up($rr3['avatar']); $about=clean_up($rr3[about]); echo "<tr><td valign='top' width='140' class='content'><center><img src='avatars/thumb/$avatar' /><br><a href='index.php?action=profile&id=$user'> $first $last</a></center></td><td class='content' valign='top'>".limitdesc($about)."</td></tr>"; } } else { echo '<tr><td colspan="2">Sorry, your search returned no results.</td></tr>'; } } else { echo '<tr><td colspan="2">We\'re sorry, there has been an error processing your request. Please try later.</td></tr>'; } echo "</table>"; echo "<div class='content'><center>"; if($getpage == 0 || $getpage == 1){}else{ $plink = $getpage - 1; echo " <a href='index.php?action=search&page=$plink'>Previous</a> "; } echo "<select id='ddp' onchange='document.location=(ddp.value)'> <option value=''>Page #</option>"; for ($i = 1; $i <= $page_count; ++$i){ echo ' <option value="index.php?action=search&page=' . $i . '">' . $i . '</option>'; } echo "</select>"; if($getpage == $page_count){}else{ if($page_count>1){ if($getpage == 0){ echo " <a href='index.php?action=search&page=2'>Next</a> "; }else{ $nlink = $getpage + 1; echo " <a href='index.php?action=search&page=$nlink'>Next</a> "; } } } echo "</center></div>"; } include ('footer.php'); ?> I keep getting these errors: Code: [Select] Warning: Cannot modify header information - headers already sent by (output started at /home/gamersgo/public_html/datingsnap.com/header.php:4) in /home/gamersgo/public_html/datingsnap.com/pages/search.php on line 182 Warning: Cannot modify header information - headers already sent by (output started at /home/gamersgo/public_html/datingsnap.com/header.php:4) in /home/gamersgo/public_html/datingsnap.com/pages/search.php on line 183 the errors are coming from the setcookie lines. any idea why its spitting out that? and when I search, the results don't come out to two results per page. so the pagination isn't working right and i am getting those errors. any ideas? Hi every one im getting an error 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 '' at line 1 SELECT * FROM Code: [Select] if(isset($_GET['subid'])){ $id = $_GET['subid']; } $query = mysql_query("SELECT * FROM sub_nav WHERE subNav_ID=" . mysql_real_escape_string((int)$id)); $row = mysql_fetch_assoc($query); $table = strtolower($row['subNavName']); // ******************************* This if statment controls the content ************************ if($row['show_hide'] == 1){ $per_page = 2; $pages_query = mysql_query("SELECT COUNT('id') FROM textiles"); $pages = ceil(mysql_result($pages_query, 0) / $per_page); $page = (isset($_GET['p']) AND (int)$_GET['p'] > 0) ? (int)$_GET['p'] : 1; $start = ($page-1) * $per_page; $query = mysql_query("SELECT imageName FROM textiles LIMIT $start, $per_page"); while ($query_row = mysql_fetch_assoc($query)){ echo '<p>',$query_row['imageName'] , '</p>'; } if ($pages >= 1){ for($x=1; $x<=$pages; $x++){ echo '<a href="?p='.$x.'">'.$x.'</a> '; } } Can any one help please My php/mysql book doesn't cover pagination so I've been searching the web for a simple pagination script that I can learn from. I got the following one working at http://www.phpsimplicity.com/tips.php?id=1 but it's just showing the next and prev links... no results on the pages and you can click on the next link forever when there's only 11 records in the table I queried. How can I display results on each page and have the info append to the next page? This is the second example I've tried and none seem to explain this part? I can't get my head around it, no matter how many tutorials I read.. So would anyone be able to put this code into a pagination of 3 per page? Many Thanks Code: [Select] <?php if(!$_GET['id']) { $query = "SELECT * FROM news where published = '1' ORDER by id DESC"; $result = mysql_query($query) or die(mysql_error()); $news = mysql_fetch_assoc($result); ?> <?php do { ?> <table width="590" border="0" cellspacing="0" cellpadding="0"> <tr> <td colspan="2"><h2><? echo $news['title']; ?></h2></td> </tr> <tr> <td width="398"><? echo $news['story']; ?></td> <td width="192"><img src="<? echo $news['image']; ?>" alt="<? echo $news['shortstory']; ?>" width="192" height="108" /></td> </tr> <tr> <td colspan="2"><i><br /> Posted by <? echo $news['author']; ?> on <? echo $news['date']; ?></i></td> </tr> </table><br /> <?php } while ($news = mysql_fetch_assoc($result)); } ?> I need a little help trying to figure this out. I have a page that pulls up data, you can then click on one and go to a page with more detail. On this page you can use the PRrev & Next to go view another detail page on other data. My problem is if my 1st page has 6 sets of data on it but has a total of, say 50, you can only use the Prev & Next to view the 6. I want to be able to use the Prev & Next to go thru all 50. ie Page1 pulls this info data1 data2 data3 data4 data5 data6 < << 1 2 [3] 4 5 6 > >> Page2 Data 1 Lots of info about data 1 < Prev Next > You will only be able to view the 6 data sets in the table above, however there are 50 I want to be able to use the < Prev Next > to go to all of them Can someone help me with this? here is my code Page1 <?php session_start(); // session timing // set timeout period in seconds $inactive = 120; // check to see if $_SESSION['timeout'] is set if(isset($_SESSION['timeout']) ) { $session_life = time() - $_SESSION['timeout']; if($session_life > $inactive) { session_destroy(); } } $_SESSION['timeout'] = time(); // END session timing include('library/login.php'); login(); mysql_select_db('test'); // sets the sessions for all values $_SESSION=array_merge($_SESSION,$_POST); // echoing to verify $gender=$_SESSION[gender]; $genderPref=$_SESSION[genderPref]; echo "Chossen Gender".$_SESSION['gender']; echo "<br><Br>"; echo "GenderPref".$_SESSION['genderPref']; echo "<br><Br>"; // if the user has been timed out or not logged in if (!isset($_SESSION['clientID'])){ echo "You are not a register user - set this to a simple search form"; echo "<br><a href='form.php'>Form</a>"; } // user is logged in else { $clientID = $_SESSION['clientID']; $sql="SELECT * FROM user WHERE userID='$clientID'"; $result=mysql_query($sql); while ($r=mysql_fetch_array($result)) { $exp_date=$r["exp_date"]; $todays_date=date("Y-m-d"); } // verifies billing if ($exp_date >= $todays_date) { // billing is up to date $result = mysql_query("SELECT * FROM user WHERE gender='$gender'") or die(mysql_error()); // ------ Sets the display of data ------ $num_rows = mysql_num_rows($result); // number of rows to show per page $rowsperpage = 8; // find out total pages $totalpages = ceil($num_rows / $rowsperpage); // get the current page or set a default if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) { // cast var as int $currentpage = (int) $_GET['currentpage']; } else { // default page num $currentpage = 1; } // end if // if current page is greater than total pages... if ($currentpage > $totalpages) { // set current page to last page $currentpage = $totalpages; } // end if // if current page is less than first page... if ($currentpage < 1) { // set current page to first page $currentpage = 1; } // end if // the offset of the list, based on current page $offset = ($currentpage - 1) * $rowsperpage; $result = mysql_query("SELECT * FROM user WHERE gender='$gender' LIMIT $offset, $rowsperpage")or die(mysql_error()); $num_rows = mysql_num_rows($result); if ($num_rows == 0){ echo "<div id='noResults'><span class='sorry'>Sorry</span>, no results found. <br> Please try again with broader search options.</div>"; } else { // format for search results $cells_wide = 2; echo " <table cellspacing='0' cellpadding='3' border='0' width='700'><tr> "; $c = 0; while ($r=mysql_fetch_array($result)) { $userID=$r["userID"]; $gender=$r["gender"]; $aUserIDs[] = $userID; if (0 < $c && 0 == $c % $cells_wide){ echo " </tr><tr> "; } echo " <td width=175> "; echo "<a href='profileSession.php?userID=$r[userID]'>$userID</a>, $gender</td>"; $c++; } // end of while echo " </tr>"; echo " </table> "; } // -------- BUILD THE PAGINATION LINKS -------------------------------- $_SESSION['userID']=$aUserIDs; $_SESSION['userID2']=$aUserIDs2; echo "<div id='navigation'>"; // range of num links to show $range = 3; // if not on page 1, show back links if ($currentpage > 1) { // show << link to go back to page 1 echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1&gender=$genderPref&genderPref=$gender&ageMin=$ageMin&ageMax=$ageMax&year1=$year1&year2=$year2'>‹‹ </a> "; // get previous page num $prevpage = $currentpage - 1; // show < link to go back to 1 page echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage&gender=$genderPref&genderPref=$gender&ageMin=$ageMin&ageMax=$ageMax&year1=$year1&year2=$year2'> ‹ </a> "; } // END if ($currentpage > 1) // loop to show links to range of pages around current page for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) { // if it's a valid page number... if (($x > 0) && ($x <= $totalpages)) { // if we're on current page... if ($totalpages == 1) { echo ""; } else{ if ($x == $currentpage) { // 'highlight' it but don't make a link echo " [<b>$x</b>] "; // if not current page... } // END if ($x == $currentpage) else { // make it a link echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x&gender=$genderPref&genderPref=$gender&ageMin=$ageMin&ageMax=$ageMax&year1=$year1&year2=$year2'>$x</a> "; } // END else } // END else } // END if (($x > 0) && ($x <= $totalpages)) } // END for loop // if not on last page, show forward and last page links if ($totalpages == 0) { echo ""; } else{ if ($currentpage != $totalpages) { // get next page $nextpage = $currentpage + 1; // echo forward link for next page echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage&gender=$genderPref&genderPref=$gender&ageMin=$ageMin&ageMax=$ageMax&year1=$year1&year2=$year2'> › </a> "; // echo forward link for lastpage echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages&gender=$genderPref&genderPref=$gender&ageMin=$ageMin&ageMax=$ageMax&year1=$year1&year2=$year2'>›› </a> "; } // END if ($currentpage != $totalpages) }// END else echo "<br>currentpage=$currentpage&gender=$genderPref&genderPref=$gender&ageMin=$ageMin&ageMax=$ageMax&year1=$year1&year2=$year2"; $link='currentpage='; $link1='&gender='; $link2='&genderPref='; $link3='&ageMin='; $link4='&ageMax='; $link5='&year1='; $link6='&year2='; $total=$link.$currentpage.$link1.$genderPref.$link2.$gender.$link3.$ageMin.$link4.$ageMax.$link5.$year1.$link6.$year2; $_SESSION['pages']=$total; echo "<br>$total"; // -------- END PAGINATION -------------------------------------------- } // END if ($exp_date >= $todays_date) else { // billing has expired echo "Billing has expired<br>"; echo $_SESSION['clientID']; echo "<br><a href='session2.php'>Sesssion2</a>"; echo "<br><a href='form.php'>Form</a>"; } } // END valid session ?> Page2 <?php session_start(); // start up your PHP session! include('library/login.php'); login(); mysql_select_db('test'); $userID=$_GET["userID"]; $link=$_SESSION['pages']; // Sends back to display page echo "<a href='searchSession.php?$link' title='Back to Search'>Back to Search</a> "; // sets the Prev & Next $aUsers = isset($_SESSION['userID']) ? $_SESSION['userID'] : array(); $current = $userID; // Ok our current. $iCurKey = array_search($current, $aUsers); $prev = null; $next = null; if ($iCurKey !== false){ $prev = $iCurKey >= 1 ? $aUsers[$iCurKey - 1] : null; $next = $iCurKey < count($aUsers) - 1 ? $aUsers[$iCurKey + 1] : null; } // Lets do this simple. if ($prev !== null){ echo ' <A href="?userID=' . $prev . '">« Previous</A> '; } else{ echo " <span class='empty'>« Previous</span> "; } if ($next !== null){ echo '<A class=right href="?userID=' . $next . '">Next »</A> '; } else{ echo "<span class='empty'> Next »</span>"; } // END of the Prev & Next $result = mysql_query("SELECT userID, first_name, gender FROM user WHERE userID='$userID'") or die(mysql_error()); while ($r=mysql_fetch_array($result)){ $userID=$r["userID"]; $first_name=$r["first_name"]; $gender=$r["gender"]; } echo "<br>$userID, $first_name, $gender"; ?> Sorry to bug yalls with yet another problem, but I tried applying pagination to the page I use to display the news on my website, which is stored within mysql, and I'm having major issues. Here's the code below for both the pagination and getting the news out of the database to display. Not sure what's going on here. I tested the script and it does everything fine except it doesn't display the information stored within the database. Go here to see for yourself: http://www.djsmiley.net/index.php Code: [Select] <?php /* Place code to connect to your DB here. */ include('cms/news/dbconnect.php'); // include your code to connect to DB. $tbl_name="mynews"; //your table name // How many adjacent pages should be shown on each side? $adjacents = 3; /* First get total number of rows in data table. If you have a WHERE clause in your query, make sure you mirror it here. */ $query = "SELECT COUNT(*) as num FROM $tbl_name"; $total_pages = mysql_fetch_array(mysql_query($query)); $total_pages = $total_pages[num]; /* Setup vars for query. */ $targetpage = "index.php"; //your file name (the name of this file) $limit = 1; //how many items to show per page $page = $_GET['page']; if($page) $start = ($page - 1) * $limit; //first item to display on this page else $start = 0; //if no page var is given, set start to 0 /* Get data. */ $sql = "SELECT 10 FROM $tbl_name LIMIT $start, $limit"; $result = mysql_query($sql); /* Setup page vars for display. */ if ($page == 0) $page = 1; //if no page var is given, default to 1. $prev = $page - 1; //previous page is page - 1 $next = $page + 1; //next page is page + 1 $lastpage = ceil($total_pages/$limit); //lastpage is = total pages / items per page, rounded up. $lpm1 = $lastpage - 1; //last page minus 1 /* Now we apply our rules and draw the pagination object. We're actually saving the code to a variable in case we want to draw it more than once. */ $pagination = ""; if($lastpage > 1) { $pagination .= "<div class=\"pagination\">"; //previous button if ($page > 1) $pagination.= "<a href=\"$targetpage?page=$prev\"><img class=\"fltlft2\" src=\"http://www.djsmiley.net/images/Icons/Arrows/Previous.png\" height=\"25\" width=\"25\"></a>"; else $pagination.= "<span class=\"disabled\"><img class=\"fltlft2\" src=\"http://www.djsmiley.net/images/Icons/Arrows/Previous.png\" height=\"25\" width=\"25\"></a></span>"; //pages if ($lastpage < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up { for ($counter = 1; $counter <= $lastpage; $counter++) { if ($counter == $page) $pagination.= "<span class=\"current\">$counter</span>"; else $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>"; } } elseif($lastpage > 5 + ($adjacents * 2)) //enough pages to hide some { //close to beginning; only hide later pages if($page < 1 + ($adjacents * 2)) { for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++) { if ($counter == $page) $pagination.= "<span class=\"current\">$counter</span>"; else $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>"; } $pagination.= "..."; $pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1</a>"; $pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage</a>"; } //in middle; hide some front and some back elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)) { $pagination.= "<a href=\"$targetpage?page=1\">1</a>"; $pagination.= "<a href=\"$targetpage?page=2\">2</a>"; $pagination.= "..."; for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++) { if ($counter == $page) $pagination.= "<span class=\"current\">$counter</span>"; else $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>"; } $pagination.= "..."; $pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1</a>"; $pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage</a>"; } //close to end; only hide early pages else { $pagination.= "<a href=\"$targetpage?page=1\">1</a>"; $pagination.= "<a href=\"$targetpage?page=2\">2</a>"; $pagination.= "..."; for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++) { if ($counter == $page) $pagination.= "<span class=\"current\">$counter</span>"; else $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>"; } } } //next button if ($page < $counter - 1) $pagination.= "<a href=\"$targetpage?page=$next\"><img src=\"http://www.djsmiley.net/images/Icons/Arrows/Next.png\" height=\"25\" width=\"25\"></a>"; else $pagination.= "<span class=\"disabled\"><img src=\"http://www.djsmiley.net/images/Icons/Arrows/Next.png\" height=\"25\" width=\"25\"></span>"; $pagination.= "</div>\n"; } ?> <?php while($row = mysql_fetch_array($result)) { echo("<p class=NewsContainer><span class=NewsID>$type</span> <font size=5>$title</font><br><br> <em>posted by <strong>$user</strong> | added on $time</em><br><br> $message<br><br> <label class=fltlft2><img src=../images/Icons/Arrows/Right.png width=20 height=20/></label><a href=$url>Read more - $url</a> <div class=newsLikeShareRate> <table width=100% border=0> <tr> <td width=3% height=21><script src=http://connect.facebook.net/en_US/all.js#xfbml=1></script> <fb:like href='$url' show_faces=true width=450 font=arial></fb:like> </td> <td width=65%><a name=fb_share id=fb_share4 type=icon_link share_url=$url>Share</a> <script src=http://static.ak.fbcdn.net/connect.php/js/FB.Share type=text/javascript></script></td> <td width=32%>Rate this article: </td> </tr> </table> </div></p><br><br>");// Your while loop here } ?> <?=$pagination?> |