我有以下代碼在一個頁面上只顯示10條記錄。當我第一次加載頁面時,前10條記錄顯示得很好(見截圖) 。但是當我點擊「Next 10 records」時,同一個URL不會使用$ _SERVER ['PHP_SELF']加載額外的GET參數。 我的地址欄顯示這個代替:PHP分頁不起作用
http://localhost/PHP/$_SERVER['PHP_SELF']?page=$page
這裏是我完整的代碼;
<?php
$con = @mysqli_connect("localhost:3306", "root", "[email protected]", "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>';
}
?>
變量沒有單引號的字符串 –