2012-03-14 124 views
-1

好吧,我會粘貼我的代碼在這裏,就像一個人選擇一個類別,然後他登陸到另一個頁面,現在這裏的問題是因爲mysql_fetch_rows選擇所有類別的所有行,所以如果有10個條目,每個類別5個,並且如果我設置爲每個頁面顯示1個帖子而不是顯示5個頁面,則顯示10個頁面,但是在頁面5之後,我得到一個php錯誤。感謝您將n這裏是我的代碼PHP變量值爲分頁

$pagination_shoot = "SELECT id, po_title, po_category FROM tbl_posts WHERE po_category = '{$category}'"; 

$page_dump = mysql_query($pagination_shoot, $db_connect); 

$no_rows = mysql_fetch_row($page_dump); 

$numrows = $no_rows[0]; 

$rows_per_page = 1; 

$lastpage = ceil($numrows/$rows_per_page); 

$page = (int)$page; 

if ($page > $lastpage) { 
$page = $lastpage; 
} // if 

if ($page < 1) { 
$page = 1; 
} // if 

$limit = 'LIMIT ' .($page - 1) * $rows_per_page .',' .$rows_per_page; 

//Run Post Query 
$data_posts = "SELECT id, po_title, po_category FROM tbl_posts WHERE po_category = '{$category}' {$limit}"; //Post Query 

$fetch_data_posts = mysql_query($data_posts, $db_connect); 

while ($list_posts = mysql_fetch_array($fetch_data_posts)) 
+0

它在我看來好像您可能正在運行一個啓用了'register_globals'的服務器。如果你是[關閉](http://php.net/manual/en/security.globals.php)。 – DaveRandom 2012-03-14 13:09:18

+0

如果我刪除條件腳本工作正常,但唯一的問題是它無法檢測哪個類別具有多少行 – PHPSrike 2012-03-14 13:09:50

回答

0

字裏行間,我認爲你正在試圖做的是獲取從該數據庫中的特定頁面的結果,而知道多少結果總共有,這樣你就可以算出將會有多少頁面。這是使用SQL_CALC_FOUND_ROWS的正確方法:

// Populate these variables however you see fit (eg through $_GET) 
$rows_per_page = 1; 
$current_page = 1; 

// ----------- 

// Make sure the page number is >= 1 
$current_page = (int) $current_page; 
if ($current_page < 1) $current_page = 1; 

// Calculate values for LIMIT clause 
$limitQty = (int) $rows_per_page; 
$limitBase = ($current_page - 1) * $limitQty; 


// Run the query 
$query = " 
    SELECT SQL_CALC_FOUND_ROWS 
    `id`, `po_title`, `po_category` 
    FROM `tbl_posts` 
    WHERE `po_category` = '".mysql_real_escape_string($category, $db_connect)."' 
    LIMIT $limitBase, $limitQty 
"; 
$result = mysql_query($query, $db_connect); 

// Store the results in an array and free the MySQL resource 
$data_posts = array(); 
while ($row = mysql_fetch_array($result)) { 
    $data_posts[] = $row; 
} 
mysql_free_result($result); 

// Get the total number of rows 
$query = " 
    SELECT FOUND_ROWS() 
"; 
$result = mysql_query($query, $db_connect); 
$numrows = mysql_fetch_row($result); 
$total_rows = $numrows[0]; 
mysql_free_result($result); 

// Calculate the total number of pages 
$total_pages = ceil($total_rows/$rows_per_page); 

if ($current_page > $total_pages) { 
    // Handle a request that asked for a page which is greater than the total number of pages 
    // You could display an error message, redirect to a page within range, or run another query 
    // to fetch the rows for the last page. 
} 

// Now you can loop the data results and do whatever you want with them 
foreach ($data_posts as $list_posts) { 
    // ... 
}