php - Fetch all related parent and child ids by given ID -
i have table 'table' following structure
id linkedwith 12 13 13 12 14 13 15 14 16 0 17 0 18 21 we given id "12" (or may 15), have fetch other related ids.
here 12 linked 13, 14 linked 13, , 15 linked 14 , on. in our case, there 4 ids indirectly related, there many. example, in above case need final result of ids 12,13,14,15.
i have got incomplete function, couldn't think of further. know might need recursive function not sure how that
function testfetchrelated($id){ $arrayids = array($id); try{ $dbh = new pdoconfig("db_test"); $stmt = $dbh->prepare("select * table id='".$id."' or linkedwith='".$id."'"); $stmt->execute(); if($stmt->rowcount()>0){ $fetch = $stmt->fetchall(pdo::fetch_obj); foreach($fetch $f){ if($f->linkedwith>0){ array_push($arrayids, $f->linkedwith); } if($f->id!=$id){ array_push($arrayids, $f->id); } } }else{ } $stmt = null; $dbh = null; return $arrayids; }catch(pdoexception $e){ echo "an error occurred: ".$e->getmessage(); } can me on this
i have knocked seem want in mysql procedure:-
delimiter ;; drop procedure if exists `find_relations`;; create procedure `find_relations`(in_id int) begin create table ids_tmp ( id int(11), primary key (id) ); insert ids_tmp select a.id some_table a.linkedwith = in_id union select a.linkedwith some_table a.id = in_id union select a.linkedwith some_table a.linkedwith = in_id union select a.id some_table a.id = in_id; while (row_count() > 0) insert ids_tmp select a.id some_table inner join ids_tmp b on a.linkedwith = b.id left outer join ids_tmp c on a.id = c.id c.id null union select a.id some_table inner join ids_tmp b on a.id = b.id left outer join ids_tmp c on a.linkedwith = c.id c.id null; end while; select id ids_tmp; drop table if exists ids_tmp; end;; delimiter ; you can invoke using call find_relations(12);
not full debugged (it better use temporary table, relies on accessing same table multiple times in various single queries, mysql doesn't support temp tables), give ideas.
if want use need ensure created table has name unique session.
Comments
Post a Comment