-2

喂。我试图不将 SQL 查询放在循环中,因为这可以提高性能。我想我应该使用内爆。但不知道该怎么做。这是我的代码:

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

我不想将查询放在 FOREACH 中,而是将其放在后面,所以我不会多次往返数据库。仅供参考,我已经知道我们应该切换到 PDO。提前致谢。

4

2 回答 2

0

这是一种方法:

$senderInString = implode("','",$senders);
$senderInString = "('$senderInString')";
$newQuery = "SELECT something FROM tables WHERE sender in $senderInString;"
$newResult = mysql_query($newQuery);
于 2013-04-03T13:32:36.697 回答
0

利用

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

代替 foreach

于 2013-04-03T13:34:19.650 回答