Limiting the Number of Records in SQL in PHP
Using the LIMIT command, we can limit
the number of rows in the result.
Example
Let's select the first two users:
<?php
$query = "SELECT * FROM users LIMIT 2";
?>
Example
Let's select all users with a salary of 500,
and then use LIMIT to take only
the first two of the selected:
<?php
$query = "SELECT * FROM users WHERE salary=500 LIMIT 2";
?>
Example
Using LIMIT, you can select several
rows from the middle of the result. In the example below,
we will select starting from the second row (row numbering
starts from zero), 5 items:
<?php
$query = "SELECT * FROM users LIMIT 1,5";
?>
Example
The LIMIT command can be combined
with ORDER BY. In this case, the sorting command must be written first,
and then the limit.
In the next example, we will first sort the
records by ascending age, and then take the
first 3 items:
<?php
$query = "SELECT * FROM users ORDER BY age LIMIT 3";
?>
Practical Tasks
Get the first 4 users.
Get users starting from the second, 3 items.
Sort users by ascending salary
and get the first 3 workers from the sorting result.
Sort users by descending salary
and get the first 3 users from the sorting result.