2016-05-26 99 views
0

我有以下代碼在一個頁面上只顯示10條記錄。當我第一次加載頁面時,前10條記錄顯示得很好(見截圖) first load 。但是當我點擊「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>'; 
} 

?>

+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>'; 
} 
+0

先生,我試過你的第一個解決方案。它運作良好。謝謝。但我有兩個問題:1)第二種解決方案中的{}是什麼。爲什麼使用? 2)我們不能在單引號內引用一個變量嗎?據我所知,可能在雙引號內?我是PHP新手。 –

+0

花括號用於將數組項封裝在雙引號括起來的字符串中。要使用單引號來包裝字符串,需要變量級聯。雙引號和單引號的行爲有所不同。注意:如果答案解決了問題,請將其標記爲已解決。謝謝 –

1
echo '<a href="'. $_SERVER['PHP_SELF']. '?page='.$page.'"> Next 10 records </a>'; 

而類似$最後。

+1

你缺少周圍href的值雙引號內插 –

+1

雙引號是不是這裏的問題,而是$變量。但好的,我也修正了雙引號。 – nospor

+1

什麼是$變量?問題是在報價中,但你不能解決一方解開其他:) –