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.
Related
How to limit mysql rows to select newest 50 rows and have a next button such that next 50 rows are selected without knowing the exact number of rows?
I mean there may be an increment in number of rows in table. Well I will explain it clearly: I was developing a web app as my project on document management system using php mysql html. Everything is done set but while retrieving the documents I mean there may be thousands of documents.
All the documents whatever in my info table are retrieving at a time in home page which was not looking good. So I would like to add pages on such that only newest 50 documents are placed in first page next 50 are in second and so on.
But how come I know the exact number of rows every time and I cannot change the code every time a new document added so... numrows may not be useful I think...
Help me out please...
What you are looking for is called pagination, and the easiest way to implement a simple pagination is using LIMIT x , y in your SQL queries.
You don't really need the total ammount of rows you have, you just need two numbers:
The ammount of elemments you have already queried, so you know where you have to continue the next query.
The ammount of elements you want to list each query (for example 50, as you suggested).
Let's say you want to query the first 50 elements, you should insert at the end of your query LIMIT 0,50, after that you'll need to store somewhere the fact that you have already queried 50 elements, so the next time you change the limit to LIMIT 50,50 (starting from element number 50 and query the 50 following elements).
The order depends on the fields you are making when the entries are inserted. Normally you can update your table and add the field created TIMESTAMP DEFAULT CURRENT_TIMESTAMP and then just use ORDER BY created, because from now on your entries will store the exact time they were created in order to look for the most recent ones (If you have an AUTO_INCREMENT id you can look for the greater values aswell).
This could be an example of this system using php and MySQL:
$page = 1;
if(!empty($_GET['page'])) {
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
if(false === $page) {
$page = 1;
}
}
// set the number of items to display per page
$items_per_page = 50;
// build query
$offset = ($page - 1) * $items_per_page;
$sql = "SELECT * FROM your_table LIMIT " . $offset . "," . $items_per_page;
I found this post really useful when I first try to make this pagination system, so I recommend you to check it out (is the source of the example aswell).
Hope this helped you and sorry I coudn't provide you a better example since I don't have your code.
Search for pagination using php & mysql. That may become handy with your problem.
To limit a mysql query to fetch 50 rows use LIMIT keyword. You may need to find & store the last row id(50th row) so that you can continue with 51th to 100th rows in the next page.
Post what you have done with your code. Please refer to whathaveyoutried[dot]com
check this example from another post https://stackoverflow.com/a/2616715/6257039, you could make and orber by id, or creation_date desc in your query
During fetching data from database with $result = mysqli_query($con,"select * from MY_table, it display 100 columns at a time. my main aim is to display 10 columns at a time, with the help of next and previous buttons user gonna read remaining. is it possible to do with Javascript , or AJAX, or PHP alone.
The word you're looking for is 'pagination'. You can divide your query results into pages. PHP can fetch a part of the query results, and you can click on a button or link to fetch the next page. That next page can be loaded by an entire page refresh, or by Ajax. In either case, PHP fetches the next results and returns them.
9lessons.info has a tutorial on this exact same topic. Well, more a bunch of snippets than a tutorial, but still..
If you're just starting: forget about Ajax at first. Start with reading about the LIMIT clause in MySQL. It allows you to query a subresult of the query, by limiting the returned rows to a specific range.
You can pass a page (or a range) in the url, so when you click 'Next page', you can just call PHP again with ?page=2 or something in the url. Based on that number, you can query a different range of rows.
The last step is to update only a part of the page using Ajax instead of doing a full page refresh.
You can use limit to your sql query to do this
$start = 0;
$result = mysqli_query($con,"select * from MY_table limit ".$start.", 10");
initially $start will be 0 the change the $start variable as per your prev next ..
I am trying to develop an application where a guest user can see search results only 10 times after which he should be directed to payment page. I can use sessions on the search results page, but how can i put a counter on that. Can any please help me on that.
Every time a search request is created you just do
$_SESSION['counter']++
Altough he can just get rid of the limit by deleting cookies. An other approach would be, to store the number of search requests in a database table including the IP address, but this can also be bypassed, while it takes more work to do so.
If you should put search limit on current running session than you can use $_SESSION['count']++.
And if you should put search limit per day than you can use 'UPDATE users SET search_count = search_count+1'
It depends whether you would allow him to search again when he comes to your website or just those 10 times even after he visits after a year.
For temporary bases, you can use cookies (see setcookie function) but if you want to restrict him once and for all, you will have to ssave that information in database.
You would code something like:
<?php
session_start();
$_SESSION['counter'] += 1;
// more logic/code
Now you will have to save the value of $_SESSION['counter'].
If your users can search only while logged in, then I see no problem - you definitely have db table with users, so just add another column to it, say 'search_count' and increase it by one each time user attemps a search.
For example:
UPDATE `users` SET search_count = search_count+1
You can also use a counter in the table user of your db and call a function everytime the user looks for the result, that increments the value by one, so a simple UPDATE.
I think maintaining database will be much better then maintaining SESSION because may be due to some reason session removed or erased.
add a field within users table name for example visit with default value 0 and update this field on every visit of search result page..
"update usertablename set visitfield = visitfield + 1 where user_id = ".$current_user_id
thanks
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 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