pagination in php and keeping results - php

have tried to implement a pagination script in my php code (adopted from a sample code i found on the net)
the page returns resaults of a mysql query. the default is an empty 'keyword' which returns all data from databse.
succeeded as far as pagination works when all data is returned but when i filter results through a keyword search clicking 'next page' returns the next page in unfiltered results (ie the searched keyword is lost in the refresh)
this is the relevant code (hope it makes sense):
Blockquote
$txt1='<A HREF="/memimomedia/music/128kb/';
$txt2='" ><IMG src="/Save.png" width="24" height="24" align="middle" border="0"></A>';
$txt9a='<a href="';
$txt9b='" target="_blank">';
$txt9c='</a>';
$txt10a='<audio src="./128kb/';
$txt10d='" controls></audio>';
if(empty($_POST['searchkeywords']) && empty($_GET['searchkeywords'])) { $result = mysql_query("SELECT *
FROM ppl_tracks WHERE Mixed !='0' ORDER BY Track"); }
if(!empty($_GET['searchkeywords'])) { $Searchword=$_GET['searchkeywords']; }
if(!empty($_POST['searchkeywords'])) { $Searchword=$_POST['searchkeywords']; }
$Totalresults = mysql_query("SELECT Track FROM (ppl_tracks LEFT JOIN
TrackStyle ON ppl_tracks.RECNO = TrackStyle.TrackID LEFT JOIN
StyleTable ON TrackStyle.StyleID = StyleTable.ID) LEFT JOIN TrackMood
ON ppl_tracks.RECNO = TrackMood.TrackID LEFT JOIN MoodTable ON
TrackMood.MoodID = MoodTable.ID WHERE (MoodChoices LIKE
'%$Searchword%' OR Description LIKE '%$Searchword%' OR StyleChoices
LIKE '%$Searchword%' OR Tempo LIKE '%$Searchword%' OR Track LIKE
'%$Searchword%' ) AND Mixed =true GROUP BY Track ORDER BY Track" );
//This checks to see if there is a page number. If not, it will set it
to page 1 if(isset($_GET['pagenum'])) { $pagenum =
$_GET['pagenum']; } else { $pagenum = 1; }
//Here we count the number of results
$hits = mysql_num_rows($Totalresults);
//This is the number of results displayed per page
$page_hits = 15;
//This tells us the page number of our last page
$last = ceil($hits/$page_hits);
//this makes sure the page number isn't below one, or more than our
maximum pages
if ($pagenum < 1)
{
$pagenum = 1;
}
elseif ($pagenum > $last)
{
$pagenum = $last;
}
//This sets the range to display in our query
$max = 'limit ' .($pagenum - 1) * $page_hits .',' .$page_hits;
$result = mysql_query("SELECT * FROM (ppl_tracks LEFT JOIN TrackStyle
ON ppl_tracks.RECNO = TrackStyle.TrackID LEFT JOIN StyleTable ON
TrackStyle.StyleID = StyleTable.ID) LEFT JOIN TrackMood ON
ppl_tracks.RECNO = TrackMood.TrackID LEFT JOIN MoodTable ON
TrackMood.MoodID = MoodTable.ID WHERE (MoodChoices LIKE
'%$Searchword%' OR Description LIKE '%$Searchword%' OR StyleChoices
LIKE '%$Searchword%' OR Tempo LIKE '%$Searchword%' OR Track LIKE
'%$Searchword%' ) AND Mixed =true GROUP BY Track ORDER BY Track $max"
);
echo " Track -
Artist Description Download ";
$color="1";
while($row = mysql_fetch_array($result)) { $SelectedStyles =
array(); $Track=$row['Track']; $SelectedStylesQuery = mysql_query("
SELECT StyleChoices FROM ppl_tracks LEFT JOIN TrackStyle ON
ppl_tracks.RECNO = TrackStyle.TrackID LEFT JOIN StyleTable ON
TrackStyle.StyleID = StyleTable.ID WHERE ppl_tracks.Track='$Track'");
while($row1 = mysql_fetch_array($SelectedStylesQuery)) {
$SelectedStyles[] = $row1[StyleChoices]; } $SelectedMoods = array(); $SelectedMoodsQuery = mysql_query(" SELECT MoodChoices FROM
ppl_tracks LEFT JOIN TrackMood ON ppl_tracks.RECNO = TrackMood.TrackID
LEFT JOIN MoodTable ON TrackMood.MoodID = MoodTable.ID WHERE
ppl_tracks.Track='$Track'"); while($row2 =
mysql_fetch_array($SelectedMoodsQuery)) {
$SelectedMoods[] = $row2[MoodChoices]; } sort($SelectedMoods); sort($SelectedStyles); $stringS= implode(", ", $SelectedStyles);
$stringM= implode(", ", $SelectedMoods);
if($color==1) { echo ""; echo "" . $row['Track'] . " - " .
ucwords($row['Artist']) . ""; echo "" . $stringM .
"".$stringS.""; echo "" . $txt1.$row['FileName'].$txt2 .
""; echo "" . $txt10a.$row['FileName'].$txt10d."";
echo ""; $color="2"; }
else { echo ""; echo "" . $row['Track'] . " - " .
ucwords($row['Artist']) . ""; echo "" . $stringM .
"".$stringS.""; echo "" . $txt1.$row['FileName'].$txt2 .
""; echo "" . $txt10a.$row['FileName'].$txt10d."";
echo ""; $color="1";}
} echo "";
// This shows the user what page they are on, and the total number of
pages
echo " --Page $pagenum of $last-- "; // 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 " <<-First ";
echo " - "; $previous = $pagenum-1; echo " <-Previous "; }
$counter=1; while ( $counter <= $last )
{
if ($counter==$pagenum)
{
echo " - ";
echo " $counter ";
echo " - ";
}
else
{
echo " - ";
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$counter'>$counter</a> ";
echo " - ";
} $counter = $counter + 1; }
//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 " Next -> "; echo " -
"; echo " Last ->>
"; } mysql_close($con); ?>

You are reloading the page every time you go onto a new page, so you need to pass the search term into the page again. The easiest way to do this is to update your link for pagination to the following:
echo " <a href='{$_SERVER['PHP_SELF']}?searchkeywords=" . $_REQUEST["searchkeywords"] . "&pagenum=$counter'>$counter</a> ";
$_REQUEST will handle both $_POST and $_GET variables, but you may want to do this in your own way. Simply put you just need to pass the searchkeywords back into your url

Related

Paginate multiple search query using single file

I have one file example.com/search_category.php. There are different subcategories in database. I don't want to open file for each category, rather I want to paginate using single file. If I open file for each category such as example.com/search_category/subcategory1.php, example.com/search_category/subcategory2.php etc then there is no problem. How is it possible to paginate using single file. I am using the following pagination code. Thanks in advance.
// how many rows to show per page
$rowsPerPage = 5;
// by default we show first page
$page_num = 1;
// if $_GET['page'] defined, use it as page number, $_GET gets the page number out of the url
//set by the $page_pagination below
if(isset($_GET['page'])){$page_num = $_GET['page'];}
//the point to start for the limit query
$offset = ($page_num - 1) * $rowsPerPage;
// Zero is an incorrect page, so switch the zero with 1, mainly because it will cause an error with the SQL
if($page_num == 0) {$page_num = 1;}
// counting the offset
$sql = "SELECT * FROM xyz WHERE subcategory='$subcategory' ORDER BY info_id ASC LIMIT $offset, $rowsPerPage ";
$res = mysql_query($sql) or die(mysql_error());
// how many rows we have in database
$sql2 = "SELECT COUNT(subcategory) AS numrows FROM xyz WHERE subcategory= '$subcategory' ";
$res2 = mysql_query($sql2) or die(mysql_error());
$row2 = mysql_fetch_array($res2);
$numrows = $row2['numrows'];
// print the random numbers
while($row = mysql_fetch_array($res))
{
extract ($row);
//Echo out your table contents here.
echo "<tr class=\"alt\" onmouseover=\"ChangeColor(this, true);\" \n";
echo "style=\"cursor: pointer;\"\n";
echo " onmouseout=\"ChangeColor(this, false);\" \n";
echo " onclick=\"DoNav('http://www.example.com/searched_page.php?info_id={$info_id}');\">\n";
echo "\n";
$info_id = $row['info_id'];
echo "</td>";
echo "<td>". $info_id . "</td>";
echo "<td>". $bname . "</td>";
echo "<td>". $text . "</td>";
echo "</tr>";
}
?>
<?php
// how many pages we have when using paging?
$maxPage = ceil($numrows/$rowsPerPage);
$self = "http://www.example.com/search_category.php";
// creating 'previous' and 'next' link
// plus 'first page' and 'last page' link
// print 'previous' link only if we're not
// on page one
if ( $page_num > 1 ) {
$page = $page_num - 1;
$prev = " [Prev] ";
$first = " [First Page] ";
} else {
$prev = ' [Prev] '; // we're on page one, don't enable 'previous' link
$first = ' [First Page] '; // nor 'first page' link
}
// print 'next' link only if we're not
// on the last page
if ( $page_num < $maxPage ) {
$page = $page_num + 1;
$next = " [Next] ";
$last = " [Last Page] ";
} else {
$next = ' [Next] '; // we're on the last page, don't enable 'next' link
$last = ' [Last Page] '; // nor 'last page' link
}
// print the page navigation link
//echo $first . $prev . " Showing page <strong>$page_num</strong> of <strong>$maxPage</strong> pages " . $next . $last;
?>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="center" class="smaller">
<?php
// print the page navigation link
echo '<br>';
echo $first . $prev . " Page <strong>$page_num</strong> of <strong>$maxPage</strong>" . $next . $last;
?>
</table>

Problems with pagination

I am working on a university project, which is based on e-shopping, i tried this code to implement my result, this gives no error but it does not work when I press next page link or "button" please help any help would be appreciated
<?php
$con = mysqli_connect("localhost","root","","php184_proj_db");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (!(isset($pagenum)))
{
$pagenum = 1;
}
//Here we count the number of results
//Edit $qry to be your query
$qry = "SELECT * FROM posts";
$result = mysqli_query($con,$qry);
$row = mysqli_num_rows($result);
//This is the number of results displayed per page
$page_rows = 5;
//This tells us the page number of our last page
$last = ceil($row/$page_rows);
//this makes sure the page number isn't below one, or more than our maximum pages
if ($pagenum < 1)
{
$pagenum = 1; //Pagination of MySQL Query Results Setting the Variables
}
elseif ($pagenum > $last)
{
$pagenum = $last;
}
//This sets the range to display in our query
$max = 'limit ' .($pagenum - 1) * $page_rows .',' .$page_rows;
$j=0;
$qry = "SELECT * FROM posts $max";
$result = mysqli_query($con,$qry);
while($row = mysqli_fetch_array($result))
{
$j++;
echo "<p>";
// This shows the user what page they are on, and the total number Query and Results of pages
echo " --Page $pagenum of $last--
<p>";
// First we check if we are on page one. If we are then we don't need a
//link to the previous page or the first page so we do nothing. If we aren't
//then we generate links to the first page, and to the previous page.
if ($pagenum == 1)
{
}
else
{
echo " <a
href='{$_SERVER['PHP_SELF']}?pagenum=1'>
<<-First</a>
";
echo " ";
$previous = $pagenum-1;
echo " <a
href='{$_SERVER['PHP_SELF']}?
pagenum=$previous'> <-Previous</a>
";
}
//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['PHP_SELF']}?pagenum=$next'>Next
-></a> ";
echo " ";
echo " <a
href='{$_SERVER['PHP_SELF']}?pagenum=$last'>Last
->></a> ";
}
?>
If you visit this URL: http://example.com/somepage.php?key=val, you don't automatically get a variable $key inside PHP. Instead, you have to use $_GET['key'], which will hold the value. (in this case: 'val')
So, somewhere in the beginning of your code, add the following:
if (isset($_GET['pagenum']) && $_GET['pagenum'] >= 1) {
$pagenum = (int) $_GET['pagenum'];
} else {
$pagenum = 1;
}
Not only does this create the $pagenum variable and give it the value from the URL, it also makes sure that the value is a valid number. If not, or if the URL doesn't contain a pagenum, it is set to 1.
Possible scenario's:
pagenum contains not an integer, but a string (might even be a SQL injection attempt)
pagenum is a negative number, or 0
pagenum isn't set at all
In all of the above cases, pagenum is set to 1.
If pagenum contains a float (for instance 1.5.), the value will be cast to an integer. In the case of 1.5, pagenum will become 1.
Remember, always make sure you sanitize user input.

PHP pagination add ID

I have a kind of problem, with following php code:
$host="localhost";
$user_name="";
$pwd="";
$database_name="";
$conexiune = mysql_connect($host,$user_name,$pwd) or die("Nu ma pot conecta la MySQL!");
mysql_select_db($database_name, $conexiune) or die("Nu gasesc baza de date");
if (isset($_GET["page"])) {
$page = $_GET["page"];
} else {
$page=1;
};
$start_from = ($page-1) * 1;
$sql = "SELECT * FROM citate ORDER BY id DESC LIMIT $start_from, 1";
$rs_result = mysql_query ($sql,$conexiune);
while ($row = mysql_fetch_assoc($rs_result))
echo "<img src='" . $row['poza'] . "' />
<br />
" . $row['titlu'] . "
<br />
" . $row['descriere'] . "
<br />
" . $row['data'] . "
";
$sql = "SELECT COUNT(id) FROM citate";
$rs_result = mysql_query($sql,$conexiune);
$row = mysql_fetch_row($rs_result);
$total_records = $row[0];
$total_pages = ceil($total_records / 1);
$pagelink ='<< ';
$pagelink_2='>> ';
if($page>1)
echo $pagelink;
if($page<2)
echo "";
for ($i=1; $i<=$total_pages; $i++) {
if ($i != $page)
echo "<a href='lista.php?page=".$i."'>".$i."</a> "; // xxxx = your page url address
if ($i==$page)
echo " <strong>". $i . "</strong> "; // defining class in the style sheet you can add colour or border to the displayed number
};
if($page<$total_pages)
echo $pagelink_2;
that code offer me pagination (u allready know that) , and the url bar adress look's like following:
http://www.site.ro/folder/lista.php?page=PAGE-NUMBER
i want to look like following:
http://www.site.ro/folder/lista.php?citat=SOME-NUMBERS&page=PAGE-NUMBER
my database table its populated like that:
--------------------------------------------------------------
| id | poza | titlu | descriere | citat | data | accesari |
--------------------------------------------------------------
i want to extract data from "citat" column , so link from url bar will look like:
http://www.site.ro/folder/lista.php?citat=EXTRACTED-FROM-CITAT&page=PAGE-NUMBER
every time when i press on next page buton, will look like:
http://www.site.ro/folder/lista.php?citat=2748925&page=1
http://www.site.ro/folder/lista.php?citat=2840194&page=2
etcetera..
how can i modify that code?
Thank in advance !
I am ignoring all your security issues.
This will work as long you display only one item per page:
$last_citat = 0;
while ($row = mysql_fetch_assoc($rs_result)) {
echo "<img src='" . $row['poza'] . "' /><br />" . $row['titlu'] . "<br />" . $row['descriere'] . " <br />" . $row['data'] . "";
$last_citat = $row['citat'];
}
and later:
$pagelink ='<< ';
$pagelink_2='>> ';
if($page>1) { echo $pagelink; }
if($page<2) { echo ""; }
for ($i=1; $i<=$total_pages; $i++) {
if ($i != $page) {
echo "<a href='lista.php?citat=".$last_citat."&page=".$i."'>".$i."</a> ";
}
if ($i==$page) {
echo " <strong>". $i . "</strong> ";
}
}
Do you want to filter database results by 'citat' value?
If so, then you have to build links with get parameter 'citat' in them, like:
<<
and later take GET['citat'] and add it in the sql query where part so that only results with certain citat value would be returned, like:
$sql = "SELECT * FROM citate WHERE citat = '".GET['citat']."' ORDER BY id DESC LIMIT $start_from, 1";
NOTE: This is not real example and it is WRONG TO USE LIKE WRITTEN: you must escape GET['citat'] because otherwise your database will be hacked very easily and very soon!
Get value of citat from while loop:
$citat = $row['citat'];
Then you can use $citat wherever and however you want, and to check the citat parameter in url you can do it by:
if (isset($_GET['citat'])) {
//it's there do something
} else {
//it's absent
}

PHP Pagination issue mysql and php showing same data on all pages

I am having issues with some pagination with data i get from a MySQL database in PHP.
My code is below. Basically what happens is it creates the right amount of pages however each page shows the same data and doesn't even show only 5 rows per page.
I'm really stuck. This is my first time trying pagination. Any help would be greatly appreciated.
$pagenum = $_GET['pagenum'];
if (!(isset($pagenum)))
{
$pagenum = 1;
} else
{
$pagenum = $_GET['pagenum'];
}
//Count the number of results.
$data = mysql_query("SELECT * FROM `articles` WHERE `content` = '' AND `requestedby` != '$id'") or die(mysql_error());
$rows = mysql_num_rows($data);
//Set the number of results to be displayed per page.
$page_rows = 5;
//This tells us the page number of our last page
$last = ceil($rows/$page_rows);
//this makes sure the page number isn't below one, or more than our maximum pages
if ($pagenum < 1)
{
$pagenum = 1;
} elseif ($pagenum > $last)
{
$pagenum = $last;
}
//This sets the range to display in our query
$max = 'LIMIT ' . ($pagenum - 1) * $page_rows .',' .$page_rows;
//This is the query again, the same one... the only difference is we add $max into it.
$data_p = mysql_query("SELECT * FROM `articles` WHERE `content` = '' AND `requestedby` != '$id' '$max'") or die(mysql_error());
//Work out writers earnings based on prices.
//100 Words - $1.25
//300 Words - $2.50
//500 Words - $4.00
//700 Words - $5.50
//1000 Words - $8.00
$_100earnings = "0.65";
$_300earnings = "1.25";
$_500earnings = "2.50";
$_700earnings = "3.00";
$_1000earnings = "5.00";
?>
<!-- main -->
<div id="main">
<center><h2>Write Articles</h2></center>
<br />Available Projects:
<table border="1">
<tr>
<td>Title:</td>
<td>Length:</td>
<td>Writers Earnings:</td>
</tr>
<?php
//This is where you display your query results
while($info = mysql_fetch_array($data_p))
{
echo "<tr>";
echo "<td>" . $info['keywords'] . "</td>";
echo "<td>" . $info['length'] . "</td>";
switch ($info['length'])
{
case 100:
$writersearnings = $_100earnings;
break;
case 300:
$writersearnings = $_300earnings;
break;
case 500:
$writersearnings = $_500earnings;
break;
case 700:
$writersearnings = $_700earnings;
break;
case 1000:
$writersearnings = $_1000earnings;
break;
}
echo "<td>$" . $writersearnings . "</td>";
//echo $info['Name'];
echo "</tr>";
}
?>
</table>
<br /><br />
<?php
// This shows the user what page they are on, and the total number of pages
echo " --Page $pagenum of $last-- <p>";
// First we check if we are on page one. If we are then we don't need a link to the previous page or the first page so we do nothing. If we aren't then we generate links to the first page, and to the previous page.
if ($pagenum == 1)
{
} else
{
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=1'> <<-First</a> ";
echo " ";
$previous = $pagenum - 1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$previous'> <-Previous</a> ";
}
//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['PHP_SELF']}?pagenum=$next'>Next -></a> ";
echo " ";
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$last'>Last ->></a> ";
}
use this code, remove ' around $max in query, when you add ' around $max the query becomes select.... from.... where..... 'LIMIT.....' and it fails the query.
$data_p = mysql_query("SELECT * FROM `articles` WHERE `content` = '' AND `requestedby` != '$id' $max") or die(mysql_error());
You need to specify LIMIT in your query LIMIT offset,count
$data_p = mysql_query("SELECT * FROMarticlesWHEREcontent= '' ANDrequestedby!= '$id' '$max'") or die(mysql_error());
Remove the ' quotes from '$max'
$data_p = mysql_query("SELECT * FROM articles WHERE content= '' AND requestedby!= '".$id."' ".$max) or die(mysql_error());

