I have a table called products in a MySQL database. products looks some what like this:
id name din strength active deleted
1 APA TEST 00246374 25 1 0
4 APA BOB 00246375 50 1 0
5 APA TIRE 00246888 50 1 0
7 APA ROT 00521414 100 1 0
9 APA APA 01142124 100 1 0
6 APA CODE 00121212 150 1 0
8 APA SERV 00011145 600 1 0
Obviously I’ve left out several columns not important to my question. When I query this table, I will be sorting by one of several different columns (The user interface allows individual users to change the sorting column and order), and I may have a search clause in which case I’ll do a LIKE clause on NAME and DIN.
What I want to know is, given the sorting info and search info, and the ID of a specific product (Say I searched for 004, which returned 3 results, and I am viewing one of them), how could I get the next and previous products?
I need to do this, because if a user clicks to edit/view one of the products after searching and sorting results, they want to be able to cycle through results without going to the previous page.
Is there a good and efficient way to do this in SQL, or am I best off using PHP? Any ideas are also welcome.
Currently using this SQL query, which is experiencing issues if I sort by the strength column as there are duplicate values
SELECT T.*
FROM `wp_products` T
INNER JOIN `wp_products` curr on curr.id = 38
AND ((T.strength = curr.strength and T.id < curr.id)
OR (T.strength > curr.strength))
WHERE T.active = 1 AND T.deleted = 0 AND (T.name LIKE '%%' OR T.din LIKE '%%')
ORDER BY T.strength ASC, T.id ASC
LIMIT 1
My PHP code (using WordPress) (Designed to get the next item)
$sql = 'SELECT T.*
FROM `' . $wpdb->prefix . 'apsi_products` T
INNER JOIN `' . $wpdb->prefix . 'apsi_products` curr on curr.id = ' . $item->id . '
AND ((T.' . $wpdb->escape( $query['orderby'] ) . ' = curr.' . $wpdb->escape( $query['orderby'] ) . ' and T.id > curr.id)
OR (T.' . $wpdb->escape( $query['orderby'] ) . ' > curr.' . $wpdb->escape( $query['orderby'] ) . '))
WHERE T.active = 1 AND T.deleted = 0 AND (T.name LIKE \'%' . $query['where'] . '%\' OR T.din LIKE \'%' . $query['where'] . '%\')
ORDER BY T.' . $wpdb->escape( $query['orderby'] ) . ' ' . $query['order'] . ', T.id ASC
LIMIT 1;';
You need to have a reference to the current record, and then progressively look for the next record based on the sorted columns. The example below assumes it is sorted on
First:
Next: (make sure you separate the
CURR.ID = 6and the AND-ORs with proper brackets!)A working sample presented below
If current is the row with ID=6, the next record can be retrieved using