I have a table 'table' with following structure
ID LinkedWith
12 13
13 12
14 13
15 14
16 0
17 0
18 21
We are given an ID say "12" (or may be 15), with it we have to fetch all other related IDs.
Here 12 is linked to 13, 14 is linked to 13, and 15 is linked to 14 and so on. In our case, there are 4 IDs indirectly related, there could be many. For example, in above case we need the final result of IDS 12,13,14,15.
I have got this incomplete function, but couldn't think of further. I know we might need recursive function but not sure how to do that
function testFetchRelated($id){
$arrayIDs = array($id);
try{
$dbh = new PDOConfig("db_test");
$stmt = $dbh->prepare("SELECT * FROM table WHERE ID='".$id."' OR LinkedWith='".$id."'");
$stmt->execute();
if($stmt->rowCount()>0){
$fetch = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach($fetch as $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 anybody help me on this