Product table:
id | id_parent | margin
------------------------
1 | NULL | 10
2 | 1 | 20
3 | NULL | 15
4 | 2 | 10
5 | 4 | 25
From data above, how to get margin total of product tree (id: 5)? It doesn't have fixed depth, it is dynamic.
I currently achieve this with iteration from PHP (recursive mysqli_query), but it consumes huge hosting memory (error 508).
Here is the PHP function:
function get_margintotal($product) {
global $link;
$query = "SELECT id_parent, margin FROM `products` WHERE id = ".$product['id_parent'];
if (!$temp_products = mysqli_query($link, $query)) {
die(json_encode(array("errmsg" => "Selecting supplier's margin.")));
}
$temp_product = mysqli_fetch_assoc($temp_products);
$temp_product['margin'] = $product['margin'] + $temp_product['margin'];
if (isset($temp_product['id_parent'])) {
return get_margintotal($temp_product);
}
else {
return $temp_product['margin'];
}
}
So I'm wondering if dynamic iteration can be done in MySQL or how to optimise the function to decrease server memory usage?
Thank you.