Tutorials, PHP & MySQL

Limit MySQL output

This tutorial will show you how to limit how many results you get from a database query. This tutorial assumes you have an understanding of basic PHP syntax.

When your querying your database you may not always want to see all the results instead just see the last 5 results for example.

This is very simple to do using the LIMIT clause in MySQL.

Here's an example:

$query = "SELECT * FROM table_name WHERE rowID ORDER BY rowID DESC LIMIT 5 ";
$result = mysql_query($query) or die('Error : ' . mysql_error());

This will only show the last 5 results in descending order. By default MySQL outputs results in ascending order so by giving the ORDER BY rowID (name of the row) DESC MySQL will output the results in descending order.

Using LIMIT 5 will tell MySQL to only show 5 results. 

David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.