How To Use SQL Limit To Limit Results In PHP/MySQLi | CampCodes

How to use SQL Limit to Limit Results in PHP/MySQLi

June 15, 2020
mysql limit

The use of limit limits the number of results of your MySQL Query and is usually at the last part of your SQL. This is most applicable if, for example, you want to get the top-selling product, you need to order the result then limit it by 1. This tutorial will teach you how to use this limit.

Note: Bootstrap CSS and script used in this tutorial are hosted; therefore, you need an internet connection for them to work.

Creating a Database

The first step is to create our database.

1. Open phpMyAdmin.

2. Click databases, create a database and name it as testing.

3. After creating a database, click the SQL and paste the below codes. See image below for detailed instruction.

CREATE TABLE `tutorial` (
  `tutorialid` INT(11) NOT NULL AUTO_INCREMENT,
  `title` VARCHAR(150) NOT NULL,
  `link` VARCHAR(150) NOT NULL,
PRIMARY KEY(`tutorialid`)
INSERT INTO `tutorial` (`tutorialid`, `title`, `link`) VALUES

create database in mysql

Creating a Connection

Next, we create our connection to our database. This will serve as the bridge between our forms and database. We name this as conn.php.

$conn = mysqli_connect("localhost","root","","testing");
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());


And this contains our sample table and a limit form so you can practice limiting our sample table.

<!DOCTYPE html>
    <title>How to use SQL Limit to Limit Results in PHP/MySQLi</title>
    <script src=""></script>
    <link rel="stylesheet" href="">  
<div class="container">
    <div class="row" style="margin-top:20px;">
        <center><span style="font-size:25px; color:blue"><strong>How to use SQL Limit to Limit Results in PHP/MySQLi</strong></span></center>
        <form method="POST" class="form-inline" style="margin-top:10px;">
            <input type="text" class="form-control" name="limit">
            <input type="submit" name="limitme" value="Limit Query" class="btn btn-primary">
            <input type="submit" name="all" value="Show All" class="btn btn-success">
    <div class="row"style="margin-top:20px;">
        <h4><a href="" style="text-decoration:none;">My Tutorials</a></h4>
        <table class="table table-bordered table-striped">
                        $limit='limit '.$number;
                    $query=mysqli_query($conn,"select * from tutorial order by tutorialid asc $limit");
                            <td><?php echo $row['tutorialid']; ?></td>
                            <td><?php echo $row['title']; ?></td>
                            <td><?php echo $row['link']; ?></td>

That ends this tutorial. If you have any questions or comments, feel free to write it below or message me. Happy Coding!

Download Code

Leave a Reply

Your email address will not be published. Required fields are marked *