I want find out the parent category id which category id is 0 ???????????????? my table : id name p_id 1 hotels 0 2 food 1 3 lunch 2 function find_pid($val) { $sqlfetch = mysql_query("select * from category_tb where id = '{$val}'"); $refetch = mysql_fetch_array($sqlfetch); if($refetch['p_id'] > 0) { find_pid($refetch['p_id']); } else { $cat = $refetch['id']; return $cat; } } echo find_pid(3); PHP: but here result is not display................... plz tell me what the problem, plz help me....................
Try this function find_pid($val) { $sqlfetch = mysql_query("select * from category_tb where id = '".$val."'"); while ($row = mysql_fetch_array($sqlfetch)) { if ($row['p_id'] == 0) { return $row['p_id']); } } return "failed to find a result with p_id == 0"; } PHP:
Hello, Your script doing several queries into database, it is not a good idea. You may make this with just a single query. SELECT t.id, t.name, @pv := t.p_id as p_id FROM (SELECT * FROM category_tb ORDER BY id DESC) t JOIN (SELECT @pv := YOUR_VAL_HERE) tmp WHERE t.id = @pv Code (markup): You will get several rows (full path) where the last one will be your parent element
Ah, I think what Sano000 is trying to say is that you could solve this with a much simpler query and just skip the loop and recursion like this $sqlfetch = mysql_query("SELECT * FROM category_tb WHERE id = '".$val."' AND p_id = 0"); Code (markup): This will give you all the rows that have your value and and have a p_id equal to 0
No, I trying to say, that you can make a recursivity on a Mysql server side. It will be faster and easier. Just add my query into mysql_query function and pop a last row.
how about this? function find_pid($val) { $sqlfetch = mysql_query("select * from category_tb where id = '{$val}'"); $refetch = mysql_fetch_array($sqlfetch); if($refetch['p_id'] > 0) { return find_pid($refetch['p_id']); } else { $cat = $refetch['id']; return $cat; } } PHP:
if @Sano000's approach scares you off and you know that there is only one layer of "parent" - ie not grandparent, great grandparent then you can try this $sql = "select Parent.* from category_tb as Parent, category_tb as Child where Child.p_id = Parent.id and Child.id = '{$val}'" PHP: and once you have that up and running look for a database handler script that will do nice things like return you an array of results and that doesn't use "depricated" functions like mysql_query