brenlei.com

PHP tutorials

Question:

Assume that your table contained hundreds (or thousands) of records. Displaying all of those records from a table on a single webpage usually doesn't work very well. Imagine if your google search displayed all the results from your search on a single page instead of breaking it down over several (if not hundreds of) pages. So how do we limit the number of records returned from a query?

Answer:

MySQL introduces a new keyword to their SQL reference called LIMIT. This allows you to limit the number of records retrieved from a query. Example 1 shows how a query can be limited to retrieve only the first 5 records. Example 2 demonstrates a technique to retrieve 5 records starting with the tenth record.

Fruit Category Table

CREATE TABLE fruit_category (

fruit_category_id smallint(3) NOT NULL auto_increment,

fruit_category_desc varchar(30) NOT NULL default '',

PRIMARY KEY (fruit_category_id),

KEY fruit_category_desc (fruit_category_desc)

) TYPE=MyISAM

COMMENT='Fruit Category Validation Table';

Example 1:
SELECT fruit_category_id,
       fruit_category_desc
FROM   fruit_category
LIMIT  5
Example 2:
SELECT fruit_category_id,
       fruit_category_desc
FROM   fruit_category
LIMIT  10, 5
Additional Notes:

The LIMIT clause is placed at the very end of the SQL script and is not part of the standard SQL specifications. It is an enhancement by MySQL. The LIMIT clause is used for the pagnation of results (i.e. displaying the results of a query over several pages).

Also note that the LIMIT clause occurs AFTER the query has been retrieved. I.e. the entire result set is retrieved from the tables, and then the LIMIT clause is applied.

MySQL

How do you display the contents of a table on the browser?
Learn how to connect to a database, write and execute a query and display the results on the browser

Comments or questions relating to this article have been disabled. They will be back soon.