PHP implements paging

【Foreword】

   This article summarizes the principles and methods of paging in PHP. The specific analysis has been annotated in the code, and you can look at the code directly.

   Relevant knowledge points, I made a summary in the previous article

   Note the filename

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>  
<?php
	//connect to the user database
    include 'config.php';
    $connect = mysqli_connect(DB_HOST,DB_USER,DB_PWD,DB_NAME);
    if(!$connect){
        die("could not connect:".mysqli_error());
    }else{
        echo "Connection succeeded<br>";
         //search result
        // The mysqli_query() function executes a MySQL query
    	$result = mysqli_query($connect,"select* from user");
    	//mysqli_num_rows The number of rows in the result set, which is obtained from the call to mysql_query()
    	$count = mysqli_num_rows($result);
    	//If you pass a page, change it to an integer
    	$page = isset($_GET['page'])?(int)$_GET['page']:1;
    	//Number of displays per page
    	$num = 5 ;
    	//total pages
    	$total = ceil($count / $num);
    	if ($page<1) {
    		$page = 1;
    	}
    	if ($page>$total) {
    		$page = $total;
    	}
    	//Offset
    	$offset = ($page-1)*$num;
    	$sql = "select id,name,age from demo order by id asc limit $offset,$num";
    	$result = mysqli_query($connect,$sql);
	    	if ($result&&mysqli_num_rows($result)) {
	    		echo "<table border=1 cellspacing=0>";
	        while($row = mysqli_fetch_array($result)){
	            echo "<tr>";
	            echo "<td>".$row['id']."</td>";
	            echo "<td>".$row['name']."</td>";
	            echo "<td>".$row['age']."</td>";
	            echo "<tr/>";
	        }
	        echo'<tr>
	        		<td colspan="5">
	        			<a href="page.php?page=1">首页</a>
	        			<a href="page.php?page=' .($page-1). '">上一页</a>
	        			<a href="page.php?page=' .($page+1). '">下一页</a>
	        			<a href="page.php?page=' .$total. '">尾页</a>
	        			The current page is '.$page.' of '.$total.'
	        		</td>
	        	</tr>';
	        echo "</table>";

    	}else{
    		echo "No data";
    	}
    }
    //close the connection
    $close = mysqli_close($connect);
    if(!$close){
        die("Failed to close the database");
    }else{
        echo "Close successfully";
    }
?>

 

   configuration file

<?php
	//database server
	define('DB_HOST', 'localhost');
	//database username
	define('DB_USER', 'root');
	//database password
	define('DB_PWD', 'root');
	//data storage name
	define('DB_NAME', 'user');
	//character set
	define('DB_CHARSET', 'utf8');
?>

 

The effect diagram is as follows:

 

 

 

 

 

.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326155679&siteId=291194637