How to Limit the Number of Rows Returned From a MySQL Table Using PHP


In this article, we show how you can limit the number of results returned from a MySQL query using PHP.

You can limit the numbers of rows returned to any number that you want.

This has good application when you want to limit the number of results to a certain mount. Say, you want to show the cheapest hotels and you have a list of 50 hotels. You can decide to show any amount, such as the 10 cheapest hotels or the 5 cheapest hotels.

To do this in MySQL, you use the LIMIT keyword and after this keyword you put in the number of rows you want returned based on the query.

So the above is the MySQL code to select all columns of the table named table_name and limit the amount of rows returned to 5 rows.

We'll now show how to tie this in with PHP.

PHP Code

The PHP code to limit the number of rows returned is shown below.

So the following code gets the data required to make a connection to a database and actually selects a database.

We then create a variable named $result that queries the table, table_name, and selects the first 5 rows from the table.

You then can later decide what you want to do with these selected rows.

I created a MySQL table called PopularToys. This is shown below.

MySQL PopularToys table

Applying the PHP code above and displaying the rows in tabular form, the following result is achieved.

Actual PHP Output