In my code I have this:
$im = $database->query("SELECT * FROM cms_messaggi_importanti WHERE messo_da = :id ORDER BY ID DESC", array("id"=>$functions->Utente("id")));
foreach($im as $imp){
$mex_i = $database->query("SELECT * FROM cms_messaggi WHERE id = :id ORDER BY ID DESC", array("id"=>$imp['id_mex']));
foreach($mex_i as $mex_imp){
}
}
Can I write this code in only one? Because I have to use a lot of variable with this method. Is there a solution to my problem? For example, using "JOIN"?
You can (and should) do your query in one go, and then iterate over those results:
$im = $database->query("
SELECT *
FROM cms_messaggi_importanti mi
LEFT JOIN cms_messaggi m ON m.id = mi.id_mex
WHERE messo_da = :id
ORDER BY mi.ID DESC,
m.ID DESC",
array("id"=>$functions->Utente("id")));
foreach($im as $imp){
//...
}
You will probably need to replace the SELECT *
by a more precise column list, which will be the columns available in the result set.