Reputation: 188
I work hierarchical categories and products table for my project.
categories table structure:
ID - PARENT - TITLE
1 - 0 - Computer
1 - 0 - Phones
...
Categories table count of row 25107.
Product Table structure
ID - CAT - TITLE
1 - 1 - Product Name is here
I want current category and sub categories for list product.
echo $subcats = categoryChild(0);
Output is: 64198,18355,18356,95623,90504,6118,90505,6117,90506,90507,6119,6120,90508,90509,90510,90511,6103,90512,90513,90514,90515,142686,142688,142790,90516,6105,90517,90518,90519,90520,90521,91691,91692,92189,92190,92312,92313,95618,95619,95620,95621,95622,142684,142690,142692,142694,142696,142698,142700,3596
And I'm using this output MySQL IN statment. Finally generate this SQL query:
SELECT * FROM products WHERE cat IN (64198,18355,18356,95623,90504,6118,90505,6117,90506,90507,6119,6120,90508,90509,90510,90511,6103,90512,90513,90514,90515,142686,142688,142790,90516,6105,90517,90518,90519,90520,90521,91691,91692,92189,92190,92312,92313,95618,95619,95620,95621,95622,142684,142690,142692,142694,142696,142698,142700,3596)
This query is very slow... Please help me.
Upvotes: 2
Views: 1774
Reputation: 1
use this will allow you to fetch cat and sub cat for the parent_id argument. its nested and can be style with css and html.
`
<ul class="" id="">
<?php
function query($parent_id, $extension = null) { //function to run a query
$query = mysql_query ( "SELECT * FROM exe_categories WHERE parent_id=$parent_id");
return $query;
}
function has_child($query) { //This function checks if the menus has childs or not
$rows = mysql_num_rows ( $query );
if ($rows > 0) {
return true;
} else {
return false;
}
}
function fetch_menu($query) {
while ( $result = mysql_fetch_array ( $query ) ) {
$id = $result ['id'];
$title = $result ['title'];
$menu_link = $result ['menu_link'];
echo "<li><a href='{$menu_link}'><span>{$title}</span></a>";
if (has_child ( query ( $id ) )) {
echo "<div>";
echo '<ul role="menu" class="fofc">';
fetch_menu ( query ( $id ) );
echo "</ul>";
echo "</div>";
}
echo "</li>";
}
}
fetch_menu (query(1)); //call this function with 1 parent id
?>`
Upvotes: 0
Reputation: 4066
try this:
select p.id as id, p.title as title, c.title as category, c.id as catid
from products p JOIN
(select * from category where id = 1 OR parent = 1) c
on p.cat = c.id
see how it works on SQLFIDDLE
to list all hierarchy levels, write a code like this:
// return all childs of category with id $cat
function list_childs($cat){
// run above query and change (select * from category where id = 1 OR parent = 1)
// to (select * from category where parent = $cat) and return results
}
then in your code call this function for every category where you want to get children's
Upvotes: 2