I have this code which hits a view in mysql called vAlbums this returns a JSON array of the query results
function getAlbumPics($arno){
$aSql = "SELECT albu_ablumid, albu_name_en, albu_name_de, albu_name_fr, albu_name_nl, albu_name_es, albu_name_it, albu_photourl FROM vAlbums WHERE site_arno=:arno";
try {
$db = getConnection();
$aStmt = $db->prepare($aSql);
$aStmt->bindParam(":arno",$arno);
$aStmt->execute();
$albums = $aStmt->fetchAll(PDO::FETCH_OBJ);
$arrAID = $aStmt->fetchColumn(2);
$db = null;
echo '{"albums": ' . json_encode($albums) . '}';
} catch(PDOException $e) {
echo '{"error":[{"text":"'. $e->getMessage() .'"}],';
echo '"SQL": ' . json_encode($aSql) .'}';
}
}
I need to do a sub query to place an array of photos in each album in the array like thus
{
"albums": [
{
"albu_ablumid": "1",
"photos": [
{
"photourl": "photo1"
},
{
"photourl": "photo2"
},
{
"photourl": "photo3"
}
]
},
{
"albu_ablumid": "2",
"photos": [
{
"photourl": "photo1"
},
{
"photourl": "photo2"
},
{
"photourl": "photo3"
}
]
}
]
}
Can someone show how to achieve this the MySQL query for photos is:
SELECT * FROM photos WHERE album_id = x
Thanks
Why not just do a join and group concat in a single query?
This will return all the photos in a comma separated string in each row that matches the album. You can then easily split it up as needed in your code. It saves a lot of connections and multiple queries being run.
Here is a little example from my play db to show how it functions:
and with some simple code to take care of the NULLs if you need to for some reason: