function fetch_Actor($ActorID){
global $pdo;
$stmt = $pdo->prepare('SELECT * FROM actors WHERE ActorID = ?');
$stmt->execute([$ActorID]);
return $stmt->fetch();
}
$actors = fetch_actor($actor['ActorID']);
foreach ($actors as $actor){
if($actor['ParentID'] > 0){
$actor = fetch_actor($actor['ParentID']);
}
}
The code above is something I wrote to override duplicate actors in my database. I believe what I am trying to do in php can be done with one statement in SQL. I just do not know where to begin. I am looking for some guidance on how to do this in one sql statement and get rid of my unnecessary foreach()
loop to fix stuff.
I am trying to include in my sql statment this condition:
if ParentID > 0 then fetch results using ParentID
else fetch results using ActorID
Table Structure
Actors
ActorID | Name | ParentID
1 | Abel | 0
2 | John | NULL
3 | Abel | 1
What I want to be returned if $ActorID = 1
Actors
ActorID | Name | ParentID
1 | Abel | 0
What I want to be returned if $ActorID = 2
Actors
ActorID | Name | ParentID
2 | John | NULL
What I want to be returned if $ActorID = 3
Actors
ActorID | Name | ParentID
1 | Abel | 0
I have tried this, but this does not seem to work:
IF((SELECT ParentID FROM actors WHERE ActorID = ?) > 0)
SELECT * FROM actors WHERE ParentID = ?
ELSE
SELECT ParentID FROM actors WHERE ActorID = ?