Methods to achieve first, previous, next and last navigation - php

I'm new to programming and have a question about navigation.
What are the various methods that can achieve a "First", "Previous", "Next" and "Last" navigation, as seen in article or comic based sites? (Admittedly the "First" link isn't confusing as it can stay static, but what about the others?)
For example, on the 50th page, the links would appropriately lead to the 49th and 51st (if it exists, if not it would not function but would automatically become active when such a page exists.
In most examples of this I see urls ending with something like ".php?id=50" but am not certain how it's achieved, with a database?
Any help will be very much appreciated, thanks.

The bit at the end of the URL is called a GET variable. When a user goes to a page with one at the end, for example:
example.org/comics/myawesomecomic.php?page=50
The server goes to that page and (usually) a server-side script will do some work before outputting the page to the user. With PHP, the GET variable is a Global Variable (along with others, the big ones being POST and COOKIE), that the php script can retrieve by getting the value passed from the server to script, in this case in $_GET['page'].
So assuming you have a script that handles all requests for the comic storyline "My Awesome Comic" and it's broken up into 60 pages, all a user has to do to get to any page is change the GET variable to the page number. Your script might do something really simple, like get the contents of a directory called myawesomecomic/ and grab a file called 50.html and then output it to the user. But chances are, you want something a tad more sophisticated since you went to this trouble, so instead it goes and grabs page 50 from a database and updates all of the navigation and maybe even throws a stylish 50 - 60 in the top corner.
Now, here's the easy part, aka the answer to your question. Now that you know how GET variables work and what the server-script does with them, all you have to do to make navigation like you describe is:
$current_page = $_GET['page'];
$next_page = $current_page + 1;
$prev_page = $current_page - 1;
$first_page = 1;
$last_page =
And that last part is going to be up to you to know already. Either you can always have the same number of pages, or you can query the DB at the same time you pull up the current page, etc. Let's say you did query the DB for the total page count while you were getting the current page. And it returned 60 (and we'll assume, just to avoid headaches that 60 is the page count starting from 1, not 0), so back to the navigation...
$last_page = 60;
Now you have your first, last, prev, and next. Assuming you know your way around HTML, all that's left (besides making this look pretty) is:
echo "
<a href='myawesomecomic.php?page=$first_page'>First Page</a>
<a href='myawesomecomic.php?page=$prev_page'>Previous Page</a>
<a href='myawesomecomic.php?page=$next_page'>Next Page</a>
<a href='myawesomecomic.php?page=$last_page'>Last Page</a>
";
And there's your navigation. Obviously you'll want to arrange them to fit your site, not have them run together like that, use cool arrows, etc. But the links will work even if you don't do anything fancy.
BUT!
I just gave you the really nice, "my first time having fun with PHP" version. Things I left out (that you should ask more about or do some serious research on):
Since GET Variables are including on the URL, they aren't hard to figure out. I could easily change ?page=50 to ?page=1=1 and, depending on how you are getting the content, I may have just asked for all contents of your database. Never grab user-input (even the URL) straight into your variables. If you know it's page number, then you know it's a number. Check the input to make sure it's a number before running it through your script and your database.
You need to have a system for if the user puts in a number and it's out of range. Something simple like "Sorry, page not found" or even "Page not found, starting at the beginning" and sending them back to page 1, whatever. If you just output nothing, it looks bad and you reveal parts of your script's logic that could be manipulated.
When you get comfortable with GET variables, I suggest ditching them for mod_rewrite (assuming you are on an apache server). Don't jump in now, but when you get the hang of it, you can start making URLs like: example.org/comics/myawesomecomic/page50 or example.org/comics/myawesomecomic/page/50 or what have you. What really happens is all pages in that directory get redirected to the same script which then checks the URL's ending to figure out what to pull from the DB. But to the end-user, it looks like there's just a webpage. This looks cleaner (I think) and does even more to cover your script's logic. But I'm saying to wait on it because it also opens you up for other risks that can be harder to anticipate until you're used to sanitizing your user-input and handling standard page errors like "page not found."
Anyways, figuring out stuff like adding a week to a current date and adding a page number to the current page is totally how I got into PHP and web app development, so I hope this was helpful and straightforward.

This kind of navigation is called pagination. There are three variables that affect pagination on a given page:
The total number of items
The number of items per page
Current page
You usually can get the total number of items from a database easily, using a query like this:
$query = "SELECT COUNT(*) FROM tbl";
$count = mysql_result($query, 0);
And as you know the number of items per page and the current page, you can figure out how many pages are in total:
$perpage = 10; // This you can define yourself
$pages_count = ceil($count / $perpage);
After that, it's easy to do some simple if clauses to see what kind of navigation should be displayed:
// Get the current page or set default if not given
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$pages_count = ceil($count / $perpage);
$is_first = $page == 1;
$is_last = $page == $pages_count;
// Prev cannot be less than one
$prev = max(1, $page - 1);
// Next cannot be larger than $pages_count
$next = min($pages_count , $page + 1);
// If we are on page 2 or higher
if(!$is_first) {
echo 'First';
echo 'Previous';
}
echo '<span>Page '.$page.' / '.$pages_count.'</span>';
// If we are not at the last page
if(!$is_last) {
echo 'Next';
echo 'Last';
}
To select the correct results from a database for the given page, you can use a query like this:
$query = "SELECT * FROM tbl LIMIT ".(int)($page - 1)." ".(int)$perpage;
That's really all there's into it. Hope this helps.

Perhaps this tutorial or this one will help you.
Edit: meh, the first one was a highly annoying site. Found another. :)

