Mysqli php ajax Pagination - php

can someone please explain to me how to approach this issue?
I have a table with 4000 records, a select option and a search field to filter out the table
however I'm trying to figure out the best way to set up pagination.
1st Approach:
Should I make one query against the database and populate the table with all records and then set up the pagination with javascript so I can be able to search for records that are not only shown on the current page?
2nd Approach
Set up the pagination with PHP, make a query via ajax for each page? however I'm afraid that this approach would not allow me to filter out the table if I need to search for a record that is not on the current page.

1st approach: definitely not, loading large number of results for nothing is not recommended.
2nd approach makes more sense. You can use the LIMIT statement inside your SELECT statement to decide which records you want. Ex. if you paginate on 10 elements perpage, you could do
SELECT * FROM Table LIMIT 10
then
SELECT * FROM Table LIMIT 10,10
and so on. Indexes start at 0.
Note that you don't even need Ajax to do that, your next button can specify the offset for the next load of the page. It's a choice based on your knowledge, the size of the rest of the page (minimize load time), ...

Related

Solution Mysql Random query migrate when goto another page

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.

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.

PHP/MySQL Show first X results, hide the rest

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.

What would i need to do display urls in order the way they are displayed on SO?

I'm really unsure of how ordered results are displayed on a page like stack overflow questions. I know how to get the data from the DB but do i use a for each loop to display the data. And how can i paginate?
I know all about display logic on the databse end. What i mean is that i have the data ready but i do not know how to put in on the page to be displayed correctly.
Thanx
You need to use
ORDER BY for sorting your results
LIMIT for pagination
GET parameters in your requests should determine the values applied to those statements.
To order results, you should add a "ORDER BY" clause to your SQL statement. Specifically, for StackOverflow default view, it shows questions by date (with the most recent most). This implies that each question has the datetime which it is created tagged to it.
As for pagination, here's a general outline of the code
Find total number of records
Decide how many records per page
Find out how many pages (record per page/page)
Check what's the current page number
Calculate the parameters to add to the LIMIT clause in the SQL statement. The start record should be current page * records per page.

Categories