Counting all results of MySQL query for paging - php

I am building a search page, each page featuring 10 results. For that purpose, I would like to display pages numbers at the bottom (like in Google for example) so a user can jump to a specific page result. In order to do that I need to know the overall count of the query (e.g., if I show 10 results per page and the specific query returns 73 rows in my Table, i would need to display links to 8 pages).
The only way I can think of is using the following (obviously inefficient) query:
// Query for the current page
$res = mysql_query("select * from TABLE WHERE COL='Sample' LIMIT $offset,10");
// Geeting the total count do I can build links to other pages
$res2 = mysql_query("select COUNT(*) fromTABLE WHERE COL='Sample'");
Is that the only way to do it?
Thanks,
Danny

you can use
SQL_CALC_FOUND_ROWS
mysql> SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name
-> WHERE id > 100 LIMIT 10;
mysql> SELECT FOUND_ROWS();
SQL_CALC_FOUND_ROWS tells MySQL to
calculate how many rows there would be
in the result set, disregarding any
LIMIT clause. The number of rows can
then be retrieved with SELECT
FOUND_ROWS()

Related

How to combine SQL query for getting total records and getting records for pagination limit

I have to apply two queries for pagination.
1) Select all records.
2) Select records with limit.
As per example
$total_records = 'select * from table_name';
$for_pagination = 'select * from table_name limit 10, 2';
Is there any solution or way to get limit records and all records together with single query?
Can you use Union All? if they have the same number of columns and data type.
https://www.techonthenet.com/mysql/union_all.php
Otherwise, could you please provide further information (such as sample data) as we don't have much idea on your request based on information from your question.

PHP Pagination MSSQL alternative to LIMIT?

To paginate a select query normally I would do this:
SELECT * FROM items WHERE condition = 1 LIMIT $start, $items
However, in MSSQL there is no LIMIT condition, so I tried with:
SELECT * FROM items WHERE condition = 1 OFFSET $start ROWS FETCH NEXT $items ROWS ONLY
And I get the error:
42000 - [SQL Server]Invalid usage of the option NEXT in the FETCH statement.
So what exactly should I do to paginate results?
This may help you.
The OFFSET-FETCH clause provides you with an option to fetch only a window or page of results from the result set. OFFSET-FETCH can be used only with the ORDER BY clause.
SELECT P_Name FROM ITEMS ORDER BY P_Name OFFSET 10 ROWS;
SRC: https://technet.microsoft.com/en-us/library/gg699618.aspx
The MS SQL equivalent to MySQL's LIMIT clause is TOP.
SELECT TOP 10 * FROM items WHERE condition = 1;
Will return the top ten rows, the same way it is done with LIMIT here:
SELECT * FROM items WHERE condition = 1 stuff LIMIT 10;
For more details (since I don't know all the context of your code) you can take a look here.

Counting all rows with a limit

I need to filter (using where clauses) the rows in my table, count the total number of rows from this filter and then limit number of rows for pagination.
What is quickest/more efficient?
Count the rows with sql query. Select the rows with a limit with sql query.
Select all rows with sql query. Count the array with PHP. Split the array with PHP.
Or is there another way to count all rows and get a limited set of the results out?
You should use SQL_CALC_FOUND_ROWS and the FOUND_ROWS() function to return the total number of rows even when a LIMIT is applied to the returned results. After you run your query the results will be returned, and then you can run SELECT FOUND_ROWS() to return the total number of rows without having to run the query again.
SELECT SQL_CALC_FOUND_ROWS * FROM my_table WHERE column = 'something' LIMIT 10;
SELECT FOUND_ROWS() AS total_results;
Use two queries, one to retrieve total number of rows, another to get the rows. The first argument in LIMIT clause specifies the offset of the first row ( current_page * post_per_page ), and the second specifies the maximum number of rows to return ( post_per_page ).
SELECT COUNT(*) AS num_rows FROM table;
SELECT * FROM table LIMIT start, length;
The MySQL LIMIT should do the trick for you. This is a more efficient approach, as it helps in fetching only the relevant records to be displayed and nothing else.
Note that the startingIndex, numberOfRecordsPerPage variables should be set before executing the query.
SELECT * FROM MY_TABLE where
(...) //ALL CONDITIONS go here
LIMIT startingIndex, numberOfRecordsPerPage;
From the MySQL Reference
With two arguments, the first argument specifies the offset of the
first row to return, and the second specifies the maximum number of
rows to return. The offset of the initial row is 0 (not 1):
SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15
In order to identify whether or not to expect any records in return, one must first run the query (with COUNT and without any LIMIT condition):
`SELECT COUNT(*) FROM MY_TABLE where (...) //ALL CONDITIONS go here`
and store it separately. This shall be the total records applicable to the WHERE clauses given.
If the sum startingIndex+numberOfRecordsPerPage is >= TOTAL_COUNT then that paginated set shall be the last of the whole list and the user should not be allowed to click the NEXT button.
PS: Also, as pointed out in the comments, you might want to look at a framework alternative, like Criteria API for Java, to the heavy weightlifting, particularly if your WHERE conditions are also generated dynamically.

display most recent query result

i have a query that i use to count the number of rows as a result, but i would also like to print out the most recent row of that query, in a view, but only that recent query instead of the whole array
basically i use this query, then run a count to display the amount of rows which is a count i display, but i also want to display the latest date, location, and code, it can only get it to display all
2 options...
Select * from table order by primary_key desc;
count the results and print the first (most recent) row
or run two separate queries...
select count(primary_key) as num_rows from table;
select * from table order by primary_key desc limit 1;

Possible to limit results returned, yet leave 'pagination' to table?

I am building a php site using jquery and the DataTables plugin. My page is laid out just as it needs to be with pagination working but in dealing with large datasets, I have noticed the server is pulling ALL returned rows as opposed to the 10 row (can be more) limit stated within each 'page'.
Is it possible to limit the results of a query and yet keep say the ID numbers of those results in memory so when page 2 is hit (or the result number is changed) only new data is sought after?
Does it even make sense to do it this way?
I just dont want to query a DB with 2000 rows returned then have a 'front-end-plugin' make it look like the other results are hidden when they are truthfully on the page from the start.
The LIMIT clause in SQL has two parts -- the limit and the offset.
To get the first 10 rows:
SELECT ... LIMIT 0,10
To get the next 10 rows:
SELECT ... LIMIT 10,10
To get the next 10 rows:
SELECT ... LIMIT 20,10
As long as you ORDER the result set the same each time, you absolutely don't have to (and don't want to) first ask the database to send you all 2000 rows.
To display paging in conjunction with this, you still need to know how many total rows match your query. There are two ways to handle that --
1) Ask for a row count with a separate query
SELECT COUNT(*) FROM table WHERE ...
2) Use the SQL_CALC_FOUND_ROWS hint in your query, which will tell MySQL to calculate how many rows match the query before returning only the 10 you asked for. You then issue a SELECT FOUND_ROWS() query to get that result.
SELECT SQL_CALC_FOUND_ROWS column1, column2 ... LIMIT 0,10
2 is preferable since it does not add an extra query to each page load.

Categories