I have a table with products. Sub-products can be assigned to a main product.
products
________________________________________________________________________
id | product_title | main_id | owner_id
1 | Volvo | 0 | 1
2 | Mercedes | 0 | 2
3 | Chevrolet | 0 | 1
4 | Rear lights | 1 | 1
5 | Glasses | 1 | 1
6 | Seats | 1 | 1
7 | Heater | 1 | 1
8 | Radio | 6 | 1
12 | Tyres | 6 | 1
13 | Rearview mirror | 8 | 1
14 | Door | 8 | 1
15 | Engine | 14 | 1
15 | Door | 3 | 1
I use function get_the_list(id = 0, owner_id = 1);
function get_the_list(id = 0, owner_id = 1) {
$query = "SELECT * FROM products WHERE main_id = $id AND owner_id = $owner_id";
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$list .= $row[product_title];
// select sub products from main_id
$list .= get_the_list($row[main_id], 1);
}
}
echo get_the_list(id = 0, owner_id = 1);
On this way I get the whole product list. Works well, no problems.
(1) i: 1 --- loop: 1, 1 - Volvo
i: 1 --- loop: 2, 2 - Rear lights
i: 2 --- loop: 3, 2 - Glasses
i: 3 --- loop: 4, 2 - Seats
i: 1 --- loop: 5, 3 - Radio
i: 1 --- loop: 6, 4 - Rear-view mirror
i: 2 --- loop: 7, 4 - Door
i: 1 --- loop: 8, 5 - Engine
i: 2 --- loop: 7, 3 - Tyres
i: 4 --- loop: 6, 2 - Heater
____________________________
(2) i: 2 --- loop: 1, 1 - Chevrolet
i: 1 --- loop: 2, 2 - Door
____________________________
(3) i: 3 --- loop: 1, 1 - Mercedes
____________________________
(4) i: 4 --- loop: 1, 1 - XX
____________________________
First (number) is main_id. Second number is running $i++ in while. Third number should be continuous/ongoing counter. BUT this breaks after level 5. fourth number after comma is level.
I have to limit a select statement to only 8 products (incl. sub products). So I will end, for example, with rear-view mirror on this image example. It works. But it works not after more than 8, because the counter breaks.
How can I limit the number of products that can be retrieved, what select statement should I choose? OR WHAT php workaround?