-2

Hie. I am trying not to place an SQL query inside a loop, since this improves performance. I think I am supposed to use implode. But can't figure out how to do it. Here is my code:

<?php 

//FUNCTION CONNECTNG TO DB HERE

function turn_result_to_array($result)
{
   $result_array = array();

   for ($count=0;  $row = mysql_fetch_array($result); $count++)
   {
      $result_array[$count] = $row;
   }
   return $result_array;
}


function get_sender_username()
{
   //connect to DB 

   $query = sprintf("SELECT DISTINCT sender FROM direct_messages
                                    WHERE receiver_username='%s'
                        ORDER BY direct_messages.id DESC", 
                   mysql_real_escape_string($_COOKIE['username']));

   $result = mysql_query($query);

   $result = turn_result_to_array($result);

   return $result;

}

$senders = get_sender_username(); 

foreach($senders as $sender)
{ //SELECT IMAGE(S) FROM USER TABLE WHERE USERNAME = $SENDERS }

Instead of putting the query inside the FOREACH, i want to put it after, so i don't make multiple round trips to the database. FYI i already know that we supposed to switch to PDO. Thanks in advance.

2 Answers2

0

Here is one way of doing it:

$senderInString = implode("','",$senders);
$senderInString = "('$senderInString')";
$newQuery = "SELECT something FROM tables WHERE sender in $senderInString;"
$newResult = mysql_query($newQuery);
Adam Erstelle
  • 2,454
  • 3
  • 21
  • 35
0

Use

      $query= "SELECT IMAGE(S) FROM USER TABLE WHERE USERNAME  IN (".implode(',',$senders).")";
      $result = mysql_query($query);

In the place of foreach

Shijin TR
  • 7,516
  • 10
  • 55
  • 122