PHP search suggestions

I have a PHP script which works with jQuery to provide search suggestions. It pulls results from a MySQL database. However, I only want 5 results to display at once for the letter the user has typed but it seems all of the results appear. Why could this be?
My code is:
<p id="searchresults"><?php
$db=new mysqli('localhost','username','password','database');
if(isset($_POST['queryString'])){
$queryString=$db->real_escape_string($_POST['queryString']);
if(strlen($queryString)>0){
$query = $db->query("SELECT * FROM search s WHERE name LIKE '%" . $queryString . "%'");
if($query){
while ($result = $query ->fetch_object()){
echo '<a href="/search/'.$result->name.'/1/">';
$name=$result->name;
echo ''.$name.'';
}
}
}
}
?></p>
I hope you can understand what I am trying to describe.
Change "SELECT * FROM search s WHERE name LIKE '%" . $queryString . "%'"
to "SELECT * FROM search s WHERE name LIKE '%" . $queryString . "%' LIMIT 5"
if you want to limit it to 5 results.
You need to add pagination code to your page:
There is the sample code:
<?php
// Connects to your Database
mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error());
mysql_select_db("address") or die(mysql_error());
//This checks to see if there is a page number. If not, it will set it to page 1
if (!(isset($pagenum)))
{
$pagenum = 1;
}
//Here we count the number of results
//Edit $data to be your query
$data = mysql_query("SELECT * FROM topsites") or die(mysql_error());
$rows = mysql_num_rows($data);
//This is the number of results displayed per page
$page_rows = 4;
//This tells us the page number of our last page
$last = ceil($rows/$page_rows);
//this makes sure the page number isn't below one, or more than our maximum pages
if ($pagenum < 1)
{
$pagenum = 1;
}
elseif ($pagenum > $last)
{
$pagenum = $last;
}
//This sets the range to display in our query
$max = 'limit ' .($pagenum - 1) * $page_rows .',' .$page_rows;
//This is your query again, the same one... the only difference is we add $max into it
$data_p = mysql_query("SELECT * FROM topsites $max") or die(mysql_error());
//This is where you display your query results
while($info = mysql_fetch_array( $data_p ))
{
Print $info['Name'];
echo "<br>";
}
echo "<p>";
// This shows the user what page they are on, and the total number of pages
echo " --Page $pagenum of $last-- <p>";
// First we check if we are on page one. If we are then we don't need a link to the previous page or the first page so we do nothing. If we aren't then we generate links to the first page, and to the previous page.
if ($pagenum == 1)
{
}
else
{
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=1'> <<-First</a> ";
echo " ";
$previous = $pagenum-1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$previous'> <-Previous</a> ";
}
//just a space
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['PHP_SELF']}?pagenum=$next'>Next -></a> ";
echo " ";
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$last'>Last ->></a> ";
}
?>
Source: www.twitter.com/ZishanAdThandar

Categories