SQL Limit in PHP


Introduction

PHP has an operator named LIMIT. Using the LIMIT operator you can fetch a minimum and maximum row from a database. In this article you will see, how to execute the LIMIT operator of MySQL in PHP. 

Suppose that there are ten rows in a table of any database in MySQL. You want to fetch only five rows from your database; then you will use the LIMIT operator.

 image1.jpg

Suppose there is the above table in your database. You want to fetch only five rows from this table. For this purpose you will use the LIMIT operator. An example of the LIMIT operator is as follows:

Example 1. If you want to see only five rows from a table in MySQL then you will use the following query:

           select * from emp limit 5

Output

image3.jpg

Example 2. If you want to see only five rows from a table in PHP form, then you will use following code.

In this example, we have created a limit.php page, in which we execute a query with the LIMIT operator. In the LIMIT operator we put minimum and maximum limit of the table data. For example, the LIMIT 0,5 retrieves the row starting from row number 0 (the first one) to a maximum of 5 rows.

Code

<html>
<
title>Limit in PHP</title>
<
body bgcolor="pink">
< h3><u>SQL Limit in PHP<u></h3>
<
center>
<?php
  $con = mysql_connect("localhost","root","");
 
if (!$con) {
 
die( 'Could not connect: ' . mysql_error());
  }
 
  mysql_select_db ("sunderdeep", $con);  // sunderdeep is a database name
  $result = mysql_query ("select * from emp limit 0,5");  // emp is the table name in database
   echo " <table  border='2' bgcolor ='skyblue'>
  <tr>
  <th align='center'>emp_id</th>
  <th align='center'>emp_Name</th>
  </tr>"
;
 
while ($row = mysql_fetch_array ($result)) {
 
echo "<tr>";
 
echo "<td align='center'>" . $row ['emp_id'] . "</td>";
 
echo "<td align='center'>" . $row ['emp_name'] . "</td>";
 
echo "</tr>";
  }
echo "</table>";

   mysql_close ($con);
?>
</center>
</
body>
</html>

The above file is saved with the name limit.php.

Output

When you browse your limit.php file then you will get the following output:

image2.jpg

Conclusion

So in this article you saw, how to execute the LIMIT operator of MySQL in PHP. Using this article one can easily understand how to execute the LIMIT operator of MySQL in PHP. 

 Some Helpful Resources