I have 2 tables in my DB, Polyptychs and Illustrations. The PK of Polyptychs is FK in Illustrations. What I want to do is:
SELECT polyptychID FROM Polyptychs
and subsequently, foreach ID returned I need all illustrations. Via PHP the solution is something like this(using PDO sintax):
<?php
//create the connection with DB
$sql = "SELECT polyptychID, polyptych_image FROM Polyptychs";
$stmt = $this->DBH->query($sql);
$resultTmp = $stmt->fetchAll(PDO::FETCH_ASSOC);
$final_result = array();
foreach($resultTmp as $val){
$id = $val['polyptychID'];
$final_result["$id"]["image"] = $val['polyptych_image'];
$sql2 = "SELECT * FROM Illustrations WHERE polyptychID = :polyID";
$stmt2 = $this->DBH->prepare($sql2);
$stmt2->execute(array('polyID' => $id));
$resultTmp2 = $stmt2->fetchAll(PDO::FETCH_ASSOC);
$final_result["$id"]["illustrations"] = $resultTmp2;
unset($id);
unset($sql2);
unset($stmt2);
unset($resultTmp2);
}
?>
Now $final_result
contains all polyptychID
as key of the array and its relative image and illustrations (if there's no error in the code).
What I want to know is if there is an easier way to get it, maybe doing it via SQL, and what is the best solution.
Thanks