php - How to perform couple of mysqli queries and add one result into existing result array?
Solution:
Use a JOIN in your query:
SELECT *
FROM movies_table m
INNER JOIN directors_table d ON d.director_id = m.dir_id
And build the array structure in your loop:
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = [
'id' => $r['id'],
'image' => $r['image'],
/* other movie keys you need */
'director' => [
'id' => $r['director_id'],
/* other director keys you need */
]
];
}
Answer
Solution:
Two solutions
Make a JOIN like @AymDev suggested in the first comment to your question. This might be the preferred solution if your tables are relatively small and you don't have any performance issues
Double query
// First retrieve all the directors and keep an array with their info. The Key of the array is the director ID
$dataQuery = "SELECT * FROM directors_table";
$sth = mysqli_query($conn, $dataQuery);
$directors = array();
while($r = mysqli_fetch_assoc($sth)) {
$directors[$r['id']] = $r;
}
$dataQuery = "SELECT * FROM movies_table";
$sth = mysqli_query($conn, $dataQuery);
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
// Retrieve the director info from the previous array
$r['director'] = $directors[$r['dir_id']];
$rows[] = $r;
}
$respObj->status = 'success';
$respObj->movies = $rows;
$respJSON = json_encode($respObj);
print $respJSON;
Source