I am assuming you are not talking about pagination (i.e. splitting a big list of records into multiple pages) but about having a detail view of a record, and preoviding "next" / "previous" links to the next and previous record.
If you have no fixed way of finding out the previous and last neighbours (so you can't just say "current ID -1" and "+1") you will have to do a database query ordered by your criteria, and find out the previous and next members.
Maybe it's to deeply into the issue, and not what you need to start out, but I asked a question recently that concerns optimization issues and differnt approaches to do this "neghbor lookup" in a fast and efficient way. Caching the results of a “next” / “previous element” query

Theres quite a few methods to go about doing this, ranging from complex to simple.
(Seach for php pagination on google).
The ?id=50 in some urls is to determine the item to start at.
For example in sql, you determine a range of items to select using SELECT * FROM tbl LIMIT 0,10 , This will select records 0-10. then SELECT * FROM tbl LIMIT 11,10 would select 11 to 20.

Related

Separate data from database into pages

This is my code:
$query="SELECT * from project where batch='$bach'" or die(mysql_error());
$var=mysql_query($query) or die(mysql_error());
if(mysql_num_rows($var)==0)
{
echo "No such batch exist.<br />";
}
while($arr=mysql_fetch_row($var))
{
echo $arr['batch'];
}
I am just displaying one field right now thats batch but there are 8 columns and many rows would be filled when user inputs the data.. This code will display the content on the same page making the page quite long. How can i split the data into various pages with html and php? A better example can be google which splits the search results into pages and with page numbers at the bottom.
Please chk this tutorial for php mysql pagination http://www.tutorialspoint.com/php/mysql_paging_php.htm .
I would personally recommend two things for you.
Create a router that will take a variable from url , like yoursite/list/11 , it will create a list , with eleventh set of your database values. Use mod_rewrite so you can have "pretty urls"
About PHP routing
You will need to create a function that will count your DB entries , and divide that number into page sets. Say One hundred entries equals ten pages. This will let you create that kind of menu that looks like 1,2,3....,9,10.
Another function which will retrieve the specific set of entries, and then pass it to whatever script runs your "list"
Since your question is not 'help me find error' but rather 'how to achieve this', I'm afraid I cannot offer more than basic logic of things.
Second thing i will recommend is avoiding mysql_ functions , because these are deprecated and will be removed from PHP.

Multiple result sites (pagenumber buttons)

I have a website were the user types in a city (f.e.: Washington), presses search and via ajax json it gets the entries from my database. I never know how many entries it got, so let's say this time I have 40 entries in my database where it says "Washington". Now a function appends all 40 entries on the site.
How do I get it to show only 4 entries and then add number buttons where the user can go to page "X" to see another 4 entries and so on?
second question:
And how do I tell the script to just add a specific amount of number buttons ( In this case just 10, since 10*4=40 already )?
I don't necessarily need a full code example, just a good explanation on how I can do this (without a plugin).
Here a simple drawing to clarify this:
Thank you very much in advance for any answer.
There is an excellent tutorial on tutsplus covering the kind of pagination as seen on your image. You would just need to modify the sql query in the script to match your requirements, point your ajax url to this pagination script, and ensure the results are returned as json. Hope this helps!
To setup the pagination you would need to use mysql LIMIT & OFFSET, also counting the total number of results and returning that in the JSON to set the correct number of pages in the pagination.
You would also need to pass the page number in the ajax call through a GET parameter so you can set the OFFSET correctly and return the correct page.
I tried some jQuery pagination plugins but they were a little buggy. So I chose pure PHP and made a really simple one myself, since the tutorials seemed a bit too overloaded to me.
I just pass pagenr via GET and in my script a set a specific amour of results to be displayed via Limit $start(=0 if pagenr=1), 10
If the pagenr is bigger then "1" it undergoes a for loop which adds up "10" to "$start" every time.
And with these values and COUNT(*) I do the pagination with for and if loops.

Pagination with XML and PHP?

before anyone asks; I've googled my 'question', I've also looks at the 'Questions that may already have your answer' and none of them work.
What I'm wanting to do is 'Pagination'. However, I don't want to use Databases as I've never had to and I'd rather not give up and go to them now as XML does everything I want it for.
The code I have is the following:
$files = glob('include/articles/*.xml');
foreach($files as $file){
$xml = new SimpleXMLElement($file, 0, true);
}
I've tried these ones already: XML pagination with PHP, PHP XML pagination and Pagination Filtered XML file and have achieved nothing. I have also tried a lot of Javascript 'pagination' scripts and still nothing.
So to sum it up: I have four articles (More to be added) and I want to show 2articles per a page. The following information will be 'pulled' from the xml file: ID, TITLE, CONTENT, PICTURE, AUTHOR, DATE by doing $xml->id and so on for the rest of them. Does anyone know of any way of doing this? as I've spent the past four hours (Its 4:04AM GMT) and have found nothing that works yet. (If I find anything that does work I'll make sure to update the question with the working code encase there is anyone else out there that needs help with this too.)
For a start define the order in which you want your articles to appear. I.e. which article goes on page 1, which one on page 2, etc. This is important, because that order will be the base for your pagination algorithm. Please note that glob() is not guaranteed to return results in any specific order, which means the order can change from one invocation of your script to another (notably when you add new articles) -- almost certainly not what you want.
Then the second step is to introduce another variable which is part of your URL that denotes the actual page (number) you're on. The URL query string would be a natural choice for putting this information, so your URL's look like: article.php?page=1. On the PHP side you can use the $_GET superglobal to retrieve the query string parameters.
Thirdly, use the new style URL's whenever you link to your article.php script. Additionally, validate the input --especially when you also want to display the current page based on this parameter (or you will end up with an injection vulnerability). This also means you want to have a default value (in case the value is invalid/wrong/ or not supplied at all for some reason).
Finally, filter your articles based on the two key pieces of information: the order of the articles w.r.t. the page number and the page number: i.e compute the actual articles that should appear on the current page.

