I would like to implement paging in PHP. I have some result set from db, let it be an array.
I need a paging that should display 4 records per page and the page numbers should be of the following
"<< 1,2,3.....20 >>"
and when you select page 2, then the format should be of the following
"<< 3,4,5.....20 >>"
can you guys suggest me some paging concepts to implement this?
You can actually use the LIMIT clause in SQL for this.
Here's a decent tutorial to get you started.
Look into PEAR::Pager.
Getting the results is simple enough, using limit as noted above based on the page number. You can use a loop to print out the page numbers.
First, say the page number is sent as page=2 in the query string.
$pagenum=(int)$_GET['page'];
if($pagenum<1){ $pagenum=1; }//perform a sanity check. You might also query to find the max page number and see that it's not higher than that.
You then insert the pagenum into your SQL query as an offset, after multiplying it by the number of results per page minus the results per page.
In almost every case one should use a prepared statement for putting using supplied parameters into SQL of course, however in this case it's not strictly necessary since you are sure the variable is an int due to casting (the (int) part). Just had to emphasize that.
Say you have 4 items per page. You can either use two arguments to LIMIT, or LIMIT and OFFSET separately. If you use just limit, the first number is the offset, second is the number of results.
$offset=$pagenum*4-4;//this means for page 1, start on 0, page 2 starts on 4, etc.
$sql="select * from the_table limit $offset,4";
So, that's how you get the data for a given page number. Then, printing out the page numbers is another story. This example is based on how you want the pages to look as described above.
for($i=pagenum+1;$i<20;$i++){
if($i<$pagenum+4){ ?>
<a href='stuff.php?page=<?php echo $i;?>'><?php echo $i;?></a>
<?php } elseif($i==$pagenum+4) { ?>
... <?php } elseif($i==20){ ?>
<a href='stuff.php?page=20'>20</a>
<?php } ?>
I would recommend using a standardized library. Ignacio reccomended the PEAR::Pager library, but I'm partial to Zend_Paginator in the Zend Framework.
There's a wide variety of adapters included in the library, and on Github by others for using different data sources.
It will be most efficient if you manage this in the Db and in the data access code u can have a function that takes arguments like pageSize,PageNumber,sortOrder.
Your sql could look something like
SELECT * FROM your_table WHERE condition = true ORDER BY some_field LIMIT 100, 10
Related
I have table Post, user can search Post by find by keyword.
So, i using SQL query by like keyword and order by RAND().
When show result, i using GridView and Pagination data. And has problem, when go to another page. Example from page 1 go to page 2 with same keyword. i Will Query again and order by Rand(). So some data in page 1 can appear in page 2.
That data duplicate and not good.
So how can i solve this problem. and data query when goto page other will same with data in the first query.
I using Yii2 in my project.
Ok, I think I get it. Example MySQL query:
SELECT * FROM articles WHERE name LIKE '%tag%' LIMIT 0, 20;
Or you can use MySQL's MATCH() instead of LIKE, it doesn't matter. Then LIMIT 0, 20 is limit, how many results to show for the first page. For the second page it should be LIMIT 1, 20. This one you know I except. Then you get an array of results in the PHP, and want to get random values. PHP has such a function for you and it is called suffle().
So you just use shuffle($results); and then you can print them with foreach or whatever you use to print the data. Note that shuffle() returns boolean, so do not use $results = shuffle($results);. Hope this helps.
I have a query which uses a list of IDs as input (eg. "WHERE XX IN (1,2,3,4) ) and the results are too many to be shown on a single web page. What I plan to do is to limit the results and paginate them. With MySql I added "LIMIT X OFFSET Z".
My problem is now how to pass the information to every single page. I could generate the pagination links with the list of IDs in it (eg. <a href='link.php?i=1,2,3&page=1>1</a> ) or I could store them somewhere. Since I'm using php I was thinking to use SESSION to store them or write them in a cookie for now. Using a DB is overkill? I can make a simple solution with cookies for now and change it later. Having IDs in a cookie isn't a security problem. Even if an user add ids to that list doesn't matter.
There are some answer on SO, but none seems to address all various possibilities.
Yes, using the database is overkill. Depending on you web app both Session and URL are good ways to solve this.
I think that the best solution of these two is to include pagination in the URL. This will help a lot when sharing links to your app. (Immagine sending a co-worker a link to a page in your app... and you are using sessions for pagination)
Have a constant in your code for the "page size" and then multiply it by the page number in the query string to get the offset. Here is a simplified code sample to illustrate:
<?php
$limit = 30; // records per page to have more/less change this
$page = 0; // if not set, $page is 0 (first page)
if (isset($_GET['page']) {
$page = (int)$_GET['page']; // cast to int, to drop funny chars etc.
}
$offset = $page * $limit;
$query = "SELECT * FROM a_table WHERE some_col IN (1,2,3,4)";
// ... then, to add offset data to your query:
$query += " LIMIT $limit OFFSET $offset"; // mind the single space
Your links then should include the page arg: echo "link.php?i=1,2,3&page=".$page+1; incrementing for next page (or have a loop for printing links to the next n pages).
A word of warning:
Do not use cookies to store pagination data. Cookies are data that needs to be sent (sometimes unnecessarily) back-and-forth between request-response lifecycles. And you shouldn't trust cookies in the first place ;)
It looks like your are getting the data for WHERE XX IN (1,2,3,4) from your query string. Be aware that doing this wrong, leaves you wide open to sql injection.
I'm sorry, I am a newbie in PHP. Now I want to learn how to write a pagination effect in PHP. I know there are many tutorials for this on the net. I searched it and have a reference to them. When I try it by myself and don't have a reference to other resources, though, I still don't know how to write a pagination effect with PHP.
Now, I want to know what's the basic and important thing of writing a pagination in PHP. If anyone could give me more details, thank you.
For this example, I will use MySQL because it's a popular database to use with PHP. The general principle applies to other databases, but the precise way you use SQL to achieve the results is different.
The essence of pagination is that you have a number records, say 105, and you only want to display a smaller, more manageable number of records at a time, say 10 of them. In order to do this, you need to know how to find out the total number of records, and you need to know how to select just a subset of the records.
First, find out how many records you have. For this, you use COUNT(*) to count the records in the table. If your table is called Users:
SELECT COUNT(*) FROM Users;
Since we said there are 105 records in the table, this will return the result 105. We said each page has 10 records, so figure out how many pages there are in total: 105 / 10 = 10.5; round up to 11 because the extra records after page 10 need their own page. So, there are 11 pages in total. Your web page will display controls that enable the user to select a page from 1 to 11.
Instead of fetching all the records, you will only fetch one page at a time. In MySQL you generally do this using the LIMIT keyword; this allows you to choose a range of records. LIMIT syntax works like this: LIMIT $SKIP, $COUNT, where $SKIP is the number of records in the result set to skip, and $COUNT is the number to return. (Actually, you will get up to $COUNT records, in case fewer are available.)
The user has requested page 6. This means that I need to skip 5 pages before the results I want to show. With pages of 10 records each, this means I will skip 5 * 10 records, i.e. 50 records. In other words, $SKIP = ($PAGE_NUMBER - 1) * $PAGE_SIZE. You query would look like this:
SELECT User_ID, UserName, City, State from Users LIMIT 50, 10;
This gives you records 51-60 of the table.
See the documentation to learn more about how LIMIT works:
http://dev.mysql.com/doc/refman/5.5/en/select.html
Now you have a single page of records. However, the numbering of the records is dependent on their ordering. The query above will give you unpredictable results because the ordering is undefined. (A database can return records in any order it chooses unless you command it to use a certain ordering.) Thus, to do pagination, you need to define the order of the records. Use ORDER BY to define the ordering:
SELECT User_ID, UserName, City, State from Users ORDER BY UserName LIMIT 50, 10;
This allows you to show different pages of results, and always know that when you show page 6, it contains the records that come after the ones on page 5 and before the ones on page 7.
(If your records don't have any natural ordering, you will have to define an arbitrary one to make this work correctly.)
I have avoided mentioning PHP at all in this answer because I don't think it's necessary to do so to explain pagination. Pagination is entirely a matter of handling data. If you understand this, I think you can go read the tutorials and they will make sense to you and then you can figure how to write the PHP to do this.
Get page number
Know how many items to display on each page.
Using mysql command "LIMIT", get the offset and select how many rows you want.
Want to use a class? http://net.tutsplus.com/tutorials/php/how-to-paginate-data-with-php/
Or just a plain script to modify? http://pastebin.com/J8nTk1q5
If you are new to PHP, then you need to learn more PHP or risk future confusion.
Does anyone know how to bring in all of a mysql tables' results, only show the first X, (say 10), and then hide the rest using jquery? I just need to know how to show only the first X results in one page, then the rest in a seperate page using href.
My aim is to only show the first 10 results, but provide a link at the bottom of the page allowing the user to show all of the results. Was thinking the hyperlink could just re-execute the query but thought it would be easier to show/hide using jquery.Thanks
Rather than using jquery, you can use MySQL to retrieve only the desired results.
SELECT * FROM TableName LIMIT 10
That will retreive the first 10 results. Then, to display the next 10 on the next page,
SELECT * FROM TableName LIMIT 10 OFFSET 10
and the next page
SELECT * FROM TableName LIMIT 10 OFFSET 20
If you are using PHP, you can build your query to show the correct results depending on which page you are on:
// $currentPage is set elsewhere in the script, and is zero-based.
$resultsPerPage = 10;
$currentOffset = $resultsInPage * $currentPage;
$query = "SELECT * FROM TableName LIMIT $resultsInPage OFFSET $currentOffset";
Actually you are searching for Pagination. There are some useful jQuery paginations plugins:
jQuery pagination plugin
DataTables Plugin
Or using PHP:
Pagination in PHP
You need pagination look at the some tutorial to do this. there are lot of code examples on this do googling
here are some links
http://www.codediesel.com/php/simple-pagination-in-php/ -
http://php.about.com/od/phpwithmysql/ss/php_pagination.htm
It might be "easier", but it's a lot less resource efficient to load all the data (and then optionally show it) in the manner you're describing.
I'd really recommend using multiple queries (perhaps via Ajax/lazy loading) rather than using the approach you're discussing.
I'd do this with a LIMIT statement in the Select-statement of your SQL query. In most cases there's no need to send all the data to the client and then let javascript hide the data you don't wanna show.
I have an sql query here and it returns a number of results. I'd like to show these results in groups.
What I mean is,
show the first 20 results in some part of the page,
show the next 20 results in another part of the page
etc...
How can I do that?
*I'm using PHP to display results.
What you want is called pagination and the specific implementation depends on the database. For example, in MySQL you can use LIMIT a,b, and most other databases you can use either TOP(n) or ROW_NUMBER.
do your SELECT command with LIMIT statement.
on first query you can get first 20 results, then next 20, etc.
Ok I found a solution in a forum. It's here in case somebody else needs it
http://www.phpbuilder.com/board/showthread.php?t=10311631