Getting multiple results without query inside loop

I’m trying to improve the loading times of images and need to change around the code.

I haven’t had any luck finding out how to do this and I’m not sure if it is even possible. In the example below you can see that I use KEY to match it with U_KEY to get FILE_PATH which I then add to a long comma delimited $allPaths string.

I know I should not use queries inside loops but I have no idea how to change this.

<?php
$sql = "SELECT * FROM test_users, image_uploads LIMIT 0, 27";
$result = mysqli_query($mysqli, $sql);

while($value = mysqli_fetch_array($result)) {
    $files_key = $value["KEY"];
    $allPaths = "";
    
    $inner_query = "SELECT * FROM additional_uploads WHERE U_KEY = '".$files_key;
    $inner_result = mysqli_query($mysqli, $inner_query);
    
    while ($row = mysqli_fetch_array($inner_result)) {
        $allpaths .= $row['FILE_PATH'].",";
    }

    // how do I get $allPaths without using a query inside the while loop?
}
?>

If someone could tell me how I can get $allPaths with only one query instead of multiple queries inside the loop as shown above it would probably load the images much faster.

Is this possible?

Edit

I have tried to understand the problem using the suggested answer and additionally I was looking on other forums as well to find out more. However I still cannot find a solution. Since I’m using mysqli_fetch_array the suggested answer really confuses me even further.

Answer

<?php
$inner_query = "SELECT * FROM additional_uploads";
$inner_result = mysqli_query($mysqli, $inner_query);
$rows = [];

while ($row = mysqli_fetch_array($inner_result)) {
    $rows[$row['U_KEY']] .= $row['FILE_PATH'].",";
}

$sql = "SELECT * FROM test_users, image_uploads LIMIT 0, 27";
$result = mysqli_query($mysqli, $sql);

while($value = mysqli_fetch_array($result)) {
    $files_key = $value["KEY"];
    $allPaths = $rows[$files_key];
}
?>