How to update prices in jQuery calculator via PHP

I am creating a "budget calculator" to manage money at festivals.
Can anyone tell me how you would include a PHP script within the JQuery?
So far I have the form calculating how much you may spend given your habits in different categories per day, then times it by 3 for the weekend.
I want to be able to update these prices as I go in order to make sure the price is as always as up to date as possible. So I created a mysql database and query that calculates the medium price and then returns it back to the page via a php script.
This is a JSfiddle to give you an idea of what it looks like at the moment - although it's not working on the site but you can see the set up.
JSfiddle
Here is a screen shot of what the form actually looks like. As you can see the price beside the title of each input is displayed via the php include. The button on the right leads to the "update" form that allows you to enter a new price.
This is an example of the query that is used to display calculate the medium:
PHP:
<?php
include 'connect.php';
$query = "SELECT x.price FROM price_pints x, price_pints y GROUP BY x.price HAVING SUM( SIGN( 1 - SIGN( y.price - x.price ) ) ) / COUNT( * ) > .5 LIMIT 1";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo "£".$row['price'];
}
?>
What I'm trying to do is get this same php include to work within the "data-unit-price" tag.. Any ideas?
Thanks.
DISCLAIMER: this is the EASIEST way i come up with, i'm trying to avoid more advanced things like dynamically generated javascript or ajax
When you build the page (PHP, server-side), load the 3 prices in three variables and then have 3 hidden inputs like this
<input type="hidden" id="pint_price" value="<?php echo $pint_price; ?>">
your script should look at the hidden input's values to initialize the calculator.
NOTE: if the prices change while the page has already been loaded, the user does not see the update. you may want to consider putting a disclaimer somewhere.
The BEST solution would be to have an ajax request every time the user inserts a new value (if bandwith is not an issue, either for your server and for the user) or every X minutes.
See jQuery get docs for reference and examples.
On an unrelated note, you really shouldn't be using mysql_* for interact with (MySQL) databases. Make a little effort and learn to use PDO. I really recommend it.

