2016-07-28 61 views
0

前面和後面的鏈接我有一個頁面列出的客戶:PHP MySQL的 - 創建一個從當前客戶

/customers/ 

客戶在此頁面上的順序是不連續的:

1st: ID 111 
2nd: ID 567 
3rd: ID 345 
etc 

這是因爲SQL查詢讓用戶根據名字,姓氏或暱稱選擇客戶訂單。

"SELECT customer_id FROM customers WHERE status = 1 ORDER BY " . $customer_order 

所以,當我在第二屆客戶在我上面的例子:

/customer/567/ 

所以我的問題是,我想顯示一個和下一個按鈕這樣的,但無法弄清楚如何:

<a href="111">Prev</a> 
<a href="567">Current</a> 
<a href="345">Next</a> 

我設法讓上一個鏈接在while循環中工作,但它很醜。我嘗試使用current(),prev()和next()但失敗。

我在StackOverflow上看到的大多數解決方案都是使用順序標識符來處理當前標識爲-1或1的查詢,或者在查詢中它們是「限制1」,我相當確信在我的工作中不起作用測試完成後的情況。

任何想法?

+0

傳遞銅rrent客戶的ID到next/prev函數,並在db中尋找下一個。 用你的方式,你必須爲每條記錄做3次查詢。在我的方式中,如果你點擊上一個或下一個按鈕,你只需要做一個和最多兩個 –

回答

0

您可以將行號分配給您的查詢,並使用該行號來識別一個和下一個記錄:

SELECT (@row_number := @row_number + 1) AS row_number, customer_id 
FROM customers, (SELECT @row_number := 0) AS rn 
WHERE status = 1 
ORDER BY firstname 

如果您對當前客戶的行數,發現使用的下/上一紀錄主查詢作爲一個子查詢:

SELECT customer_id AS next_id 
FROM 
(
    SELECT (@row_number := @row_number + 1) AS row_number, customer_id 
    FROM customers, (SELECT @row_number := 0) AS rn 
    WHERE status = 1 
    ORDER BY firstname 
) ordered_customers 
WHERE ordered_customers.row_number = :current_row_number + 1 

如果你只是有電流id:

SELECT customer_id AS next_id 
FROM 
(
    SELECT (@row_number := @row_number + 1) AS row_number, customer_id 
    FROM customers, (SELECT @row_number := 0) AS rn 
    WHERE status = 1 
    ORDER BY firstname 
) ordered_customers 
WHERE ordered_customers.row_number = 1 + ( 
    SELECT row_number 
    FROM 
    (
     SELECT (@row_number2 := @row_number2 + 1) AS row_number, customer_id 
     FROM customers, (SELECT @row_number2 := 0) AS rn 
     WHERE status = 1 
     ORDER BY firstname 
    ) ordered_customers2 
    WHERE ordered_customers2.id = :current_id 
)