PHP Mysql - 从当前客户创建上一个和下一个链接

时间:2016-07-28 08:04:24

标签: 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>

我设法让Previous链接在while循环中工作,但它很难看。我尝试使用current(),prev()和next()但是失败了。

我在StackOverflow上看到的大多数解决方案都与顺序ID有关,其中它们是-1或1当前ID,或者它们是&#34; LIMIT 1&#34;在我测试之后,我相当确定在我的情况下无法工作的查询。

有什么想法吗?

1 个答案:

答案 0 :(得分: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
)