How to limit mysql rows to select newest 50 rows - php

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

Related

php fetch database, displaying them customized.

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 ..

Server-side Pagination: total row count for expensive query?

I have a simple query using server-side pagination. The issue is the WHERE Clause makes a call to an expensive function and the functions argument is the user input, eg. what the user is searching for.
SELECT
*
FROM
( SELECT /*+ FIRST_ROWS(numberOfRows) */
query.*,
ROWNUM rn FROM
(SELECT
myColumns
FROM
myTable
WHERE expensiveFunction(:userInput)=1
ORDER BY id ASC
) query
)
WHERE rn >= :startIndex
AND ROWNUM <= :numberOfRows
This works and is quick assuming numberOfRows is small. However I would also like to have the total row count of the query. Depending on the user input and database size the query can take up to minutes. My current approach is to cache this value but that still means the user needs to wait minutes to see first result.
The results should be displayed in the Jquery datatables plugin which greatly helps with things like serer-side paging. It however requires the server to return a value for the total records to correctly display paging controls.
What would be the best approach? (Note: PHP)
I thought if returning first page immediately with a fake (better would be estimated) row count. After the page is loaded do an ajax call to a method that determines total row count of the query (what happens if the user pages during that time?) and then update the faked/estimated total row count.
However I have no clue how to do an estimate. I tried count(*) * 1000 with SAMPLE (0.1) but for whatever reason that actually takes longer than the full count query. Also just returning a fake/random value seems a bit hacky too. It would need to be bigger than 1 page size so that the "Next" button is enabled.
Other ideas?
One way to do it is as I said in the comments, to use a 'countless' approach. Modify the client side script in such a way that the Next button is always enabled and fetch the rows until there are none, then disable the Next button. You can always add a notification message to say that there are no more rows so it will be more user friendly.
Considering that you are expecting a significant amount of records, I doubt that the user will paginate through all the results.
Another way is to schedule a cron job that will do the counting of the records in the background and store that result in a table called totals. The running intervals of the job should be set up based on the frequency of the inserts / deletetions.
Then in the frontend, just use the count previously stored in totals. It should make a decent aproximation of the amount.
Depends on your DB engine.
In mysql, solution looks like this :
mysql> SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name
-> WHERE id > 100 LIMIT 10;
mysql> SELECT FOUND_ROWS();
Basically, you add another attribute on your select (SQL_CALC_FOUND_ROWS) which tells mysql to count the rows as if limit clause was not present, while executing the query, while FOUND_ROWS actually retrieves that number.
For oracle, see this article :
How can I perform this query in oracle
Other DBMS might have something similar, but I don't know.

How to write pager effect in PHP

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.

Mysql query forward and back

I'm wondering what is command for database query that is querying data forward or back between rows? Just like forward and back button. Can someone give me an example? Thanks.
For examp:
$sql_xxxx = mysql_query("SELECT * FROM xxxx WHERE id='$xxx'") or die (mysql_error());
$row_xxxx = mysql_fetch_array($sql_xxxx);
Now I need the two same query but for one forward and in the other backward the data.
Since you tagged PHP and MySQL I think I can guess what you are trying to do;
Usually you can control this with the ID of a record in MySQL, for example:
SELECT * FROM MYTABLE WHERE ID = 1;
In PHP, you can construct dynamic queries to get different results while just changing the value of a variable.
Lets say we now want to take the same query and make it dynamic:
$id = 1;
$query = "SELECT * FROM MYTABLE WHERE ID = $id ";
as long as you execute this query, it will give you the row with ID = 1 , cause now it is taking the value from the $id variable.
If you want the next row, then you execute the same query but now $id must have the next value.
$id = 2;
Having a "NEXT" and "BACK" button can be matter of just adding or substracting 1 to the $id variable.
Still, this is only an example. In most of the cases you should not play with id's like that cause you should not assume that all id's exist, remember that "DELETE" exist;
So you can try to execute better a little query to find the next value like this:
to go foward:
$query= "SELECT MIN(ID) FROM MYTABLE WHERE ID > $id"
// This will get you for sure the closest id next to the current one
and to go back:
$query= "SELECT MAX(ID) FROM MYTABLE WHERE ID < $id"
I hope this helps,
Regards
You can specify a LIMIT in your query, which results in a specific number of rows. For instance, when you end your query with LIMIT 100, 10, you will get 10 results starting at row 100.
This way, you can build prev/next buttons, that when clicked, retrieve the previous or next page of results.
But in most other cases, you will just query everything you need and run through the result set. You do this by querying the result, and fetching each next row of the result.
If you use the LIMIT keyword, the database will happily return a "page" of data, for example;
SELECT * FROM posts ORDER BY post_time LIMIT 40,20; -- will return rows 41-60.
You can make use of that from PHP by just setting the first LIMIT number to page number * page size and the second number to page size (with page number being 0 for the first page). In the example, the page size would be 20 and the page number would be 2 (the third page) and the results will be all the posts from the third page.
There's nothing more to it from the database side, you'll just have to make good use of it from PHP.
if i'm understanding the question correctly, it sounds like you're trying to implement pagination in your queries and you would utilize the 'limit' clause, like so:
SELECT * FROM `your_table` LIMIT 5, 5
This will show records 6, 7, 8, 9, and 10
here's more documentation

