Custom PHP Pagination - php

I use the code below to do a "next" and "previous" navigation. It works but even when there is 1 entry the next button shows and when there are more than 20 entries and once they have been served the code shows next and previous. How can I make it so that the next button will only show if there are more than 10 and how do I show no next and previous button if there are no more results to show:
if (!isset($_GET['pg']) or !is_numeric($_GET['pg'])) {
$startrow = 0;
} else {
$startrow = (int)mysql_real_escape_string($_GET['pg']);
}
echo '<a id=pgnvg href=
"'.$_SERVER['PHP_SELF'].'?pg='.($startrow+20).'& q='.($what).'">Next</a>';
$prev = $startrow - 20;
//only print a "Previous" link if a "Next" was clicked
if ($prev >= 0)
echo '<a id=pgnvg2 href="'.$_SERVER['PHP_SELF'].'?pg='.$prev.'">Previous</a>';

you need to add a check on how many items are actually returned e.g:
if($itemAmount > 20) {
echo '<a id=pgnvg href=
"'.$_SERVER['PHP_SELF'].'?pg='.($startrow+20).'& q='.($what).'">Next</a>';
}
otherwise the next button will always display

Assume that you have a variable $itemsCount containing the number of items into the recordset.
If you don't have one you can calculate it with a query like
count(*) FROM <wathever table or join> WHERE <list of conditions>
Further I would use a constant called ITEMS_ON_A_PAGE (Hope you will guess its content ;)
define ('ITEMS_ON_A_PAGE',20); // put it where more appropriate
...
if (!isset($_GET['pg']) or !is_numeric($_GET['pg'])) {
$startrow = 0;
} else {
// no need to issue a mysql query, you need an integer from a numeric variable
$startrow = (int)$_GET['pg'];
}
$linkTemplate = '<a id="%s" href="?%s">%s</a>';
$nextPageFirstItem = $startrow + ITEMS_ON_A_PAGE;
$previousPageFirstItem = $startrow - ITEMS_ON_A_PAGE;
if ($itemsCount> $nextPageFirstItem) {
echo printf($linkTemplate,
'pgnvg',
http_build_query(array('pg'=>$nextPageFirstItem,'q'=>$what)),
'Next'
);
}
if ($previousPageFirstItem >= 0) {
echo printf($linkTemplate,
'pgnvg2',
http_build_query(array('pg'=>$previousPageFirstItem,'q'=>$what)),
'Previous'
);
}
Here there is the reference for the http_build_query that creates the query for you
There will be a lot of room to improve this code but, as a starting point, it would suffice ;)

