Select Limit Records Using Mysqli and PDO

The LIMIT clause returns the number of rows from the table.The LIMIT clause is used in PHP for Pagination with MySQL. When MySQL has very number of rows. Then pagination is divided into separate pages with LIMIT clause. This also decreases the page size and page loading.

Example for LIMIT clause using MySQLi

<?php
$conn = mysqli_connect("localhost", "root", "", "expertstutorials");
if($conn){
echo "Connected successfully.<br />";
}
else{
echo "Connection failed : ".mysqli_connect_error();
}
$select = "SELECT * FROM course LIMIT 2";
$result = mysqli_query($conn, $select);
echo "<table>
<tr>
<th>id</th>
<th>Course Name</th>
<th>Course Year</th>
</tr>";
if(mysqli_num_rows($result) > 0){
while($rows = mysqli_fetch_assoc($result)){
echo "<tr>
<td>".$rows['id']."</td>
<td>".$rows['course_name']."</td>
<td>".$rows['course_year']."</td>
</tr>"; 
}
echo "</table>";
}
else{
echo "rows not found in table";
}
mysqli_close($conn);
?>

Example for LIMIT clause using PDO

<?php
$server = "localhost";
$user = "root";
$password = "";
$db = "expertstutorials";
try{
$conn = new PDO("mysql:host=$server;dbname=$db", $user, $password);
echo "Connected successfully.";
$select = "SELECT * FROM course LIMIT 3";
$result = $conn->query($select);
echo "<table>
<tr>
<th>id</th>
<th>Course Name</th>
<th>Course Year</th>
</tr>";
if($result->rowCount() > 0){
while($rows = $result->fetch()){
echo "<tr>
<td>".$rows['id']."</td>
<td>".$rows['course_name']."</td>
<td>".$rows['course_year']."</td>
</tr>"; 
}
echo "</table>";
}
else{
echo "rows not found in table";
}
} 
catch(PDOException $e){
echo "Table Creation failed : " . $e->getMessage();
}
$conn = null;
?>