How to do pagination in simpledb

I have tried offset in simpledb but it's not working as it was working in MySQL. I want to do paging for my database API in PHP so that I send the pagenumber and pagelength to the query and it will return the data of that page only.
How can I do this in simpledb?
select * from second
where time_stamp is not null and gibid = '54' and gibview = 'O'
order by time_stamp asc limit $pagelength
Offset is not working so I can't add offset in query. I have Googled and find there is next token is returned but I am not getting nexttoken. How to check for nexttoken?
Per the Simpledb team (this question was asked in their forums) using the next token is the way to do it.
If you want to grab, say the 2500-2600th item from a list and not iterate over the first 2500, the simpledb team recommends doing a count(*) up to 2500, cause it is fast, then grabbing the next token from that result and then issuing your real query to pull the names and attributes.
Clever hack to the fact that limit doesn't take a starting index I thought, but should save you some performance. Just wanted to share that.
Done By Using NextToken in simple db
$files = $this->db->select($domain, $query, $offset)
Here $offset is nexttoken string which will pass in query. and will return next page.
$pagelenght should be :
$pagenum = 4; //current page
$numitems = 20; //items per page
$row_from = $pagenum * $numitems - $numitems;
$pagelenght = $row_from.','.$numitems;
in the end pagelenght should look like this
$pagelenght = '0,20'; //first page
$pagelenght = '20,20'; //second page
$pagelenght = '40,20'; //third page
$pagelenght = 60,20'; //forth page
something like this, first number is from which row, and second is number how many items in one page.
I confirm that LIMIT in SimpleDB only takes one argument.
To be sure, I tried the following query (the domain Person exists):
"SELECT * FROM Person LIMIT 20, 20" and I had the following response:
Client error : The specified query expression syntax is not valid.
Even if limit is not specified, SimpleDB applies a default limit 100, the maximum limit is 2500 rows. I want to stress out that LIMIT works differently from other databases. LIMIT 100 means that you'll get 100 results per time, and you'll get another batch of 100 results with the next token (provided that there is enough data of course).
The way to do the pagination is use tokens. Already obtained token can be stored in the session, so it will be possible to go back to previous pages.
Amazon SimpleDB doesn't support OFFSET clauses in its query syntax like some other storage systems do. For example, if you're using pages of 10 items each in your app, here is how you might get the 4th page in MySQL:
SELECT * FROM items LIMIT 30, 10
The LIMIT 30, 10 clause means skip the first 30 records and return the 10 after them. SimpleDB doesn't have this out of the box, but you can simulate it by doing 2 queries. The first is this one, which counts up the first 30 items:
SELECT COUNT(*) FROM items LIMIT 30
Your SimpleDB client library will execute this, returning the count and also a NextToken element in the response. Now you can make this second query to get the 4th page of items:
SELECT * FROM items LIMIT 10
Make sure that you pass along the NextToken into your client library so that the query is resumed from the associated cursor. Any query issued with that next token only operates on the records that weren't counted by the first query, giving you an implicit offset.
From article https://coderwall.com/p/yr-mdg/numbered-paging-in-simpledb-queries

Categories