-2

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"?

Prafulla Kumar Sahu
  • 9,321
  • 11
  • 68
  • 105
  • 5
    Yes the solution is to use join – e4c5 Sep 08 '16 at 14:44
  • @e4c5 you can give me an example? I'm not very practical.. – JohnAnderlon Sep 08 '16 at 14:45
  • There are many MySQL guides and tutorials out there that will teach you how to write a simple JOIN. You should take the time to actually learn what you're doing instead of just copy/pasting what someone else gives you. – Patrick Q Sep 08 '16 at 14:46
  • Duplicate: http://stackoverflow.com/questions/32061254/how-can-i-loop-through-two-arrays-at-once – Tommy Sep 08 '16 at 14:48

1 Answers1

0

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.

trincot
  • 317,000
  • 35
  • 244
  • 286