Since a few weeks I use prepared statements in PHP with the fetch_object(className:: class)
. I really like this way because of the autocomplete in my controllers and in my view(Twig), but some times I need an inner join (One to many).
Now I do it like below. Luckily I have only a few results in the projects where I use this so the number of queries is low. But on a large result, this will create a lot of queries. To improve performance I store the $returnResult in apcu / Redis in the controller or save it in a JSON file when I can't use the other cache method.
My question is: can I do this on a better way to reduce the number of queries but still use the fetch_object(className:: class)
Thanks in advance for the help.
public function getAll()
{
// Create database connection
$db = DB::connect();
$stmt = $db->prepare("SELECT * FROM dataroom_category ORDER BY display_order");
$stmt->execute();
$returnResult = [];
$categoryResult = $stmt->get_result();
$stmt2 = $db->prepare("SELECT * FROM dataroom_file WHERE dataroom_category_id = ? ORDER BY display_order");
$stmt2->bind_param('i', $id);
/** @var data $category */
while ($category = $categoryResult->fetch_object(data::class)) {
$id = $category->getId();
$stmt2->execute();
$filesResult = $stmt2->get_result();
while ($file = $filesResult->fetch_object(DataroomFile::class)) {
// Add the file to the setFiles array with $file->getid() as key
$category->setFiles($file);
}
// I noticed by using mysqli_free_result the server used alot less memory at the end
mysqli_free_result($filesResult);
$returnResult[$category->getId()] = $category;
}
mysqli_free_result($categoryResult);
$stmt2->close();
$stmt->close();
// Return the categories with the files for usage in the controller and view
return $returnResult;
}