SitePoint Sponsor |
|
User Tag List
Results 1 to 4 of 4
Thread: Problem with recursive function
-
Aug 25, 2007, 18:52 #1
Problem with recursive function
I can't get my recursive function to append a variable ($sub_cats) each time a query is run.
CODE:PHP Code:$this_cat_id = $arg['category'];
function get_all_sub_cats ($this_cat_id, $sub_cats='') {
$sub_cats_result = mysql_query("SELECT category_id, category_parent FROM default_categories WHERE category_parent = '" . $this_cat_id . "'");
//echo $sub_cats_result;
if (@mysql_num_rows($sub_cats_result) >= 1) {
while ($sub_cat = mysql_fetch_array($sub_cats_result)) {
$this_cat_id = $sub_cat['category_id'];
$sub_cats .= $sub_cat['category_id'] . "','";
get_all_sub_cats ($this_cat_id, $sub_cats);
}
}
return $sub_cats;
}
$all_sub_cats = get_all_sub_cats ($this_cat_id, $sub_cats);
What am I doing wrong?
-
Aug 25, 2007, 20:08 #2
Actually, you're not using the returned value of your recursive function.
The code should be :
PHP Code:$this_cat_id = $arg['category'];
function get_all_sub_cats ($this_cat_id, $sub_cats='') {
$sub_cats_result = mysql_query("SELECT category_id, category_parent FROM default_categories WHERE category_parent = '" . $this_cat_id . "'");
//echo $sub_cats_result;
if (@mysql_num_rows($sub_cats_result) >= 1) {
while ($sub_cat = mysql_fetch_array($sub_cats_result)) {
$this_cat_id = $sub_cat['category_id'];
$sub_cats .= $sub_cat['category_id'] . "','";
$sub_cats .= get_all_sub_cats ($this_cat_id, $sub_cats);
}
}
return $sub_cats;
}
$all_sub_cats = get_all_sub_cats ($this_cat_id, $sub_cats);
-
Aug 25, 2007, 20:15 #3
that was it! thanks and welcome to SP.
eric
-
Aug 26, 2007, 01:27 #4
Functions are so much easier to understand and go though when you keep them simple. Also you should do some checking on the var that is being submitted.
PHP Code:function get_all_sub_cats ($id, $sub = '') {
// Sanity Check
if (!is_scalar($id)) { return -1; }
$id = mysql_real_escape_string(stripslashes((string)$id));
$results = mysql_query("SELECT category_id FROM default_categories WHERE category_parent = '" . $id . "'");
if (mysql_num_rows($results) > 0) {
while ($row = mysql_fetch_assoc($results)) {
$sub .= $sub_cat['category_id'] . "','";
$sub .= get_all_sub_cats($row['category_id'], $sub);
}
}
return $sub;
}
Bookmarks