Pagination in PHP

I have a page that serves a list of files for users to download.
There can be hundreds of files there, and I would like to break them down into multiple pages and give users the option either to see them page by page or get them all displayed in one page.
I've never done anything like this and don't know how to do it.
Please help.
Thank you!
Ok, I had this question too once. This is basically the logic behind the pagination, I am not going to write code but if you need it let us know.
Basically, you need two values to create a pagination, a limit and a offset.
The limit is the amount of items your are displaying at the same time.
The offset is from where you started your query.
So, let's say you have 5 items in each page and 25 items total.
In your query, you have to limit 5,0 (the amount of items and the position the query will start).
Now, if you divide 5(limit)/25(total) and you'll get 5 (amount of pages).
Now in page 0 (the start) you can get the offset by multiplying the page number with the limit, so 0 (page) * 5 (limit) gives you 0 (in the first page you start from the offset 0).
Now in the 3rd page, you multiply 3(page) * 5 (limit) it gives you 15, which means in page 3 (or four if you take into account that you actually started at page 0) you will display from offset 16 to 20.
Finally in page 4 (which to your users will be page 5 because they started at page 1, not page 0) you will display from offset 21 to 25 which are all the items in your query.
I hope after reading this you understand the logic behind pagination, if you need help with the code, again, just let us know.
Are your filenames coming from a database? If so, check out OFFSET and LIMIT filters in your queries. If not, try counting up the number of files you have, divide them out into blocks, and then when you go to the next page let it know where to start.
Here's a hint,
print "<a href='page.php?offset=$offest&limit=$limit'> Next </a>"
It is better for you to try and write this on your own, pagination is a basic feature in PHP applications.
For someone that has never done anything like this it doesn't hurt to learn.
In order to do this you are going to need to pass values through the url and have your sql script change based on the limit value passed in the url.
Things to consider:
SQL limit - This is the amount of results you will receive.
Page number - This is the page of results that are returned.
Sort - This is how the results are going to be returned in the pagination.
page links - The list of pages. This is found by taking your result number, dividing by the limit and flooring the number.
The hard part about creating pagination is making it extendible and able to be used with other lists of information such as comments or user lists.
Maybe you try write one? This is very easy thing to write and you will not linked to someone code who can be writed in not good quality or some other else code or framework who can by deprecated in some time.
I know this is not solution for this question but this is a my first idea reading this topic.
Firstly you could try to write your own.
Alternatively you could use Smarty (a very well known PHP presentation framework) along with this pagination plugin.

Categories