Q: php recursive function not working correctly i have a categories table
(id=1 , name=Hand made, parent=0)
(id=2 , name=Factory made, parent=0) 
(id=3 , name=chairs, parent=1) 
(id=4 , name=tabels, parent=1) 
(id=5 , name=old chairs, parent=3) 
at the menu if visitor clicked on category OLD CHAIRS , will go to page
products.php?category_id = 5 
then at this page i need to know what is the main category_id , which should be HAND MADE with category_id=1 
so at this page i want to say 
if isset($_REQUEST['category_id']){ 
do the function till find the main parent, 
$mainparentid = main parent category_id 
}else { $mainparentid = ''; 
} echo $mainparentid; 

here is my PHP Code
if (isset($_REQUEST['category_id'])) {

    function getParent($id) { 
      global $connection;   
      $query_rsCategoryId = "SELECT * FROM categories 
      WHERE category_id = '".$_REQUEST['category_id']."'";
      $rsCategoryId = mysql_query($query_rsCategoryId, $connection);
      $row_rsCategoryId = mysql_fetch_assoc($rsCategoryId);
      $parent = $row_rsCategoryId['category_parent'];
      if (mysql_num_rows($rsCategoryId) < 1) {
        // Error handling, entry with id $id not found
        return null;
      }
      if ($parent == 0) {
        return $id;
      } else {
        return getParent($parent);
      }
    }
$mainparentid = getParent($id);

}else {

    $mainparentid ='none';
}
echo $mainparentid ;


A: You always input ID of the category from $_REQUEST. Change line:
WHERE category_id = '".$_REQUEST['category_id']."'";

to:
WHERE category_id = '".$id."'";


A: You are using parent id from request instead of given via function parameter
  // notice $id instead of $_REQUEST['category_id']
  $query_rsCategoryId = "SELECT * FROM categories WHERE category_id = '{$id}'";

