saftutorials.com
MYSQL LIMIT

LIMIT clause is used to specify the no of records fetched from the table in MYSQL. LIMIT clause is very useful in pagination functionality.


Syntax of MYSQL SELECT statement with LIMIT

SELECT * FROM table_name LIMIT (positive numeric value like 10)

or

SELECT column1, column2 FROM table_name LIMIT (positive numeric value like 10)


Below is a simple example of fetching first 10 rows from student table of database by using LIMIT clause


<?php
 $database_host = 'localhost:3036';
 $database_user = 'root';
 $database_pass = '';
 $conn = mysql_connect($database_host, $database_user, $database_pass);
 if(! $conn ) {
   die('Could not connect: ' . mysql_error());
 }else{
   echo 'Connected successfully\n';
}
 $selected_or_not = mysql_select_db( 'xyz_school' );
 if(! $selected_or_not ) {
   die('Not Selected xyz_school database');
 }else{
   echo 'Selected xyz_school database';
}
 $sql = 'SELECT * FROM student LIMIT 10';
 $result = mysql_query( $sql, $conn );
 if(! $result ) {
  die('Could not get data: ' . mysql_error());
 }
 mysql_close($conn);
?>
<!DOCTYPE html>
<html>
<body>
    <h2>Student List</h2>
     <table>
        <th>
           <td>S No</td>
           <td>Student Name</td>
           <td>Address</td>
           <td>Enrollment No</td>
           <td>Joining date</td>
        </th>
<?php
$i = 1;
while($row = mysql_fetch_array($result)) {
?>
        <tr>
           <td><?php echo $i++;?> </td>
           <td><?php echo $row['student_name'] ."or". $row[1];?> </td>
           <td><?php echo $row['student_address'] ."or". $row[2];?> </td>
           <td><?php echo $row['student_enrollment_no'] ."or". $row[3];?> </td>
           <td><?php echo $row['join_date'] ."or". $row[4];?> </td>
        </tr>
<?php
}
?>
     </table>
  </body>
</html>
Output: This code gives result from student table with limit 10 data.



Find us on

Facebook Google Plus Twitter Pinterest YouTube

web statistic