You might actually want to use a switch statement. Sometimes if statements stop working when you have too many of them and too many evaluate to be true. Just pay attention to when you want to break; vs not breaking (don't include break;).

Related

While echo - dont write mutiple lines, overwrite one instead

im trying to write a loop that displays the counter on one line, been sitting here for over an hour but cant figure it out.
The main loop is
while($counter< 100){
echo $counter;
usleep($timeInSeconds*1000000);
$counter=$counter+1;
}
Now this prints 100 numbers after a delay each on a new line. Is it possible for the echo to instead replace itself for each loop?
I tried many options, here is one that didnt crash:
while($counter < 100){
$counter=$counter+1;
echo $counter;
usleep($timeInSeconds*1000000);
flush();
ob_flush();
}
However, with this option it works in one line with a delay, but it doesnt clear the previous echo, so its just a bunch of number next to each other
Could someone help me out?
You are trying to do something on the server that should be done on the client.
I expect you are making a timer. You should write some JavaScript code instructing the web browser on how to display multiple numbers with a delay in between. Your current code will show a loading wheel and a blank screen for the entire duration on many browsers.
Instead, replace your loop with something like:
var time_in_seconds = 1; // You can replace 1 with the value of the PHP variable
var count_element = document.getElementById("example_counter");
var n = 0;
var interval_id;
function update_counter(){
n += 1;
if (n >= 100) {
clearInterval(interval_id);
}
count_element.textContent = n;
}
interval_id = setInterval(update_counter, time_in_seconds * 1000);
<span id="example_counter"></span>

Can you put multiple elements in an html <a> tag?

Is there any way to create a new a href that remembers all the submitted data earlier. I don't know how to say it properly so I will describe in the code:
The first button
Click me
After the user clicks it, he is redirected to the same page but with the new button :
Click me
And so on :
Click me
How do i create the n variable to be added and increased after the button is pressed ?
( I have a table displayed from a database by using the while command with mysqli_fetch_array($database); )
The table is created like (trivial ) :
$retrieve_items = mysql_query("SELECT * FROM items WHERE id > 0");
$col = 0;
echo '<table width=100% border= 1><tr>';
while($row = mysql_fetch_array( $retrieve_items )) {
$col ++;
echo '<td>'.$row['name_item'].'</td>';
if ($col % 5 == 0 )
{
echo '</tr><tr>';
}
}
echo '</tr></table>';
I recommend not to try managing numbered variable names. If there is no important reason to do so, it will make your logic unnecessarily complicated.
PHP understands array parameters in e.g. $_GET. They are passed from HTML with empty braces appended to the parameter name.
This is a little demo to illustrate this alternative approach:
<?php
// get the passed array or generate a new one
$n = isset($_GET['n']) ? (array) $_GET['n'] : [];
//ppend 2 random numbers
$n[] = rand(1,100);
$n[] = rand(1,100);
//output the link with GET parameters in query
?>
the link
<!-- or let PHP's built-in generate a propper query --><br>
the link
Be aware, that the second link generated by http_build_query contains indexes of the array, which are commonly based on 0.
in php, to access the current query String, you can use
$_SERVER['QUERY_STRING']
so you could so something like
Click me
or you could replace your previous value in the query string

Why is my pagination for the results not working?

I have an app that searches the database for active jobs and it returns them in a list of results. that part work fine, but the pagination is not working. when I click the link to go to the next 10 jobs it just stays in the same page.
here is what the code looks like.
$currPage = (($s/$limit) + 1);
// Links to access additional results
if ($s>=1) {
$prevs=($s-$limit);
$upd_msg_prev = '<< Prev 10 | ';
if ($s>$numrows-10) {
$upd_msg_next = 'Next 10 >>';
}
} else {
if ($numrows>10) {
$upd_msg_prev = '<< Prev 10 | ';
}
}
$here = isset($_POST['here']);
// calculate number of pages needing links
$pages=intval($numrows/$limit);
// Check how many $pages are needed by getting total plus one if there's a remainder
if ($numrows%$limit) {
$pages++;
}
// check to see if last page
if (!((($s+$limit)/$limit)==$pages) && $pages!=1) {
$news=($s+$limit);
$upd_msg_next = 'Next 10 >>';`
}
I think the problem is $here=isset...
That function will return true or false so it doesn't make sense using it in $upd_msg... further down in your code.

Pass $_GET variable to the next page

Right now im trying to code read other codes and make it work, because some of the projects that i have are made by other developers and i really have to learn reading other code, I already made this one work but the problem is when i try to incorporate this pagination code to a $_GET variable an error occur, when it load the first page everything thing is smooth but when i click the other pages the $_GET variable dies. i already found a code in the site but i can't really get how to incorporate it with the other code.
here is the code that "MIGHT" solve the problem solving pagination $_GET
printf('Next',$targetpage,http_build_query(array('page' => 2) + $_GET));
here is the part of the code that make the link 1 2 3 4. . . and so on
$range = 3;
// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1?srId=$srdd'><<</a> ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage?srId=$srdd'><</a> ";
} // end if
// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $totalpages)) {
// if we're on current page...
if ($x == $currentpage) {
// 'highlight' it but don't make a link
echo " [<b>$x</b>] ";
// if not current page...
} else {
// make it a link
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x?srId=$srdd'>$x</a> ";
} // end else
} // end if
} // end for
// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage?srId=$srdd'>></a> ";
// echo forward link for lastpage
//echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages?srId=$srdd'>>></a> ";
printf("<a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages?srId=$srdd'>>></a>");
} // end if
/****** end build pagination links ******/
?>
I already figured it out guys I saw lots for this problem on the web and also some on the forum here's how to solve it
<?php
session_start();
// store session data
if (isset($_GET["srId"]))
{
$_SESSION['variable']=$_GET["srId"];
$srdd = $_SESSION['variable'];
}
else
{
$srdd = $_SESSION['variable'];
$tableName = $srdd."r";
}
?>
thanks for your response guys.
You will need to use either session variables or cookies to pass them one page to another.
The $_GET global array will be a NEW array for every new page, assuming you're sending a GET request and it can be seen in the URL.
In general, the web is stateless which means it will not remember what you do from one page to another UNLESS you use cookies, sessions or a database for persistence.
Design your links
Page 1 | 2 | 3 | 4
to have the information in the link so they are ready for the next page
Page 1 = http://url?page=1&page_limit=25
Page 2 = http://url?page=2&page_limit=25
...
Etc
If the paginated links are in this format, these variables will be in the $_GET array.
Try replacing
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1?srId=$srdd'><<</a> ";
with
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1&srId=$srdd'><<</a> ";
After the initial '?' in a url, the following *'$_GET[]'* items should be separated from the preceeding one with an '&'. Note that your 'srId=$srdd' is preceeded by a '?'.
Example:
myurl.com?id=1234&page=help
Doing it this way will help you avoid having to store the information in the $_SESSION array, and keeps the URL secure.

PHP conditional processing required to display rotating banners continuously

I'm trying to do something a little different with a banner rotator.
Below is the script I am using to read two text files (stored on my root directory with .db extensions) to rotate banners on a website. One file holds a counter (FileDB), the other holds the HTML banner code (URLDB).
The URLDB file currently holds six lines of HTML code to display hyperlinked banners.
The following script builds an array and rotates these banners sequentially on the refresh of the page counting from 0 - 5, and it does this perfectly:
<?php
define('FILEDB', '/WORKING DIRECTORY/count.db');
define('URLDB', '/WORKING DIRECTORY/url.db');
function readURLS()
{
$fo = fopen(URLDB, 'r');
if( null == $fo )
return false;
$retval = array();
while (($line = fgets($fo)) !== false)
{
$retval[] = $line;
}
return $retval;
}
$list = readURLS();
if( false === $list )
{
echo "No URLs available";
}
else
{
$fo = fopen(FILEDB, 'a+');
$count = (fread($fo, filesize(FILEDB)) + 1) % count($list);
ftruncate($fo, 0);
fwrite($fo, "{$count}");
fclose($fo);
echo $list[$count];
}
?>
On the webpage that I want to display the banners there are eight placeholders. However I only have six banners.
Here is the PHP code in each of the placeholders:
Placeholder 1: <?php echo $list[$count];?>
Placeholder 2: <?php echo $list[$count +1];?>
Placeholder 3: <?php echo $list[$count +2];?>
Placeholder 4: <?php echo $list[$count +3];?>
Placeholder 5: <?php echo $list[$count +4];?>
Placeholder 6: <?php echo $list[$count +5];?>
Placeholder 7: <?php echo $list[$count +6];?>
Placeholder 8: <?php echo $list[$count +7];?>
With the count at 0 the 6 banners are displayed in placeholders 1 - 6 and placeholders 7 and 8 are blank.
With every refresh the counter is increase by one, showing each banner in the first placed holder and pulling the other banners through each placeholder from 5 through to 0, but leaving previously populated placeholders blank until the sixth banner is in placeholder one. Then on the next refresh banners 1 - 6 are once again shown.
This occurs because I've hardcoded the values in each placeholder and I am obviously attempting to reference an entry in the file that is out of the bounds of the array built by the above script.
You can see a working example here.
What I am trying to achieve is display all banners in the URLDB such that when the last entry is shown, the first entry is displayed in the next placeholder (which in this case is placeholder 7) and the 2nd entry is show in in placeholder 8.
The idea is that the banners move continuously through each of the placeholders like the carriages of a train with each page refresh and increment of the counter - one following the other.
So, now you have the background, on to my question.
Is there a way I can amend the script to store in a PHP variable the maximum number of entries in the URLDB file/array and subsequently add conditional processing in the placeholders to check when the counter reaches this maximum value, and reference the next valid value in the array (i.e. 0) such that the banners restart again in the surplus placeholders - so here are no blank or empty placeholders shown?
I imagine this might seem like a strange request. But of course I would appreciate any advice on how to achieve my goal based on where things are currently.
Once you use a loop things become a bit easier to manipulate.
Hopefully the following solves your problem.
$numOfBanners = count($list);
$numOfPlacements = 8;
for ($i=0; $i < $numOfPlacements; $i++) {
// use the modulus operator to come back around
$bannerID = $i % $numOfBanners;
echo $list[$bannerID];
}
More info on the modulus operator can be found here.

Categories