You have a form which allows the user to browse through the rows in a database table, what do you do if that table has hundreds or even thousands of rows? It would not be a good idea to show all those rows in a single form, instead you should split the database output into more manageable chunks or ‘pages’. There are two things you must do:
Below HTML & PHP Code (index.php) code COPY & PASTE in your text editor
<!DOCTYPE html> <html lang="en"> <head> <title>Pagination in php</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script> </head> <body> <!-- jumbotron --> <div class="jumbotron" style="padding:10px 0;"> <center> <h1>Pagination in PHP</h1> <p>Guide how to create a pagination using PHP and MySQL.</p> </center> </div> <!-- container start --> <div class="container"> <?php $link = mysqli_connect("localhost", "root", "","demo_load_data"); //Check connection if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } //Default Limit = 15 && Page = 1 $limit = 15; $page = 1; //check url "n" to get value n and set var page; if(isset($_GET['n']) && $_GET['n'] != "") { $page = $_GET['n']; } $start = ($page-1) * $limit; $query = "SELECT * FROM `tbl_country_master` LIMIT $start, $limit"; $result = mysqli_query($link,$query); ?> <!-- Start Table --> <table class="table table-striped"> <thead> <tr style="background-color:#F26C37;color:#fff;"><th width="50">#</th><th>Country Name</th></tr> <thead> <tbody> <?php //start loop while($data = mysqli_fetch_array($result)) { ?> <tr> <td><?php echo $data[0]; ?></td> <td><?php echo $data[1]; ?></td> </tr> <?php } //end loop ?> </tbody> </table> <!-- End Table --> <?php //start page get //Get table total recode number & set page number like (1,2,3,4...) $query_row = "SELECT `countryId` FROM `tbl_country_master`"; $result_row = mysqli_query($link, $query_row); $row = mysqli_num_rows($result_row); //The ceil() function is a built-in function in PHP and is used to round a number to the nearest greater integer. $total_pages = ceil($row / $limit); $page_html = "<ul class='pagination'>"; for ($i=1; $i<=$total_pages; $i++) { //current page active start $active = ""; if($page == $i){ $active = 'class="active"'; } //current page active end $page_html .= "<li ".$active."><a href='index.php?n=".$i."'>".$i."</a></li>"; }; $page_html ."</ul>"; echo $page_html; //end page get ?> <!-- container end --> </div> <br><br> </body> </html>
Write a Reply or Comment