我有以下代码在一个页面上只显示10条记录。当我第一次加载页面时,前10条记录显示良好(见截图) 。但是,当我点击"接下来的10条记录"时,使用$ _SERVER [' PHP_SELF']不会使用额外的GET参数加载相同的URL。 我的地址栏显示了这一点:
http://localhost/PHP/$_SERVER['PHP_SELF']?page=$page
这是我的完整代码;
<?php
$con = @mysqli_connect( "localhost:3306", "root", "P@ssw0rd", "world" ) or die ("Couldn't connect to server");
//get total number of records
$query = "SELECT count(ID) FROM city";
$result = mysqli_query ( $con, $query) or die ("Couldn't execute SELECT query: ". mysqli_error($con));
$rec_count = mysqli_num_rows($result);
$rec_limit = 10; //number of records to display
if( isset($_GET['page']) ){ //when user clicks link
$page = $_POST['page'] + 1; //page count increment by 1
$offset = $rec_limit * $page;
}
else{ //user has not yet clicked any link
$page = 0;
$offset = 0;
}
//xxxxxxxx $rec_count is taken from result set
$left_rec = $rec_count - ($page * $rec_limit); //number of records remaining to display
$display_query = "SELECT * FROM city LIMIT $offset, $rec_limit";
$display_result = mysqli_query ( $con, $display_query) or die ("Couldn't execute SELECT query: ". mysqli_error($con));
echo "<table>";
echo "<th>ID</th> <th>Name</th> <th>Country Code</th> <th>District</th> <th>Population</th>";
while( $row = mysqli_fetch_assoc($display_result) ){
extract($row);
echo "<tr>
<td>$ID</td>
<td>$Name</td>
<td>$CountryCode</td>
<td>$District</td>
<td>$Population</td>
</tr>";
}
echo "</table>";
if( $page == 0 ){ //user has not yet clicked any link
echo '<a href="$_SERVER[\'PHP_SELF\']?page=$page"> Next 10 records </a>';
}
else if( $page>0 ){ //user has clicked at least once on link
$last = $page - 2; //here -2 because, in isset block again increment by 1
echo '<a href='. $_SERVER['PHP_SELF']. '?page=$last> Last 10 records </a>';
echo '<a href='. $_SERVER['PHP_SELF']. '?page=$page> Next 10 records </a>';
}
else if( $left_rec < $rec_limit ){ //when only records less than 10 remains
$last = $page - 2;
echo '<a href='. $_SERVER['PHP_SELF']. '?page=$last> Last 10 records </a>';
}
&GT;
答案 0 :(得分:1)
echo '<a href="'. $_SERVER['PHP_SELF']. '?page='.$page.'"> Next 10 records </a>';
和$ last相似。
答案 1 :(得分:1)
if( $page == 0 ){ //user has not yet clicked any link
echo '<a href="'.$_SERVER['PHP_SELF'].'?page='.$page.'"> Next 10 records </a>';
}
这将修复您的单引号和双引号,并将回显值而不是变量。您必须对所有输入应用相同的逻辑。 你也可以这样做:
if( $page == 0 ){ //user has not yet clicked any link
echo "<a href=\"{$_SERVER['PHP_SELF']}?page=$page\"> Next 10 records </a>';
}