I have three tables which look like this (simplified)
"plants" Table
ID (PK, AI) | botanicalName | quickCode
1 | Monstera adansonii | 1234567
2 | Aloe Vera | 1233456
"commonNames" Table
ID (PK, AI) | plantsID | commonName
1 | 1 | Swiss Cheese Vine
2 | 2 | Cape Fern
3 | 1 | Hurricane Plant
"images" Table
ID (PK, AI) | plantsID | fileName
1 | 1 | monstera_adansonii.jpg
2 | 2 | capefern.jpg
3 | 2 | capefern2.jpg
In "commonNames" and "images" tables the "plantsID" columns are references to the ID in "plants" table.
How could I write my MySQL Select and php to format a result like this:
array (
id => 1, //plants.id
botanicalName => Monstera adansonii, //plants.botanicalName
commonNames => array ( 0 => Swiss Cheese Vine, 1 => Hurricane Plant ), //commonNames.commonName (array)
fileName => array ( 0 => monstera_adansonii.jpg ) //images.fileName (array),
)
2
Answers
I would like to offer the following solution:
Select all plants and save result to $plants variable
SELECT ID as id, botanicalName FROM plants;
Use the loop and add key
commonNames
andfileName
foreach(plants as &$plant){
}
SQL1
SELECT ID as id, commonName FROM commonNames WHERE plantsID = {$plant[‘id’]};
SQL2
SELECT ID as id, fileName FROM images WHERE plantsID = {$plant[‘id’]};
I would use one query with GROUP_CONCAT for commonNames and fileName. Then loop through results and explode those fields. Something like that:
Let’s say the query returns results into $plants so then you would do:
Please note that this is all hand written without syntax check.